@north-light/cli 0.3.782 → 0.3.783

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 (45) hide show
  1. package/dist/api/contract.d.ts +1 -1
  2. package/dist/api/contract.js +1 -1
  3. package/dist/api/dto/charges.d.ts +3 -3
  4. package/dist/api/dto/charges.js +1 -1
  5. package/dist/builtin-memory/crouter-sdk/release-notes.md +6 -0
  6. package/dist/builtin-memory/internal/marketplaces.md +1 -1
  7. package/dist/builtin-memory/internal/storage-tiers.md +1 -1
  8. package/dist/cli.js +2 -8
  9. package/dist/clients/attach/viewer.js +526 -526
  10. package/dist/commands/pkg/account-installs.d.ts +9 -0
  11. package/dist/commands/pkg/account-installs.js +1 -0
  12. package/dist/commands/sys/setup-core.d.ts +1 -52
  13. package/dist/commands/sys/setup-core.js +6 -6
  14. package/dist/commands/sys/setup-wizard.d.ts +4 -9
  15. package/dist/commands/sys/setup-wizard.js +2 -1
  16. package/dist/commands/sys/setup.js +1 -1
  17. package/dist/commands/sys/signin.js +6 -3
  18. package/dist/core/grants/sync.js +1 -1
  19. package/dist/core/ledger/check.d.ts +6 -2
  20. package/dist/core/ledger/check.js +1 -1
  21. package/dist/core/llm/run.js +2 -2
  22. package/dist/core/runtime/first-run-offer.d.ts +2 -6
  23. package/dist/core/runtime/first-run-offer.js +2 -10
  24. package/dist/core/runtime/front-door.js +8 -9
  25. package/dist/core/runtime/start-refusal-notice.d.ts +5 -0
  26. package/dist/core/runtime/start-refusal-notice.js +1 -0
  27. package/dist/core/scoped-state/seed-terminal-defaults.d.ts +2 -0
  28. package/dist/core/scoped-state/seed-terminal-defaults.js +1 -0
  29. package/dist/daemon/cron-run.js +2 -2
  30. package/dist/daemon/fleet.js +5 -5
  31. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  32. package/docs/sdk/release-notes.md +6 -0
  33. package/package.json +3 -3
  34. package/packages/crouter-api/dist/api/contract.js +1 -1
  35. package/packages/crouter-api/dist/api/dto/charges.js +1 -1
  36. package/packages/crouter-api/package.json +1 -1
  37. package/packages/crouter-identity/package.json +1 -1
  38. package/packages/crouter-plugin/package.json +3 -3
  39. package/runtime.lock.json +14 -14
  40. package/dist/commands/sys/panels/plugin-env-panel.d.ts +0 -19
  41. package/dist/commands/sys/panels/plugin-env-panel.js +0 -2
  42. package/dist/commands/sys/panels/plugins-panel.d.ts +0 -16
  43. package/dist/commands/sys/panels/plugins-panel.js +0 -1
  44. package/dist/core/runtime/front-door-login.d.ts +0 -2
  45. package/dist/core/runtime/front-door-login.js +0 -1
@@ -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{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(`
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 $e,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 Ce,isManagedProvider as N,markSubscriptionRateLimited as et,markSubscriptionSuccess as tt,readSubscriptionPool as Ie,retryAfterMsFromHeaders as we,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 be}from"../provider-error-recognition.js";import{isSafetyRefusal as ut}from"./refusal.js";import{findRefusal as ct,payerOf as Oe,refusalError as ft,refusedMark as mt,writeCharge as ve}from"../ledger/index.js";import{storedApiKey as De}from"../auth-file.js";import{directoryIssuer as ie}from"../directory/issuer.js";import{eligibleHostedEndpoint as pt}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=be({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 sn(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(sn,"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{...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};
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 $t(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($t,"hostedModel");function St(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(St,"usdEquivalent");function Ct(e,t){return e.compat?.allowedFallbackModels?.find(s=>s.provider===e.provider&&s.model===t)}l(Ct,"allowedFallback");function dn(e){return e?{payer:e.payer,sub:e.sub,grantee:e.grantee,inference_endpoint:e.inference_endpoint??null}:void 0}l(dn,"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 It=/\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||!It.test(t)))return new i(404,"model_unavailable",t,void 0,{served_model:o})}l(Et,"codexAccountModelRejection");function Ot(e){return e.get("request-id")??e.get("x-request-id")}l(Ot,"vendorRequestId");async function ln(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 S=Ve(y.model);return S?[{routeId:"app",credentialSource:"app",family:"app",strength:y.strength,...S,rank:b}]:[]}),q=q.filter(y=>vt(R,e,y))):q=await kt(R,e,s);const ae=!_&&d!==void 0&&w!==null?await pt():null,se=ae===null?void 0:bt(e,q,ae),Ue=se?ae:null;se&&(q=[...q,se]);const Ke=_?new Set:Xe(),ke=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:ie()===null?null:`${ie()}/account/pay`,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 ke();const H=`chatcmpl-${He()}`;let P=1/0,F=1/0,de,v,le,ue;const G=new Set,ce=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!==$e&&N(y.providerId)){const k=await Ie(y.providerId);k.length>0&&k.every(A=>A.authFailure)&&G.add(y.providerId)}continue}const S=b?$t(R,y.modelId):R.find(y.providerId,y.modelId);if(!S)continue;const z=b?Ue.base_url:void 0,u=_?{...S,baseUrl:`${_.base_url}/${S.provider}`}:z?{...S,baseUrl:`${z}/anthropic`,compat:{...S.compat,allowedFallbackModels:void 0}}:S,h=y.providerId,V=y.credentialSource===$e&&N(h),fe=!r&&!b&&!V&&N(h)?await Ie(h):[],L=fe.filter(k=>!k.authFailure),xe=L.filter(k=>Ce(k,u.id)<=Date.now()),T=V?await De(h):Ke.has(h)?void 0:fe.length?await De(h):void 0;if(V&&T===void 0)continue;if(fe.length>0&&L.length===0&&T===void 0){N(h)&&G.add(h);continue}if(L.length&&!xe.length&&T===void 0){const k=Math.min(...L.map(c=>Ce(c,u.id)));k<P&&(P=k,le=`${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 Re=r||b?[void 0,void 0]:V?["key"]:L.length||T!==void 0?[...xe,...T!==void 0?["key"]:[]]:[void 0];let qe=!1;for(const[k,A]of Re.entries()){if(qe&&A!=="key")continue;const c=A==="key"?void 0:A,C=A==="key",Y=Date.now();let Ae=c?.access;if(c&&c.expires<=Date.now()&&N(h))try{Ae=await qt(R,h,c,`${u.provider}/${u.id}`,t)}catch(n){if(!Qe(n))throw n;de??=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,me=d?.environmentPayer,j=b?w===null?null:{payer:me??w,funding:"endpoint"}:r?Oe({call:"model",route:"endpoint",grantee:r.grantee,environmentPayer:me}):w===null?null:Oe({call:"model",route:c?"subscription":"key",sub:w,environmentPayer:me});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 ve({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 ce(),refused:mt(n)}),ue??=n,A!=="key"&&Re.includes("key")){qe=!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,je=!1,g,X,Z,I=!1,M,Q=null,$=3e4,B;const pe=[],he=[],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=>{pe.push(n),o?.(n)},"emit"),Be=ze(u,We,{apiKey:O?.access_token??Ae??(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 je=!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&&(I=!0,B=p.headers,$=we(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&&(I=!0,B=n.headers,$=we(n.headers)??15e3)},"onResponse")});try{for await(const n of Be)n.type==="text_delta"&&(he.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=be({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(!I&&p.kind!=="rate-limit")throw pe.length?new i(503,"upstream_model_unavailable",n instanceof Error?n.message:String(n),void 0,{served_model:f}):n;I=!0,$=m??$}}if(b){if(je)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(I&&we(B)===void 0)throw new i(503,"upstream_model_unavailable",`${f} was rate-limited without a retry-after`,void 0,{served_model:f});if(!I&&(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(!I&&a?.stopReason==="error"&&be({message:a.errorMessage}).kind==="rate-limit"&&(I=!0,$=15e3),I){const n=it(B,u.id,$),{observation:m,vendorReset:p}=n;if($=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=${$} headers=${JSON.stringify(m.headers)}`),c&&N(h)&&await et(h,c.label,$,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($,Se)<P&&(P=Date.now()+Math.min($,Se),le=f),he.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=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 _e=a.content.filter(n=>n.type==="toolCall").map(n=>({id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.arguments)}})),ye=oe?"content_filter":a.stopReason==="toolUse"?"tool_calls":a.stopReason==="length"?"length":"stop",ge=a.responseModel?Ct(u,a.responseModel):void 0,E=X?`${u.provider}/${X.served_model}`:ge?`${u.provider}/${ge.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(ge??u,a.usage.cost.total),served_model:E};b?d!==void 0&&j!==null&&await ve({id:W,request:d.request??H,kind:"model",what:E,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 ce(),vendorRef:Q}):d!==void 0&&j!==null&&await ve({request:d.request??H,kind:"model",what:E,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 ce(),vendorRef:Q});const Me={id:H,object:"chat.completion",created:Math.floor(Y/1e3),model:E,served_model:E,requested_model:K,substituted:K!==E&&!/^([^/]+)\/(ultra|strong|medium|light)$/.test(K),choices:[{index:0,message:{role:"assistant",content:he.join("")||null,...ee.length?{reasoning_content:ee.join("")}:{},..._e.length?{tool_calls:_e}:{},...oe?{refusal:a.errorMessage??"Content filtered"}:{}},finish_reason:ye}],usage:re,...e.metadata!==void 0?{metadata:e.metadata}:{}};for(const[n,m]of _e.entries())ne(te({tool_calls:[{index:n,...m}]}));return ne({...te({},ye),model:E,served_model:E,substituted:Me.substituted,...oe?{choices:[{index:0,delta:{},finish_reason:ye,message:{refusal:a.errorMessage??"Content filtered"}}]}:{},usage:re}),{completion:Me,chunks:pe}}}throw ue!==void 0?ft(ue):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:ie()===null?null:`${ie()}/account/pay`,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}`:le,...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):de!==void 0?de: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 ke()}l(ln,"runLlm");export{qt as freshSubscriptionAccess,dn as llmCallerOf,sn as parseLlmRequest,ln as runLlm,St as usdEquivalent};
@@ -1,14 +1,10 @@
1
- /** The first message on a computer not yet signed in to Northlight: the tour and sign-in offered together. */
2
- export declare const FIRST_RUN_OFFER_SENTENCE = "Want a quick tour of how this works? I can also sign you in to Northlight, so I can use your apps like Gmail and Slack, search the web and text you. Say which, or just tell me what you're working on.";
3
- /** The first message on a computer already signed in: the tour alone. */
1
+ /** The first message after setup: the tour offer. */
4
2
  export declare const FIRST_RUN_TOUR_SENTENCE = "Want a quick tour of how this works? Say yes, or just tell me what you're working on.";
5
3
  /** The prompt the front door gives a freshly booted root, and whether the
6
4
  * viewer should play the initial-whip animation (only for a prompt the user
7
- * typed). `signedIn` is whether this computer's records already live in a
8
- * Northlight account. */
5
+ * typed). */
9
6
  export declare function frontDoorBootPrompt(facts: {
10
7
  offerTour: boolean;
11
- signedIn: boolean;
12
8
  userPrompt: string | undefined;
13
9
  }): {
14
10
  prompt: string | undefined;
@@ -1,13 +1,5 @@
1
- var r=Object.defineProperty;var n=(t,o)=>r(t,"name",{value:o,configurable:!0});import{formatCard as e}from"../../shared/generated-context.js";const i="Want a quick tour of how this works? I can also sign you in to Northlight, so I can use your apps like Gmail and Slack, search the web and text you. Say which, or just tell me what you're working on.",s="Want a quick tour of how this works? Say yes, or just tell me what you're working on.",a=e("first-run",{},`Open this conversation with exactly this sentence and nothing else:
1
+ var o=Object.defineProperty;var e=(t,r)=>o(t,"name",{value:r,configurable:!0});import{formatCard as n}from"../../shared/generated-context.js";const i="Want a quick tour of how this works? Say yes, or just tell me what you're working on.",s=n("first-run",{},`Open this conversation with exactly this sentence and nothing else:
2
2
 
3
3
  ${i}
4
4
 
5
- Read the user's answer:
6
- - Sign in (or yes to signing in): run \`crtr sys signin\` and follow what it prints.
7
- - Tour (or yes to the tour): run \`crtr sys tutorial basic\` and teach it one lesson per invocation \u2014 in your own words, letting them try each thing before moving on.
8
- - Both: sign in first. When this conversation resumes after the sign-in, start the tour.
9
- - Anything else: drop both offers and do what they asked. Do not mention the tour or signing in again in this conversation. A command that later answers that it needs a Northlight account still gets its one ask; that answer says how.`),h=e("first-run",{},`Open this conversation with exactly this sentence and nothing else:
10
-
11
- ${s}
12
-
13
- If the user says yes, run \`crtr sys tutorial -h\`, pick the track it names, and teach it one lesson per invocation \u2014 in your own words, letting them try each thing before moving on. If the user says anything else, drop the tour entirely and do what they asked.`);function c(t){return t.userPrompt!==void 0&&t.userPrompt.trim()!==""?{prompt:t.userPrompt,initialWhip:!0}:t.offerTour?{prompt:t.signedIn?h:a,initialWhip:!1}:{prompt:void 0,initialWhip:!1}}n(c,"frontDoorBootPrompt");export{i as FIRST_RUN_OFFER_SENTENCE,s as FIRST_RUN_TOUR_SENTENCE,c as frontDoorBootPrompt};
5
+ If the user says yes, run \`crtr sys tutorial -h\`, pick the track it names, and teach it one lesson per invocation \u2014 in your own words, letting them try each thing before moving on. If the user says anything else, drop the tour entirely and do what they asked.`);function u(t){return t.userPrompt!==void 0&&t.userPrompt.trim()!==""?{prompt:t.userPrompt,initialWhip:!0}:t.offerTour?{prompt:s,initialWhip:!1}:{prompt:void 0,initialWhip:!1}}e(u,"frontDoorBootPrompt");export{i as FIRST_RUN_TOUR_SENTENCE,u as frontDoorBootPrompt};
@@ -1,12 +1,11 @@
1
- var L=Object.defineProperty;var p=(i,a)=>L(i,"name",{value:a,configurable:!0});import{existsSync as b,statSync as M}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as $}from"../../build-root.js";import{FRONT_DOOR_ENV as W}from"./front-door-env.js";import{frontDoorBootPrompt as B}from"./first-run-offer.js";import{readMachineConfig as R}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as V}from"./node-id-token.js";import{markTourOffered as G,recordSetupCompleted as U,setupCompleted as y,tourOfferPending as Y}from"./setup-marker.js";function I(i){try{return b(i)&&M(i).isDirectory()}catch{return!1}}p(I,"isDir");const j=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function J(){let i=!1;const a=p(()=>{i=!0},"onSigint");process.once("SIGINT",a);try{const{runSetup:t}=await import("../../commands/sys/setup-wizard.js"),e=await t();if(i){const l=new Error("Interrupted");throw l.name="AbortError",l}await U(e)}finally{process.removeListener("SIGINT",a)}}p(J,"runFirstSetup");function X(i){let a=process.cwd(),t,e,l,f=!1,u,g;const o=[];for(let d=0;d<i.length;d++){const s=i[d];if(s==="--name")t=i[++d];else if(s==="--kind")e=i[++d];else if(s==="--profile")l=i[++d];else if(s==="--pick-profile")f=!0;else if(s==="--continue"||s==="-c")u="continue";else if(s==="--resume"||s==="-r"){u="pick";const w=i[d+1];w!==void 0&&V(w)&&!I(h(w))&&(g=w,d++)}else s.startsWith("--")||o.push(s)}o.length>0&&I(h(o[0]))&&(a=h(o.shift()));const m=o.length>0?o.join(" "):void 0;return{cwd:a,prompt:m,name:t,kind:e,profile:l,pickProfile:f,resume:u,resumeId:g}}p(X,"parseRootArgs");import{FRONT_DOOR_ENV as ae}from"./front-door-env.js";async function oe(i){const a=i.slice(2),t=a[0];if(process.env[W]||t==="-h"||t==="--help"||t==="--version"||t==="-v"||t!==void 0&&$.includes(t))return!1;if(t!==void 0){const r=/\s/.test(t),n=!t.startsWith("-")&&I(h(t)),c=j.has(t);if(!r&&!n&&!c)return!1;if(n){const{buildRoot:D}=await import("../../build-root.js");if((await D()).subtrees.some(A=>A.name===t))return!1}}const e=X(a),l=p(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:r}=await import("../profiles/manifest.js");e.profile=r(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await l();const f=process.stdin.isTTY&&process.stdout.isTTY;if(R()===void 0){f||(process.stderr.write("crtr: this computer is not signed in to Northlight; run `crtr sys signin`.\n"),process.exit(1));const{sysSigninLeaf:r}=await import("../../commands/sys/signin.js");try{await r.run({},{}),await(await import("../../commands/person-settings.js")).loadPersonSettingsViaApi()}catch(n){process.stderr.write(`${n instanceof Error?n.message:String(n)}
2
- `),process.exit(1)}}let u=!1;const g=f&&!y()&&(await(await import("../../commands/api-client.js")).cliClient().getModelAuthReadiness({cwd:e.cwd})).hosted_endpoint;f&&!y()&&!g&&(await J(),u=!0);let o=null,m,d=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:r,noResumeTargetMessage:n}=await import("./resume-root.js"),c=await r(e.resumeId);"error"in c&&(process.stderr.write(`${c.error}
3
- `),process.exit(1)),"none"in c?(e.resumeId.includes("-")&&(process.stderr.write(`${n(e.resumeId)}
4
- `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await l()):(o=c.node.profile_id,m=c.node.node_id,I(c.node.cwd)&&(d=c.node.cwd))}if(m===void 0){const{selectProfileForCwd:r,selectProfileForCwdReadOnly:n}=await import("../profiles/select.js");u&&e.profile===void 0&&process.stdout.write(`
1
+ var v=Object.defineProperty;var m=(t,s)=>v(t,"name",{value:s,configurable:!0});import{existsSync as _,statSync as x}from"node:fs";import{resolve as h}from"node:path";import{SUBTREE_NAMES as D}from"../../build-root.js";import{FRONT_DOOR_ENV as F}from"./front-door-env.js";import{frontDoorBootPrompt as E}from"./first-run-offer.js";import{readMachineConfig as C}from"../../daemon/machine-link/config.js";import{looksLikeNodeIdToken as b}from"./node-id-token.js";import{markTourOffered as A,recordSetupCompleted as L,setupCompleted as W,tourOfferPending as $}from"./setup-marker.js";function T(t){try{return _(t)&&x(t).isDirectory()}catch{return!1}}m(T,"isDir");const B=new Set(["--name","--kind","--profile","--pick-profile","--continue","-c","--resume","-r"]);async function M(){let t=!1;const s=m(()=>{t=!0},"onSigint");process.once("SIGINT",s);try{const{runSetup:r}=await import("../../commands/sys/setup-wizard.js"),e=await r();if(t){const c=new Error("Interrupted");throw c.name="AbortError",c}await L(e)}finally{process.removeListener("SIGINT",s)}}m(M,"runFirstSetup");function G(t){let s=process.cwd(),r,e,c,l=!1,u,p;const i=[];for(let f=0;f<t.length;f++){const n=t[f];if(n==="--name")r=t[++f];else if(n==="--kind")e=t[++f];else if(n==="--profile")c=t[++f];else if(n==="--pick-profile")l=!0;else if(n==="--continue"||n==="-c")u="continue";else if(n==="--resume"||n==="-r"){u="pick";const w=t[f+1];w!==void 0&&b(w)&&!T(h(w))&&(p=w,f++)}else n.startsWith("--")||i.push(n)}i.length>0&&T(h(i[0]))&&(s=h(i.shift()));const g=i.length>0?i.join(" "):void 0;return{cwd:s,prompt:g,name:r,kind:e,profile:c,pickProfile:l,resume:u,resumeId:p}}m(G,"parseRootArgs");import{FRONT_DOOR_ENV as re}from"./front-door-env.js";async function Q(t){const s=t.slice(2),r=s[0];if(process.env[F]||r==="-h"||r==="--help"||r==="--version"||r==="-v"||r!==void 0&&D.includes(r))return!1;if(r!==void 0){const o=/\s/.test(r),d=!r.startsWith("-")&&T(h(r)),a=B.has(r);if(!o&&!d&&!a)return!1;if(d){const{buildRoot:O}=await import("../../build-root.js");if((await O()).subtrees.some(S=>S.name===r))return!1}}const e=G(s),c=m(async()=>{if(e.profile===void 0)return;const{resolveProfileOperand:o}=await import("../profiles/manifest.js");e.profile=o(e.profile).profileId},"resolveProfileFlag");e.resumeId===void 0&&await c();const l=process.stdin.isTTY&&process.stdout.isTTY;C()===void 0&&!l&&(process.stderr.write("crtr: this computer is not signed in to Northlight; run `crtr sys signin`.\n"),process.exit(1));let u=!1;l&&!W()&&(await M(),u=!0);let p=null,i,g=process.cwd();if(e.resumeId!==void 0){const{resolveResumeTarget:o,noResumeTargetMessage:d}=await import("./resume-root.js"),a=await o(e.resumeId);"error"in a&&(process.stderr.write(`${a.error}
2
+ `),process.exit(1)),"none"in a?(e.resumeId.includes("-")&&(process.stderr.write(`${d(e.resumeId)}
3
+ `),process.exit(1)),e.prompt=e.prompt===void 0?e.resumeId:`${e.resumeId} ${e.prompt}`,e.resumeId=void 0,await c()):(p=a.node.profile_id,i=a.node.node_id,T(a.node.cwd)&&(g=a.node.cwd))}if(i===void 0){const{selectProfileForCwd:o,selectProfileForCwdReadOnly:d}=await import("../profiles/select.js");u&&e.profile===void 0&&process.stdout.write(`
5
4
  Choose a profile
6
- `),o=e.profile??(f?await r(e.cwd,void 0,e.pickProfile,!1):n(e.cwd))}const{cliClient:s}=await import("../../commands/api-client.js"),[{exitForMissingProviderCredential:w,hasConfiguredProviderCredential:k},S]=await Promise.all([import("./provider-credential-gate.js"),o===null?[]:s().listProfileEnv(o).then(r=>r.names)]),v=p(async()=>{const r=await s().getModelAuthReadiness({cwd:e.cwd,...o===null?{}:{profile:o}});return r.credential==="ready"||r.hosted_endpoint},"startable");if(!await k(S)&&!await v()){f||w();const{runFrontDoorLogin:r}=await import("./front-door-login.js");await r()||w()}const{inTmux:P}=await import("./placement-tmux.js");if(f&&!P()){const{TMUX_STARTED_ENV:r,handoffToTmux:n}=await import("./tmux-handoff.js");process.env[r]===void 0&&n(a,m!==void 0?null:o,d)}const[{bootRoot:N},{resumeRoot:O},{rendererWarning:_,missingPackageWarning:x,piAgentDir:C}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const r=x(C());r!==null&&process.stderr.write(`
7
- ${r}
5
+ `),p=e.profile??(l?await o(e.cwd,void 0,e.pickProfile,!1):d(e.cwd))}const{inTmux:f}=await import("./placement-tmux.js");if(l&&!f()){const{TMUX_STARTED_ENV:o,handoffToTmux:d}=await import("./tmux-handoff.js");process.env[o]===void 0&&d(s,i!==void 0?null:p,g)}const[{bootRoot:n},{resumeRoot:w},{rendererWarning:R,missingPackageWarning:k,piAgentDir:y}]=await Promise.all([import("./boot-root.js"),import("./resume-root.js"),import("./package-health.js")]);try{const o=k(y());o!==null&&process.stderr.write(`
6
+ ${o}
8
7
 
9
- `);const n=_();n!==null&&process.stderr.write(`
10
- ${n}
8
+ `);const d=R();d!==null&&process.stderr.write(`
9
+ ${d}
11
10
 
12
- `)}catch{}if(m!==void 0){const{resumeNodeById:r}=await import("./resume-root.js");await r(m)}if(e.resume!==void 0&&await O(e.cwd,e.resume==="pick")==="aborted")return!0;const T=f&&(u||await Y()),{prompt:E,initialWhip:F}=B({offerTour:T,signedIn:T&&R()!==void 0,userPrompt:e.prompt});return T&&P()&&await G(),await N({...e,prompt:E,initialWhip:F,selectedProfileId:o??void 0}),!0}p(oe,"maybeBootRoot");export{ae as FRONT_DOOR_ENV,oe as maybeBootRoot,X as parseRootArgs};
11
+ `)}catch{}if(i!==void 0){const{resumeNodeById:o}=await import("./resume-root.js");await o(i)}if(e.resume!==void 0&&await w(e.cwd,e.resume==="pick")==="aborted")return!0;const I=l&&(u||await $()),{prompt:P,initialWhip:N}=E({offerTour:I,userPrompt:e.prompt});return I&&f()&&await A(),await n({...e,prompt:P,initialWhip:N,selectedProfileId:p??void 0}),!0}m(Q,"maybeBootRoot");export{re as FRONT_DOOR_ENV,Q as maybeBootRoot,G as parseRootArgs};
@@ -0,0 +1,5 @@
1
+ import type { Refusal } from '../ledger/index.js';
2
+ /** Report a refused start of `user:<id>` by an app limit or an operator stop; any other refusal is not reported. Never throws. */
3
+ export declare function noticeStartRefusal(refusal: Refusal): Promise<void>;
4
+ /** The same report from the `402 cap_exhausted` a refused revive or respawn threw; any other error is ignored. */
5
+ export declare function noticeStartRefusalError(error: unknown): Promise<void>;
@@ -0,0 +1 @@
1
+ var l=Object.defineProperty;var n=(e,t)=>l(e,"name",{value:t,configurable:!0});import{directoryIssuer as f}from"../directory/issuer.js";import{emitEvent as c}from"../events/emit.js";import{describeOutboundFailure as p,outboundFetch as _}from"../events/outbound.js";import{mintDirectoryToken as y}from"../grants/sync.js";import{usageMonth as m}from"../ledger/months.js";import{RunError as g}from"../runs/operations.js";const a=new Set;async function E(e){await u(e.limit)}n(E,"noticeStartRefusal");async function x(e){if(!(e instanceof g)||e.code!=="cap_exhausted")return;const t=e.details?.limit;t!==void 0&&await u({id:t.id,payer:t.payer,source:t.source,grantee:t.filters.grantee})}n(x,"noticeStartRefusalError");async function u(e){const t=f();if(t===null||!e.payer?.startsWith("user:")||e.source!=="grant_sync"&&e.source!=="operator")return;const i=m(),o=`${e.id}|${i}`;if(a.has(o))return;a.add(o);const d=`${t}/v1/runtime/limit-refusals`;try{const r=await y(t),s=await _("limit_refusal_notice",d,{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`,"Content-Type":"application/json"},body:JSON.stringify({user_id:e.payer.slice(5),limit_id:e.id,month:i,reason:e.source==="grant_sync"?"app_limit":"operator_stop",app_id:e.source==="grant_sync"&&e.grantee?.startsWith("app:")?e.grantee.slice(4):null}),signal:AbortSignal.timeout(1e4)});if(s.status===400){c({level:"warn",event:"ledger.start_refusal.notice_rejected",fields:{limit_id:e.id}});return}if(!s.ok)throw new Error(`directory answered the limit refusal notice: ${s.status}`)}catch(r){a.delete(o),c({level:"warn",event:"ledger.start_refusal.notice_failed",error:r,fields:{limit_id:e.id,...p(r)}})}}n(u,"notice");export{E as noticeStartRefusal,x as noticeStartRefusalError};
@@ -0,0 +1,2 @@
1
+ export declare const seededKey: (person: string) => string;
2
+ export declare function seedTerminalDefaults(): Promise<string[]>;
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var r=(e,n)=>m(e,"name",{value:n,configurable:!0});import{withCanvasWrite as u}from"../canvas/db.js";import{applyOpsToRows as f,readSnapshotFromRows as O}from"./person-rows.js";import{appRevisionOf as E}from"./person-store.js";const o="app:terminal",p={name:"crouter-official-marketplace",url:"https://github.com/crouton-labs/crouter-official-marketplace.git"},g=["capture"],i=r(e=>`terminal_defaults_seeded:${e}`,"seededKey");async function y(){return await u(async e=>{const n=(await e.prepare("SELECT DISTINCT sub FROM grants WHERE grantee = 'app:terminal' AND status = 'active'").all()).map(a=>a.sub),s=[];for(const a of n){if(await e.prepare("SELECT 1 FROM canvas_meta WHERE key = ?").get(i(a))!==void 0)continue;const t=(await O(e,a)).apps[o];if(t===void 0||Object.keys(t.plugins).length===0&&Object.keys(t.marketplaces).length===0){const c=Object.fromEntries(g.map(l=>[l,{enabled:!0,source_marketplace:p.name}]));await f(e,a,[{op:"app-plugins.replace",app:o,plugins:c,marketplaces:{[p.name]:{url:p.url,ref:"main",installed_at:new Date().toISOString()}},ifRevision:E(t)}]),s.push(a)}await e.prepare("INSERT INTO canvas_meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO NOTHING").run(i(a),new Date().toISOString())}return s})}r(y,"seedTerminalDefaults");export{y as seedTerminalDefaults,i as seededKey};
@@ -1,2 +1,2 @@
1
- var Y=Object.defineProperty;var i=(e,c)=>Y(e,"name",{value:c,configurable:!0});import{randomUUID as X}from"node:crypto";import{CRON_OUTPUT_HEAD_BYTES as A,formatCronOutputHead as S}from"./cron/capture.js";import{clearLiveRun as _,cronDaemonInstanceId as M,ensureCronOwnerLease as z,registerLiveRun as G}from"./cron/live-runs.js";import{closeCronExecution as J,openCronExecution as K}from"./cron/run-socket.js";import{appProcessSandboxed as Q}from"../core/spaces/process.js";import{nodeAgentDir as V}from"../core/canvas/paths.js";import{uidForApp as W}from"../core/spaces/users.js";import{buildArmedRunContext as Z}from"./cron/armed-context.js";import{asPerson as j}from"./reconcilers/node-lifecycle/node-person.js";import{isProfilePaused as ee}from"../core/profiles/manifest.js";import{ensureCronFolder as ne}from"./cron/folders.js";import{cronEnvironment as re,fireInSandbox as te,fireOnMachine as oe,machineLinkLive as ae}from"./cron/machine-fire.js";import{advanceRecurrence as U}from"./cron/recurrence.js";import{checkCronFire as ie,cronPrincipalOf as se}from"./cron/authority.js";import{refusalError as de}from"../core/ledger/index.js";import{startRefusal as le}from"../core/runtime/start-check.js";import{settleClosedRun as ue,settleUnspawnedRun as v}from"./cron/closed.js";import{settleRun as B}from"./cron/settle.js";import{applyOverlapPolicies as fe,expireDueCrons as me}from"./cron/passes.js";import{dueClockCrons as ce,acquireCronRunLease as pe,releaseCronRunLease as he,attachCronRunPid as _e,HOSTED_CRON_MAX_FIRES as we}from"../core/canvas/crons.js";import{emitEvent as $}from"../core/events/emit.js";import{deliverDueDeadline as Ce}from"../core/feed/messages.js";import{runAppCommand as ge}from"../core/runtime/run-command.js";import{CRON_OUTPUT_HEAD_BYTES as Qe}from"./cron/capture.js";import{cronDaemonInstanceId as We,markSelfCanceledCronRun as Ze}from"./cron/live-runs.js";import{recoverStaleCronLeases as en}from"./cron/lease-recovery.js";function ze(e,c){return F(e,c).settled}i(ze,"executeCron");function F(e,c){const{outOfBand:s}=c;let l=i(()=>{},"admit");const u=new Promise(t=>{l=t}),w=new Promise((t,a)=>{let p=!1;const r=X();let I=i(()=>{},"undo");const R=i(d=>{if(I(),!p){a(d);return}p=!1,he(e.cron_id,r).then(()=>a(d),f=>{$({level:"error",event:"cron.lease.release_failed",error:f,fields:{cron_id:e.cron_id}}),a(d)})},"fail");(async()=>{const d=Date.now(),f=new Date(d).toISOString(),C={runId:r,outOfBand:s,startedAtIso:f,startedAtMs:d},D=await re(e),b=D?.kind==="machine"?D.id:null;if(b!==null&&!s&&!await ae(b)){t(null);return}if(await z(),!await pe(e.cron_id,M,f,s,r,D?.kind==="blaxel"?we:null)){t(null);return}p=!0;let m=await ie(se(e));if(m.allowed){e={...e,scopes:m.scopes};const n=await le({grantee:e.grantee,sub:e.sub,grant_id:e.grant_id});n!==null&&(m={allowed:!1,reason:"limit_reached",message:de(n).message})}if(!m.allowed){try{if(!s&&e.recur!=null){const h=await U(e,d);if(h!==null)throw h}}catch(h){v(e,C,"run could not be armed",h).then(t,a);return}const n=Date.now();B(e,{outOfBand:s,outcome:{kind:"refused",reason:m.reason,message:m.message},record:{runId:r,startedAtIso:f,finishedAtMs:n,durationMs:n-d,exitCode:null,stdoutHead:null,stderrHead:`${m.reason}: ${m.message}`.slice(0,A)},lease:"release"}).then(t,a);return}if(D?.kind==="blaxel"){te(e,C,l).then(t,R);return}if(b!==null){oe(e,{environmentId:b,runId:r,outOfBand:s,startedAtIso:f,startedAtMs:d},l).then(t,R);return}let H;try{if(e.isolated&&ne(e.grantee,e.cron_id),{env:H}=await Z(e,r),!s&&e.recur!=null){const n=await U(e,d);if(n!==null)throw n}}catch(n){v(e,C,"run could not be armed",n).then(t,a);return}let k=null,y=!1;const O={runId:r,replaced:!1,selfCanceled:!1,kill:i(()=>{k!==null?k():y=!0},"kill")};G(e.cron_id,O),I=i(()=>_(e.cron_id,r),"undo"),l();const g=Q()?{executionId:r,kind:"cron",cronId:e.cron_id,fromExec:e.armed_from_exec,grantee:e.grantee,sub:e.sub,grantId:e.grant_id,scopes:e.scopes,originRunId:e.origin_run_id,isolated:e.isolated,anchor:e.anchor_node,uid:await W(e.grantee),rebuilt:!1,refusal:null}:null,x=i(()=>{g!==null&&J(r)},"closeExecution");I=i(()=>{_(e.cron_id,r),x()},"undo"),i(async()=>(g!==null&&await K(g,e.cwd,e.profile),ge({command:e.command,cwd:e.cwd,env:H,app:e.grantee,isolated:e.isolated,principal:{sub:e.sub,grantId:e.grant_id,scopes:e.scopes},...e.isolated?{folder:e.cwd}:{},...g!==null?{cron:{executionId:r,...e.anchor_node===null||e.isolated?{}:{anchorDir:V(e.anchor_node,e.grantee)}}}:e.anchor_node===null||e.isolated?{}:{nodeId:e.anchor_node},timeoutMs:e.run_timeout_s*1e3,headBytes:A})),"launch")().then(async n=>{if(n.pid===null){_(e.cron_id,r),x(),n.completion.then(o=>{v(e,C,"run failed to spawn",o.processError??new Error("bash did not provide a process id")).then(t,a)},a);return}I=i(()=>{_(e.cron_id,r),x(),n.terminate()},"undo");let h=!1;const P=i(()=>{n.completion.then(o=>{const T=O.replaced,N=O.selfCanceled,E=g?.refusal??null;if(_(e.cron_id,r),x(),h){t(null);return}if(E!==null&&!T){const L=Date.now(),q=S(o.stderr,o.stderrTruncated);B(e,{outOfBand:s,outcome:{kind:"refused",reason:E.reason,message:E.message},record:{runId:r,startedAtIso:f,finishedAtMs:L,durationMs:L-d,exitCode:o.exitCode,stdoutHead:S(o.stdout,o.stdoutTruncated)||null,stderrHead:`${E.reason}: ${E.message}
2
- ${q}`.trim().slice(0,A)},lease:"release"}).then(t,a);return}ue(e,{runId:r,outOfBand:s,startedAtIso:f,startedAtMs:d,finishedAtMs:Date.now(),code:o.exitCode,timedOut:o.timedOut,processError:o.processError,stdoutHead:S(o.stdout,o.stdoutTruncated),stderrHead:S(o.stderr,o.stderrTruncated),stdoutSha256:o.stdoutSha256,wasReplaced:T,wasSelfCanceled:N}).then(t,a)},a)},"settleCommand");if(!await _e(e.cron_id,M,f,n.pid)&&!O.selfCanceled){h=!0,n.terminate(),P();return}k=n.terminate,y&&n.terminate(),P()},n=>{_(e.cron_id,r),x(),v(e,C,"run failed to spawn",n).then(t,a)}).catch(R)})().catch(R)});return w.then(l,l),{admitted:u,settled:w}}i(F,"startCron");async function Ge(e,c){const s=new Date(e).toISOString();await me(s),await fe(e,s);const l=[];for(const u of await ce(s)){const w=await j(u.sub,async()=>ee(u.profile)?null:u.deadline_body!==null?await Ce(u).then(()=>null):F(u,{outOfBand:!1})).catch(r=>($({level:"error",event:"cron.fire_failed",error:r,fields:{cron_id:u.cron_id}}),null));if(w===null)continue;const{admitted:t,settled:a}=w,p=a.then(()=>{});p.catch(()=>{}),await t,l.push(p),c.register?.(p)}for(const u of l)u.catch(()=>{});return l}i(Ge,"runDueCrons");export{Qe as CRON_OUTPUT_HEAD_BYTES,We as cronDaemonInstanceId,ze as executeCron,Ze as markSelfCanceledCronRun,en as recoverStaleCronLeases,Ge as runDueCrons,F as startCron};
1
+ var Y=Object.defineProperty;var i=(e,c)=>Y(e,"name",{value:c,configurable:!0});import{randomUUID as X}from"node:crypto";import{CRON_OUTPUT_HEAD_BYTES as A,formatCronOutputHead as S}from"./cron/capture.js";import{clearLiveRun as w,cronDaemonInstanceId as M,ensureCronOwnerLease as z,registerLiveRun as G}from"./cron/live-runs.js";import{closeCronExecution as J,openCronExecution as K}from"./cron/run-socket.js";import{appProcessSandboxed as Q}from"../core/spaces/process.js";import{nodeAgentDir as V}from"../core/canvas/paths.js";import{uidForApp as W}from"../core/spaces/users.js";import{buildArmedRunContext as Z}from"./cron/armed-context.js";import{asPerson as j}from"./reconcilers/node-lifecycle/node-person.js";import{isProfilePaused as ee}from"../core/profiles/manifest.js";import{ensureCronFolder as ne}from"./cron/folders.js";import{cronEnvironment as re,fireInSandbox as te,fireOnMachine as oe,machineLinkLive as ae}from"./cron/machine-fire.js";import{advanceRecurrence as U}from"./cron/recurrence.js";import{checkCronFire as ie,cronPrincipalOf as se}from"./cron/authority.js";import{refusalError as de}from"../core/ledger/index.js";import{noticeStartRefusal as le}from"../core/runtime/start-refusal-notice.js";import{startRefusal as ue}from"../core/runtime/start-check.js";import{settleClosedRun as fe,settleUnspawnedRun as v}from"./cron/closed.js";import{settleRun as B}from"./cron/settle.js";import{applyOverlapPolicies as me,expireDueCrons as ce}from"./cron/passes.js";import{dueClockCrons as pe,acquireCronRunLease as he,releaseCronRunLease as we,attachCronRunPid as _e,HOSTED_CRON_MAX_FIRES as Ce}from"../core/canvas/crons.js";import{emitEvent as $}from"../core/events/emit.js";import{deliverDueDeadline as ge}from"../core/feed/messages.js";import{runAppCommand as xe}from"../core/runtime/run-command.js";import{CRON_OUTPUT_HEAD_BYTES as We}from"./cron/capture.js";import{cronDaemonInstanceId as je,markSelfCanceledCronRun as en}from"./cron/live-runs.js";import{recoverStaleCronLeases as rn}from"./cron/lease-recovery.js";function Je(e,c){return F(e,c).settled}i(Je,"executeCron");function F(e,c){const{outOfBand:s}=c;let l=i(()=>{},"admit");const u=new Promise(t=>{l=t}),_=new Promise((t,a)=>{let p=!1;const r=X();let I=i(()=>{},"undo");const R=i(d=>{if(I(),!p){a(d);return}p=!1,we(e.cron_id,r).then(()=>a(d),f=>{$({level:"error",event:"cron.lease.release_failed",error:f,fields:{cron_id:e.cron_id}}),a(d)})},"fail");(async()=>{const d=Date.now(),f=new Date(d).toISOString(),C={runId:r,outOfBand:s,startedAtIso:f,startedAtMs:d},D=await re(e),b=D?.kind==="machine"?D.id:null;if(b!==null&&!s&&!await ae(b)){t(null);return}if(await z(),!await he(e.cron_id,M,f,s,r,D?.kind==="blaxel"?Ce:null)){t(null);return}p=!0;let m=await ie(se(e));if(m.allowed){e={...e,scopes:m.scopes};const n=await ue({grantee:e.grantee,sub:e.sub,grant_id:e.grant_id});n!==null&&(m={allowed:!1,reason:"limit_reached",message:de(n).message},await le(n))}if(!m.allowed){try{if(!s&&e.recur!=null){const h=await U(e,d);if(h!==null)throw h}}catch(h){v(e,C,"run could not be armed",h).then(t,a);return}const n=Date.now();B(e,{outOfBand:s,outcome:{kind:"refused",reason:m.reason,message:m.message},record:{runId:r,startedAtIso:f,finishedAtMs:n,durationMs:n-d,exitCode:null,stdoutHead:null,stderrHead:`${m.reason}: ${m.message}`.slice(0,A)},lease:"release"}).then(t,a);return}if(D?.kind==="blaxel"){te(e,C,l).then(t,R);return}if(b!==null){oe(e,{environmentId:b,runId:r,outOfBand:s,startedAtIso:f,startedAtMs:d},l).then(t,R);return}let H;try{if(e.isolated&&ne(e.grantee,e.cron_id),{env:H}=await Z(e,r),!s&&e.recur!=null){const n=await U(e,d);if(n!==null)throw n}}catch(n){v(e,C,"run could not be armed",n).then(t,a);return}let k=null,y=!1;const O={runId:r,replaced:!1,selfCanceled:!1,kill:i(()=>{k!==null?k():y=!0},"kill")};G(e.cron_id,O),I=i(()=>w(e.cron_id,r),"undo"),l();const g=Q()?{executionId:r,kind:"cron",cronId:e.cron_id,fromExec:e.armed_from_exec,grantee:e.grantee,sub:e.sub,grantId:e.grant_id,scopes:e.scopes,originRunId:e.origin_run_id,isolated:e.isolated,anchor:e.anchor_node,uid:await W(e.grantee),rebuilt:!1,refusal:null}:null,x=i(()=>{g!==null&&J(r)},"closeExecution");I=i(()=>{w(e.cron_id,r),x()},"undo"),i(async()=>(g!==null&&await K(g,e.cwd,e.profile),xe({command:e.command,cwd:e.cwd,env:H,app:e.grantee,isolated:e.isolated,principal:{sub:e.sub,grantId:e.grant_id,scopes:e.scopes},...e.isolated?{folder:e.cwd}:{},...g!==null?{cron:{executionId:r,...e.anchor_node===null||e.isolated?{}:{anchorDir:V(e.anchor_node,e.grantee)}}}:e.anchor_node===null||e.isolated?{}:{nodeId:e.anchor_node},timeoutMs:e.run_timeout_s*1e3,headBytes:A})),"launch")().then(async n=>{if(n.pid===null){w(e.cron_id,r),x(),n.completion.then(o=>{v(e,C,"run failed to spawn",o.processError??new Error("bash did not provide a process id")).then(t,a)},a);return}I=i(()=>{w(e.cron_id,r),x(),n.terminate()},"undo");let h=!1;const P=i(()=>{n.completion.then(o=>{const T=O.replaced,N=O.selfCanceled,E=g?.refusal??null;if(w(e.cron_id,r),x(),h){t(null);return}if(E!==null&&!T){const L=Date.now(),q=S(o.stderr,o.stderrTruncated);B(e,{outOfBand:s,outcome:{kind:"refused",reason:E.reason,message:E.message},record:{runId:r,startedAtIso:f,finishedAtMs:L,durationMs:L-d,exitCode:o.exitCode,stdoutHead:S(o.stdout,o.stdoutTruncated)||null,stderrHead:`${E.reason}: ${E.message}
2
+ ${q}`.trim().slice(0,A)},lease:"release"}).then(t,a);return}fe(e,{runId:r,outOfBand:s,startedAtIso:f,startedAtMs:d,finishedAtMs:Date.now(),code:o.exitCode,timedOut:o.timedOut,processError:o.processError,stdoutHead:S(o.stdout,o.stdoutTruncated),stderrHead:S(o.stderr,o.stderrTruncated),stdoutSha256:o.stdoutSha256,wasReplaced:T,wasSelfCanceled:N}).then(t,a)},a)},"settleCommand");if(!await _e(e.cron_id,M,f,n.pid)&&!O.selfCanceled){h=!0,n.terminate(),P();return}k=n.terminate,y&&n.terminate(),P()},n=>{w(e.cron_id,r),x(),v(e,C,"run failed to spawn",n).then(t,a)}).catch(R)})().catch(R)});return _.then(l,l),{admitted:u,settled:_}}i(F,"startCron");async function Ke(e,c){const s=new Date(e).toISOString();await ce(s),await me(e,s);const l=[];for(const u of await pe(s)){const _=await j(u.sub,async()=>ee(u.profile)?null:u.deadline_body!==null?await ge(u).then(()=>null):F(u,{outOfBand:!1})).catch(r=>($({level:"error",event:"cron.fire_failed",error:r,fields:{cron_id:u.cron_id}}),null));if(_===null)continue;const{admitted:t,settled:a}=_,p=a.then(()=>{});p.catch(()=>{}),await t,l.push(p),c.register?.(p)}for(const u of l)u.catch(()=>{});return l}i(Ke,"runDueCrons");export{We as CRON_OUTPUT_HEAD_BYTES,je as cronDaemonInstanceId,Je as executeCron,en as markSelfCanceledCronRun,rn as recoverStaleCronLeases,Ke as runDueCrons,F as startCron};
@@ -1,4 +1,4 @@
1
- var P=Object.defineProperty;var l=(i,e)=>P(i,"name",{value:e,configurable:!0});import{getNode as w,getRow as R,recordRespawnAttempt as T}from"../core/canvas/index.js";import{revokeExitedNodeToken as N}from"../core/canvas/node-tokens.js";import{PROFILE_PAUSE_STOP_REASON as _,absorbProfilePauseStop as S,endExecution as y,hasLaunchingExecution as F,hasProfilePauseStop as C,hasRunningRemoteExecution as b,liveExecutionForNode as g,liveExecutionNodeIds as O,markProfilePauseStop as k,recordExecutionExit as A,takeObservedExit as M}from"../core/canvas/executions.js";import{isProfilePaused as z}from"../core/profiles/manifest.js";import{fullName as p}from"../core/canvas/labels.js";import{isSafeNodeId as o}from"../core/canvas/paths.js";import{hasIdleReleaseIntent as B,transition as v}from"../core/runtime/lifecycle.js";import{publishNotice as L}from"../core/runtime/close.js";import{hasAdmittedTurn as D,readFault as W,readInterruptedTurn as q,readTransportPoisonVerdict as G}from"../core/canvas/recovery.js";import{hasPendingWake as H}from"./reconcilers/live-obligation.js";import{clearRespawnPolicy as h,deferRespawnWhileOffline as Y,MAX_RESPAWN_ATTEMPTS as U,OFFLINE_RESPAWN_RETRY_MS as V,recordRespawnPolicy as j,respawnBackoffMs as K}from"./reconcilers/node-lifecycle/respawn-policy.js";import{probeOnline as X}from"../core/runtime/connectivity.js";import{runnerForExecution as J}from"../core/runtime/runner/index.js";import{reviveNode as Q}from"../core/runtime/revive.js";import{isStartRefusal as Z}from"../core/runtime/start-check.js";import{MachineOfflineError as I}from"../core/runtime/runner/machine/ops.js";import{pushUrgent as m}from"../core/feed/feed.js";import{emitEvent as f}from"../core/events/emit.js";import{brokerThresholdsForDaemon as ee}from"../core/runtime/fleet.js";import{isRecoveryHeld as te}from"../core/runtime/recovery-hold.js";async function E(i,e){const r=await W(i.node_id),t=r===null?"":`The broker reported a ${r.kind} fault on ${r.link} (${r.op}) before it exited: ${r.message}
1
+ var P=Object.defineProperty;var c=(i,e)=>P(i,"name",{value:e,configurable:!0});import{getNode as w,getRow as R,recordRespawnAttempt as T}from"../core/canvas/index.js";import{revokeExitedNodeToken as N}from"../core/canvas/node-tokens.js";import{PROFILE_PAUSE_STOP_REASON as _,absorbProfilePauseStop as S,endExecution as y,hasLaunchingExecution as F,hasProfilePauseStop as C,hasRunningRemoteExecution as b,liveExecutionForNode as g,liveExecutionNodeIds as O,markProfilePauseStop as k,recordExecutionExit as A,takeObservedExit as M}from"../core/canvas/executions.js";import{isProfilePaused as z}from"../core/profiles/manifest.js";import{fullName as p}from"../core/canvas/labels.js";import{isSafeNodeId as o}from"../core/canvas/paths.js";import{hasIdleReleaseIntent as B,transition as v}from"../core/runtime/lifecycle.js";import{publishNotice as L}from"../core/runtime/close.js";import{hasAdmittedTurn as D,readFault as W,readInterruptedTurn as q,readTransportPoisonVerdict as G}from"../core/canvas/recovery.js";import{hasPendingWake as H}from"./reconcilers/live-obligation.js";import{clearRespawnPolicy as h,deferRespawnWhileOffline as Y,MAX_RESPAWN_ATTEMPTS as U,OFFLINE_RESPAWN_RETRY_MS as V,recordRespawnPolicy as j,respawnBackoffMs as K}from"./reconcilers/node-lifecycle/respawn-policy.js";import{probeOnline as X}from"../core/runtime/connectivity.js";import{runnerForExecution as J}from"../core/runtime/runner/index.js";import{reviveNode as Q}from"../core/runtime/revive.js";import{noticeStartRefusalError as Z}from"../core/runtime/start-refusal-notice.js";import{isStartRefusal as I}from"../core/runtime/start-check.js";import{MachineOfflineError as ee}from"../core/runtime/runner/machine/ops.js";import{pushUrgent as m}from"../core/feed/feed.js";import{emitEvent as f}from"../core/events/emit.js";import{brokerThresholdsForDaemon as te}from"../core/runtime/fleet.js";import{isRecoveryHeld as re}from"../core/runtime/recovery-hold.js";async function E(i,e){const r=await W(i.node_id),t=r===null?"":`The broker reported a ${r.kind} fault on ${r.link} (${r.op}) before it exited: ${r.message}
2
2
 
3
3
  `,s=e===void 0?"The daemon did not observe an exit status.":`The observed exit status was code ${e.code??"null"}, signal ${e.signal??"null"}.`;return`\u26A0 Spawn failed \u2014 \`${i.name}\` (${i.kind}) never started.
4
4
 
@@ -6,16 +6,16 @@ Its pi vehicle exited before the session came up (no pi_session_id was ever reco
6
6
 
7
7
  `+t+`Inspect canonical event diagnostics with \`crtr sys logs --node ${i.node_id}\`.
8
8
 
9
- If the work still needs doing, re-spawn it.`}l(E,"bootFailureBody");async function $(i,e){await m(i.node_id,await E(i,e),{from:i.node_id})}l($,"surfaceBootFailure");function x(i){return`\u26A0 Out of memory \u2014 \`${i.name}\` (${i.kind}) was killed because its app's processes together passed the app's memory limit.
9
+ If the work still needs doing, re-spawn it.`}c(E,"bootFailureBody");async function $(i,e){await m(i.node_id,await E(i,e),{from:i.node_id})}c($,"surfaceBootFailure");function x(i){return`\u26A0 Out of memory \u2014 \`${i.name}\` (${i.kind}) was killed because its app's processes together passed the app's memory limit.
10
10
 
11
- Every process of the run was stopped. The daemon does not restart it, because it would reach the same limit. Reduce what the run holds in memory, or ask the person to raise the app's limit (\`crtr sys limits set --app ${i.grantee??"app:terminal"} --memory <size>\`), then revive the node.`}l(x,"outOfMemoryBody");async function re(i){const e=await G(i.node_id),r=e===null?"":`
11
+ Every process of the run was stopped. The daemon does not restart it, because it would reach the same limit. Reduce what the run holds in memory, or ask the person to raise the app's limit (\`crtr sys limits set --app ${i.grantee??"app:terminal"} --memory <size>\`), then revive the node.`}c(x,"outOfMemoryBody");async function ie(i){const e=await G(i.node_id),r=e===null?"":`
12
12
 
13
13
  Provider rotation observed ${e.consecutivePasses} consecutive route-queue passes with no HTTP response (tried ${e.routes.join(", ")}). Check network and provider transport before reviving.`,t=`\u26A0 Crash loop \u2014 \`${i.name}\` (${i.kind}) kept dying without settling a turn.
14
14
 
15
15
  Its session started successfully, but six consecutive relaunches made no progress, so the daemon stopped retrying.`+r+`
16
16
 
17
- Fix the crash cause, then revive the node if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(re,"surfaceCrashLoop");async function ie(i,e){const r=e instanceof Error?e.message:String(e),t=`\u26A0 Recovery failed \u2014 \`${i.name}\` (${i.kind}) could not be relaunched.
17
+ Fix the crash cause, then revive the node if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}c(ie,"surfaceCrashLoop");async function se(i,e){const r=e instanceof Error?e.message:String(e),t=`\u26A0 Recovery failed \u2014 \`${i.name}\` (${i.kind}) could not be relaunched.
18
18
 
19
19
  The daemon refused this recovery before starting a broker: ${r}
20
20
 
21
- The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}l(ie,"surfaceRecoveryFailure");function se(i,e,r=!0,t=!1){return i===null||i.status==="done"||i.status==="canceled"||i.status==="dead"?"forget":i.intent==="refresh"||i.cycle_pending===!0?"respawn-fresh":B(i)?"dormant":i.lifecycle==="resident"&&!e&&!r&&(i.pi_session_id!=null||t)?"release-idle":i.pi_session_id!=null?"respawn-resume":e||t||i.fork_from!=null?"respawn-fresh":"boot-failure"}l(se,"classifyDeadNode");const ae=3e4;class Re{static{l(this,"DaemonFleet")}#a;#n;#r;#o;#e=new Map;#t=new Set;#l=Number.NEGATIVE_INFINITY;constructor(e){this.#a=e.epoch,this.#n=e.enqueue,this.#r=e.now??Date.now,this.#o=e.probeOnline??(()=>X())}epoch(){return this.#a}register(e,r){if(this.#e.has(e))throw new Error(`fleet: ${e} already has a live broker entry \u2014 refusing a second launch (programming error)`);if(r.pid===null)throw new Error(`fleet: refusing to register ${e} with no pid`);this.#t.delete(e),this.#e.set(e,{pid:r.pid,handle:r})}async has(e){return this.#e.has(e)||await b(e)}async isClaimed(e){return this.#e.has(e)||this.#t.has(e)||await b(e)||await F(e,this.#a)}get(e){return this.#e.get(e)}size(){return this.#e.size}async#c(){const e=await O();for(const r of this.#e.keys())e.add(r);for(const r of this.#t)e.add(r);return e}async occupancy(){return(await this.#c()).size}async reserveSlot(e){if(this.#t.has(e)||this.#e.has(e))return!0;const{automaticReviveCap:r}=ee(),t=await this.#c();if(this.#t.has(e)||this.#e.has(e))return!0;if(t.delete(e),t.size<r)return this.#t.has(e)||this.#t.add(e),!0;const s=this.#r();return s-this.#l>=ae&&(this.#l=s,f({level:"warn",event:"broker.capacity.revive_deferred",fields:{live_count:t.size,hard_cap:r}})),!1}releaseReservation(e){this.#t.delete(e)}entries(){return this.#e.entries()}async interruptForProfilePause(e,r=this.#e.get(e)?.pid){if(r===void 0){const t=await g(e);if(t===null||t.runner==="process"||t.state!=="running")return;await k(e),(await J(t.runner).stop(t,{reason:_})).confirmed&&await y(t.executionId,{reason:_});return}await k(e);try{process.kill(r,"SIGTERM")}catch{}}async hasProfilePauseInterruption(e){return await C(e)}forget(e){this.#e.delete(e),this.#t.delete(e)}#i=new Set;async exitsSettled(){for(;this.#i.size>0;)await Promise.allSettled([...this.#i])}async onChildExit(e,r,t){const s=this.#u(e,r,t);this.#i.add(s);try{await s}finally{this.#i.delete(s)}}async#u(e,r,t){const s=t??(await g(e))?.executionId;t&&await N(t),this.#e.delete(e),s!==void 0&&(await A(s,r),await y(s,{reason:"exited"})),this.#n(async()=>{const a=await w(e),n=a?.launched_at==null?Number.NaN:Date.parse(a.launched_at),d=Number.isFinite(n)?Math.max(0,this.#r()-n):null,u=a?.respawn_failures??0;this.#f(e,r,d,u)})}async deliverExit(e,r){await this.onChildExit(e,r)}async applyDeadRowPolicy(e){await this.#h(e,await M(e))}async terminalizeIfStillNonTerminal(e,r,t,s,a){const n=await w(e);return n===null||n.status==="done"||n.status==="canceled"||n.status==="dead"?!1:(await this.#s(e,n,{event:r,reason:s,detail:a,wake:`Child crashed \u2014 ${p(n)} (${e}) could not be relaunched and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>ie(n,t),"surface")}),!0)}dispose(){}#f(e,r,t,s){f({level:"info",event:"broker.exit.observed",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},code:r.code,signal:r.signal,uptime_ms:t,consecutive_failures:s}})}async#h(e,r){return this.#d(e,r)}async#d(e,r){const t=await w(e);if(t!==null&&z(t.profile_id))return await h(e),"forget";if(await S(e))return await h(e),"forget";if(await te(e))return"dormant";const s=(await q(e))?.interrupted===!0;if(r?.oomKilled===!0&&t!==null&&t.status!=="done"&&t.status!=="canceled"&&t.status!=="dead")return await h(e),await this.#s(e,t,{event:"broker.out_of_memory",reason:"out_of_memory",detail:{schema:"crtr.node-outcome-detail/v1",message:x(t)},wake:`Child out of memory \u2014 ${p(t)} (${e}) used more memory than its app is allowed and is now dead. It is not restarted automatically. Revive it with \`crtr node lifecycle revive ${e}\` once the work needs less memory or the cap is raised (\`crtr sys limits set\`).`,surface:l(async()=>{await m(e,x(t),{from:e})},"surface")}),"forget";const a=se(t,s,await H(e),await D(e));switch(a){case"forget":await h(e);break;case"dormant":await h(e);break;case"release-idle":await h(e),await v(e,"release"),f({level:"info",event:"broker.recovery.released",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e}}});break;case"boot-failure":await this.#s(e,t,{event:"broker.boot.failed",reason:"boot_failed",detail:{schema:"crtr.node-outcome-detail/v1",message:await E(t,r)},wake:`Child crashed \u2014 ${p(t)} (${e}) exited before its session ever came up and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:l(()=>$(t,r),"surface")});break;case"respawn-fresh":case"respawn-resume":await this.#p(e,t,a,s);break}return a}async#p(e,r,t,s){const a=await R(e);if(a===null)return;const n=a.respawn_failures??0;if(!await this.#o()){await Y(e,n,this.#r()),f({level:"info",event:"broker.respawn.offline_deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,retry_in_ms:V,consecutive_failures:n}});return}const d=a.respawn_not_before==null,u=d?await j(a,this.#r()):{failures:n,notBefore:a.respawn_not_before,exhausted:n>=U};if(u.exhausted){await T(e,{failures:u.failures,notBefore:null});const c=`Child crashed \u2014 ${p(r)} (${e}) kept dying without settling a turn (${u.failures} consecutive launches) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;await this.#s(e,r,{event:"broker.respawn.exhausted",reason:"crash_looped",detail:{schema:"crtr.node-outcome-detail/v1",message:c,respawn_failures:u.failures},wake:c,...r.pi_session_id!=null?{surface:l(()=>re(r),"surface")}:{}});return}if(d&&u.notBefore!==null){f({level:"info",event:"broker.respawn.deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,backoff_ms:K(u.failures),consecutive_failures:u.failures}});return}f({level:"info",event:"broker.respawn.started",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,consecutive_failures:u.failures}});try{await Q(e,{capacity:"freeze",resume:t==="respawn-resume",wakeReason:t==="respawn-resume"&&s?"runtime-restart-abort":void 0,recovery:!0})}catch(c){if(Z(c)||c instanceof I){await h(e),await v(e,"release"),f({level:"warn",event:"node.start.refused",node_id:e,error:c,fields:{enact:"respawn"}});return}f({level:"error",event:"broker.respawn.failed",...o(e)?{node_id:e}:{},error:c,fields:{...o(e)?{}:{affected_node_id:e},action:t}}),await this.terminalizeIfStillNonTerminal(e,"broker.respawn.refused",c,"launch_failed",{schema:"crtr.node-outcome-detail/v1",message:c instanceof Error?c.message:String(c)})}}async#s(e,r,t){f({level:"error",event:t.event,...o(e)?{node_id:e}:{fields:{affected_node_id:e}}}),await v(e,"crash",{reason:t.reason,outcome:{detail:t.detail}});try{await(t.surface??(()=>$(r)))()}catch(s){f({level:"error",event:"broker.boot_failure_surface.failed",...o(e)?{node_id:e}:{fields:{affected_node_id:e}},error:s})}await L(e,"notice.crash",t.wake,{reason:"child-crashed",child:e})}}export{Re as DaemonFleet,se as classifyDeadNode,$ as surfaceBootFailure};
21
+ The node is now dead. Fix the recorded launch configuration, then revive it if the work still needs doing.`;await m(i.node_id,t,{from:i.node_id})}c(se,"surfaceRecoveryFailure");function ae(i,e,r=!0,t=!1){return i===null||i.status==="done"||i.status==="canceled"||i.status==="dead"?"forget":i.intent==="refresh"||i.cycle_pending===!0?"respawn-fresh":B(i)?"dormant":i.lifecycle==="resident"&&!e&&!r&&(i.pi_session_id!=null||t)?"release-idle":i.pi_session_id!=null?"respawn-resume":e||t||i.fork_from!=null?"respawn-fresh":"boot-failure"}c(ae,"classifyDeadNode");const ne=3e4;class Ne{static{c(this,"DaemonFleet")}#a;#n;#r;#o;#e=new Map;#t=new Set;#l=Number.NEGATIVE_INFINITY;constructor(e){this.#a=e.epoch,this.#n=e.enqueue,this.#r=e.now??Date.now,this.#o=e.probeOnline??(()=>X())}epoch(){return this.#a}register(e,r){if(this.#e.has(e))throw new Error(`fleet: ${e} already has a live broker entry \u2014 refusing a second launch (programming error)`);if(r.pid===null)throw new Error(`fleet: refusing to register ${e} with no pid`);this.#t.delete(e),this.#e.set(e,{pid:r.pid,handle:r})}async has(e){return this.#e.has(e)||await b(e)}async isClaimed(e){return this.#e.has(e)||this.#t.has(e)||await b(e)||await F(e,this.#a)}get(e){return this.#e.get(e)}size(){return this.#e.size}async#c(){const e=await O();for(const r of this.#e.keys())e.add(r);for(const r of this.#t)e.add(r);return e}async occupancy(){return(await this.#c()).size}async reserveSlot(e){if(this.#t.has(e)||this.#e.has(e))return!0;const{automaticReviveCap:r}=te(),t=await this.#c();if(this.#t.has(e)||this.#e.has(e))return!0;if(t.delete(e),t.size<r)return this.#t.has(e)||this.#t.add(e),!0;const s=this.#r();return s-this.#l>=ne&&(this.#l=s,f({level:"warn",event:"broker.capacity.revive_deferred",fields:{live_count:t.size,hard_cap:r}})),!1}releaseReservation(e){this.#t.delete(e)}entries(){return this.#e.entries()}async interruptForProfilePause(e,r=this.#e.get(e)?.pid){if(r===void 0){const t=await g(e);if(t===null||t.runner==="process"||t.state!=="running")return;await k(e),(await J(t.runner).stop(t,{reason:_})).confirmed&&await y(t.executionId,{reason:_});return}await k(e);try{process.kill(r,"SIGTERM")}catch{}}async hasProfilePauseInterruption(e){return await C(e)}forget(e){this.#e.delete(e),this.#t.delete(e)}#i=new Set;async exitsSettled(){for(;this.#i.size>0;)await Promise.allSettled([...this.#i])}async onChildExit(e,r,t){const s=this.#u(e,r,t);this.#i.add(s);try{await s}finally{this.#i.delete(s)}}async#u(e,r,t){const s=t??(await g(e))?.executionId;t&&await N(t),this.#e.delete(e),s!==void 0&&(await A(s,r),await y(s,{reason:"exited"})),this.#n(async()=>{const a=await w(e),n=a?.launched_at==null?Number.NaN:Date.parse(a.launched_at),d=Number.isFinite(n)?Math.max(0,this.#r()-n):null,u=a?.respawn_failures??0;this.#f(e,r,d,u)})}async deliverExit(e,r){await this.onChildExit(e,r)}async applyDeadRowPolicy(e){await this.#h(e,await M(e))}async terminalizeIfStillNonTerminal(e,r,t,s,a){const n=await w(e);return n===null||n.status==="done"||n.status==="canceled"||n.status==="dead"?!1:(await this.#s(e,n,{event:r,reason:s,detail:a,wake:`Child crashed \u2014 ${p(n)} (${e}) could not be relaunched and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:c(()=>se(n,t),"surface")}),!0)}dispose(){}#f(e,r,t,s){f({level:"info",event:"broker.exit.observed",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},code:r.code,signal:r.signal,uptime_ms:t,consecutive_failures:s}})}async#h(e,r){return this.#d(e,r)}async#d(e,r){const t=await w(e);if(t!==null&&z(t.profile_id))return await h(e),"forget";if(await S(e))return await h(e),"forget";if(await re(e))return"dormant";const s=(await q(e))?.interrupted===!0;if(r?.oomKilled===!0&&t!==null&&t.status!=="done"&&t.status!=="canceled"&&t.status!=="dead")return await h(e),await this.#s(e,t,{event:"broker.out_of_memory",reason:"out_of_memory",detail:{schema:"crtr.node-outcome-detail/v1",message:x(t)},wake:`Child out of memory \u2014 ${p(t)} (${e}) used more memory than its app is allowed and is now dead. It is not restarted automatically. Revive it with \`crtr node lifecycle revive ${e}\` once the work needs less memory or the cap is raised (\`crtr sys limits set\`).`,surface:c(async()=>{await m(e,x(t),{from:e})},"surface")}),"forget";const a=ae(t,s,await H(e),await D(e));switch(a){case"forget":await h(e);break;case"dormant":await h(e);break;case"release-idle":await h(e),await v(e,"release"),f({level:"info",event:"broker.recovery.released",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e}}});break;case"boot-failure":await this.#s(e,t,{event:"broker.boot.failed",reason:"boot_failed",detail:{schema:"crtr.node-outcome-detail/v1",message:await E(t,r)},wake:`Child crashed \u2014 ${p(t)} (${e}) exited before its session ever came up and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,surface:c(()=>$(t,r),"surface")});break;case"respawn-fresh":case"respawn-resume":await this.#p(e,t,a,s);break}return a}async#p(e,r,t,s){const a=await R(e);if(a===null)return;const n=a.respawn_failures??0;if(!await this.#o()){await Y(e,n,this.#r()),f({level:"info",event:"broker.respawn.offline_deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,retry_in_ms:V,consecutive_failures:n}});return}const d=a.respawn_not_before==null,u=d?await j(a,this.#r()):{failures:n,notBefore:a.respawn_not_before,exhausted:n>=U};if(u.exhausted){await T(e,{failures:u.failures,notBefore:null});const l=`Child crashed \u2014 ${p(r)} (${e}) kept dying without settling a turn (${u.failures} consecutive launches) and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`;await this.#s(e,r,{event:"broker.respawn.exhausted",reason:"crash_looped",detail:{schema:"crtr.node-outcome-detail/v1",message:l,respawn_failures:u.failures},wake:l,...r.pi_session_id!=null?{surface:c(()=>ie(r),"surface")}:{}});return}if(d&&u.notBefore!==null){f({level:"info",event:"broker.respawn.deferred",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,backoff_ms:K(u.failures),consecutive_failures:u.failures}});return}f({level:"info",event:"broker.respawn.started",...o(e)?{node_id:e}:{},fields:{...o(e)?{}:{affected_node_id:e},action:t,consecutive_failures:u.failures}});try{await Q(e,{capacity:"freeze",resume:t==="respawn-resume",wakeReason:t==="respawn-resume"&&s?"runtime-restart-abort":void 0,recovery:!0})}catch(l){if(I(l)||l instanceof ee){await h(e),await v(e,"release"),f({level:"warn",event:"node.start.refused",node_id:e,error:l,fields:{enact:"respawn"}}),await Z(l);return}f({level:"error",event:"broker.respawn.failed",...o(e)?{node_id:e}:{},error:l,fields:{...o(e)?{}:{affected_node_id:e},action:t}}),await this.terminalizeIfStillNonTerminal(e,"broker.respawn.refused",l,"launch_failed",{schema:"crtr.node-outcome-detail/v1",message:l instanceof Error?l.message:String(l)})}}async#s(e,r,t){f({level:"error",event:t.event,...o(e)?{node_id:e}:{fields:{affected_node_id:e}}}),await v(e,"crash",{reason:t.reason,outcome:{detail:t.detail}});try{await(t.surface??(()=>$(r)))()}catch(s){f({level:"error",event:"broker.boot_failure_surface.failed",...o(e)?{node_id:e}:{fields:{affected_node_id:e}},error:s})}await L(e,"notice.crash",t.wake,{reason:"child-crashed",child:e})}}export{Ne as DaemonFleet,ae as classifyDeadNode,$ as surfaceBootFailure};
@@ -1 +1 @@
1
- var N=Object.defineProperty;var s=(i,t)=>N(i,"name",{value:t,configurable:!0});import{clearFrozen as w,getNode as y,getRow as D}from"../../../core/canvas/index.js";import{openDb as _}from"../../../core/canvas/db.js";import{fullName as T}from"../../../core/canvas/labels.js";import{isSafeNodeId as l}from"../../../core/canvas/paths.js";import{emitEvent as u}from"../../../core/events/emit.js";import{operationIdContext as z}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as C}from"../../../core/canvas/deliveries.js";import{publishNotice as L}from"../../../core/runtime/close.js";import{transition as p}from"../../../core/runtime/lifecycle.js";import{isStartRefusal as h}from"../../../core/runtime/start-check.js";import{EnvironmentImagePending as A}from"./remote-wake.js";import{asNodePerson as M}from"./node-person.js";import{MachineOfflineError as m}from"../../../core/runtime/runner/machine/ops.js";import{commitReopenResident as b}from"../../../core/runtime/reopen.js";import{reviveNode as E}from"../../../core/runtime/revive.js";import{hasPendingWake as k}from"../live-obligation.js";import{readInterruptedTurn as I}from"../../../core/canvas/recovery.js";import{mapAsync as O}from"../../../core/async-array.js";const R=6,P=10*6e4,U=2e4;async function x(i){const t=await(await _()).prepare("SELECT idle_release_attempts, idle_release_last_attempt_at, idle_release_acked_count FROM nodes WHERE node_id = ?").get(i);return{attempts:Number(t?.idle_release_attempts??0),acknowledgedCount:Number(t?.idle_release_acked_count??0),lastAttempt:t?.idle_release_last_attempt_at==null?void 0:Date.parse(t.idle_release_last_attempt_at)}}s(x,"readEpisode");async function H(i,t,a,e,n){const o=await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ? AND idle_release_attempts = ?").run(a,new Date(n).toISOString(),e,i,t);return Number(o.changes)===1}s(H,"claimAttempt");async function F(i,t){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ?").run(t.attempts,t.lastAttempt===void 0?null:new Date(t.lastAttempt).toISOString(),t.acknowledgedCount,i)}s(F,"writeEpisode");function W(i,t){if(t)return 2;const a=i.launched_at;if(a==null)return 1;const e=i.last_settled_at;return e==null?2:Date.parse(e)>Date.parse(a)?1:2}s(W,"thawTier");function $(i,t){const a=i.row.frozen_at,e=t.row.frozen_at;return a==null?e==null?0:1:e==null?-1:Date.parse(a)-Date.parse(e)}s($,"compareThaw");const B=16;class le{static{s(this,"FreezeLaneReconciler")}async endEpisode(t){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = 0, idle_release_last_attempt_at = NULL, idle_release_acked_count = 0 WHERE node_id = ? AND (idle_release_attempts <> 0 OR idle_release_last_attempt_at IS NOT NULL OR idle_release_acked_count <> 0)").run(t)}async run(t,a){const e=await O(a.candidates,async r=>({...r,tier:W(r.row,await k(r.row.node_id))}));e.sort($);const n={stalled:0,waitingOnMail:0};let o=0;const d=s(async()=>{for(;o<e.length;){const r=e[o++];await z.fresh(()=>M(r.row,()=>this.enact(t,r,a.fleet)))==="frozen"&&(r.tier===1?n.stalled+=1:n.waitingOnMail+=1)}},"worker");return await Promise.all(Array.from({length:Math.min(B,e.length)},d)),n}async enact(t,a,e){const n=a.row.node_id;try{return a.enact==="thaw"?await this.enactThaw(a.row):a.enact==="reopen"?await this.enactReopen(a.row):a.enact==="idle-release"?await this.enactIdleRelease(t,a.row):(await e.applyDeadRowPolicy(n),await e.has(n)?"launched":(await D(n))?.frozen_at!=null?"frozen":"skipped")}catch(o){return u({level:"error",event:"node.lifecycle.enact_failed",...l(n)?{node_id:n}:{},error:o,fields:{...l(n)?{}:{affected_node_id:n},enact:a.enact}}),"skipped"}}async enactReopen(t){await b(t.node_id);try{return(await E(t.node_id,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":"launched"}catch(a){if(h(a)||a instanceof A||a instanceof m)return await this.settleRefusedStart(t.node_id,a,"reopen");throw a}}async settleRefusedStart(t,a,e){return a instanceof m&&a.sent||await p(t,"release"),await w(t),u({level:"warn",event:"node.start.refused",node_id:t,error:a,fields:{enact:e}}),"skipped"}async enactThaw(t){const a=(await I(t.node_id))?.interrupted===!0;if(!a&&t.lifecycle==="resident"&&(await y(t.node_id))?.pi_session_id!=null&&!await k(t.node_id))return await p(t.node_id,"release"),await w(t.node_id),"skipped";try{return(await E(t.node_id,{resume:!0,capacity:"freeze",recovery:!0,...a?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}catch(e){if(h(e)||e instanceof A||e instanceof m)return await this.settleRefusedStart(t.node_id,e,"thaw");const n=await y(t.node_id);throw n!==null&&(n.status==="active"||n.status==="idle")&&(await p(t.node_id,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}),await w(t.node_id)),e}}async enactIdleRelease(t,a){const e=a.node_id,n=await C(e),o=await x(e),d=o.attempts===0||o.acknowledgedCount!==n,r=d?0:o.attempts;if(r>=R)return await this.endEpisode(e),u({level:"warn",event:"broker.idle_release.exhausted",...l(e)?{node_id:e}:{},fields:{...l(e)?{}:{affected_node_id:e},attempts:r,max_attempts:R}}),await p(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:r}}}),await L(e,"notice.crash",`Child crashed \u2014 ${T(a)} (${e}) failed to relaunch after ${r} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e}),"skipped";const f=d?void 0:o.lastAttempt,S=Math.min(U*2**r,P);if(f!==void 0&&t-f<S||!await H(e,o.attempts,r+1,n,t))return"skipped";const g=s(()=>F(e,{attempts:d?0:r,lastAttempt:d?void 0:o.lastAttempt,acknowledgedCount:n}),"giveBack");let v;try{v=await E(e,{resume:!0,capacity:"freeze"})}catch(c){if(!(c instanceof m||h(c)))throw c;return await g(),await this.settleRefusedStart(e,c,"idle-release")}return v.outcome==="frozen"?(await g(),"frozen"):(u({level:"info",event:"broker.revive.idle_release",...l(e)?{node_id:e}:{},attempt:r+1,fields:{...l(e)?{}:{affected_node_id:e},attempts:r+1,max_attempts:R}}),"launched")}}export{le as FreezeLaneReconciler,$ as compareThaw,W as thawTier};
1
+ var N=Object.defineProperty;var s=(i,t)=>N(i,"name",{value:t,configurable:!0});import{clearFrozen as w,getNode as y,getRow as D}from"../../../core/canvas/index.js";import{openDb as _}from"../../../core/canvas/db.js";import{fullName as T}from"../../../core/canvas/labels.js";import{isSafeNodeId as l}from"../../../core/canvas/paths.js";import{emitEvent as u}from"../../../core/events/emit.js";import{operationIdContext as z}from"../../../core/events/operation-id.js";import{acknowledgedNodeMailCount as C}from"../../../core/canvas/deliveries.js";import{publishNotice as L}from"../../../core/runtime/close.js";import{transition as p}from"../../../core/runtime/lifecycle.js";import{noticeStartRefusalError as M}from"../../../core/runtime/start-refusal-notice.js";import{isStartRefusal as h}from"../../../core/runtime/start-check.js";import{EnvironmentImagePending as A}from"./remote-wake.js";import{asNodePerson as b}from"./node-person.js";import{MachineOfflineError as m}from"../../../core/runtime/runner/machine/ops.js";import{commitReopenResident as I}from"../../../core/runtime/reopen.js";import{reviveNode as E}from"../../../core/runtime/revive.js";import{hasPendingWake as k}from"../live-obligation.js";import{readInterruptedTurn as O}from"../../../core/canvas/recovery.js";import{mapAsync as P}from"../../../core/async-array.js";const R=6,U=10*6e4,x=2e4;async function H(i){const t=await(await _()).prepare("SELECT idle_release_attempts, idle_release_last_attempt_at, idle_release_acked_count FROM nodes WHERE node_id = ?").get(i);return{attempts:Number(t?.idle_release_attempts??0),acknowledgedCount:Number(t?.idle_release_acked_count??0),lastAttempt:t?.idle_release_last_attempt_at==null?void 0:Date.parse(t.idle_release_last_attempt_at)}}s(H,"readEpisode");async function F(i,t,a,e,r){const o=await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ? AND idle_release_attempts = ?").run(a,new Date(r).toISOString(),e,i,t);return Number(o.changes)===1}s(F,"claimAttempt");async function W(i,t){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = ?, idle_release_last_attempt_at = ?, idle_release_acked_count = ? WHERE node_id = ?").run(t.attempts,t.lastAttempt===void 0?null:new Date(t.lastAttempt).toISOString(),t.acknowledgedCount,i)}s(W,"writeEpisode");function $(i,t){if(t)return 2;const a=i.launched_at;if(a==null)return 1;const e=i.last_settled_at;return e==null?2:Date.parse(e)>Date.parse(a)?1:2}s($,"thawTier");function B(i,t){const a=i.row.frozen_at,e=t.row.frozen_at;return a==null?e==null?0:1:e==null?-1:Date.parse(a)-Date.parse(e)}s(B,"compareThaw");const X=16;class _e{static{s(this,"FreezeLaneReconciler")}async endEpisode(t){await(await _()).prepare("UPDATE nodes SET idle_release_attempts = 0, idle_release_last_attempt_at = NULL, idle_release_acked_count = 0 WHERE node_id = ? AND (idle_release_attempts <> 0 OR idle_release_last_attempt_at IS NOT NULL OR idle_release_acked_count <> 0)").run(t)}async run(t,a){const e=await P(a.candidates,async n=>({...n,tier:$(n.row,await k(n.row.node_id))}));e.sort(B);const r={stalled:0,waitingOnMail:0};let o=0;const d=s(async()=>{for(;o<e.length;){const n=e[o++];await z.fresh(()=>b(n.row,()=>this.enact(t,n,a.fleet)))==="frozen"&&(n.tier===1?r.stalled+=1:r.waitingOnMail+=1)}},"worker");return await Promise.all(Array.from({length:Math.min(X,e.length)},d)),r}async enact(t,a,e){const r=a.row.node_id;try{return a.enact==="thaw"?await this.enactThaw(a.row):a.enact==="reopen"?await this.enactReopen(a.row):a.enact==="idle-release"?await this.enactIdleRelease(t,a.row):(await e.applyDeadRowPolicy(r),await e.has(r)?"launched":(await D(r))?.frozen_at!=null?"frozen":"skipped")}catch(o){return u({level:"error",event:"node.lifecycle.enact_failed",...l(r)?{node_id:r}:{},error:o,fields:{...l(r)?{}:{affected_node_id:r},enact:a.enact}}),"skipped"}}async enactReopen(t){await I(t.node_id);try{return(await E(t.node_id,{resume:!0,capacity:"freeze"})).outcome==="frozen"?"frozen":"launched"}catch(a){if(h(a)||a instanceof A||a instanceof m)return await this.settleRefusedStart(t.node_id,a,"reopen");throw a}}async settleRefusedStart(t,a,e){return a instanceof m&&a.sent||await p(t,"release"),await w(t),u({level:"warn",event:"node.start.refused",node_id:t,error:a,fields:{enact:e}}),await M(a),"skipped"}async enactThaw(t){const a=(await O(t.node_id))?.interrupted===!0;if(!a&&t.lifecycle==="resident"&&(await y(t.node_id))?.pi_session_id!=null&&!await k(t.node_id))return await p(t.node_id,"release"),await w(t.node_id),"skipped";try{return(await E(t.node_id,{resume:!0,capacity:"freeze",recovery:!0,...a?{wakeReason:"runtime-restart-abort"}:{}})).outcome==="frozen"?"frozen":"launched"}catch(e){if(h(e)||e instanceof A||e instanceof m)return await this.settleRefusedStart(t.node_id,e,"thaw");const r=await y(t.node_id);throw r!==null&&(r.status==="active"||r.status==="idle")&&(await p(t.node_id,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",message:e instanceof Error?e.message:String(e)}}}),await w(t.node_id)),e}}async enactIdleRelease(t,a){const e=a.node_id,r=await C(e),o=await H(e),d=o.attempts===0||o.acknowledgedCount!==r,n=d?0:o.attempts;if(n>=R)return await this.endEpisode(e),u({level:"warn",event:"broker.idle_release.exhausted",...l(e)?{node_id:e}:{},fields:{...l(e)?{}:{affected_node_id:e},attempts:n,max_attempts:R}}),await p(e,"crash",{reason:"launch_failed",outcome:{detail:{schema:"crtr.node-outcome-detail/v1",respawn_failures:n}}}),await L(e,"notice.crash",`Child crashed \u2014 ${T(a)} (${e}) failed to relaunch after ${n} attempts while trying to deliver a pending inbox message (no delivery progress across any attempt), and is now dead. It stays dead until you revive it \u2014 \`crtr node lifecycle revive ${e}\`.`,{reason:"child-crashed",child:e}),"skipped";const f=d?void 0:o.lastAttempt,S=Math.min(x*2**n,U);if(f!==void 0&&t-f<S||!await F(e,o.attempts,n+1,r,t))return"skipped";const g=s(()=>W(e,{attempts:d?0:n,lastAttempt:d?void 0:o.lastAttempt,acknowledgedCount:r}),"giveBack");let v;try{v=await E(e,{resume:!0,capacity:"freeze"})}catch(c){if(!(c instanceof m||h(c)))throw c;return await g(),await this.settleRefusedStart(e,c,"idle-release")}return v.outcome==="frozen"?(await g(),"frozen"):(u({level:"info",event:"broker.revive.idle_release",...l(e)?{node_id:e}:{},attempt:n+1,fields:{...l(e)?{}:{affected_node_id:e},attempts:n+1,max_attempts:R}}),"launched")}}export{_e as FreezeLaneReconciler,B as compareThaw,$ as thawTier};
@@ -7,6 +7,12 @@ 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.783
11
+
12
+ ### Every limit refusal carries `details.payment`
13
+
14
+ A `402 cap_exhausted` now always has `details.payment = { reason, message, pay_url, reset_at }`, whatever limit refused: `app_limit` (link to the app's page on the account site), `card_limit` (billing limit), `card_required`, `operator_stop`, and the new `person_limit` (a limit set with `crtr sys spend`; no link). `message` is the sentence to show the person and is also the error's top-level message. `PAYMENT_REFUSAL_REASONS` gains `operator_stop` and `person_limit`; treat an unknown reason as a sentence with no button. The `nothing_left` link is now `<directory>/account/pay`.
15
+
10
16
  ## 0.3.781
11
17
 
12
18
  `sourcing.read` and `SOURCING_RUN_RULE`. Additive: no request or response an existing app sends or reads changes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.782",
3
+ "version": "0.3.783",
4
4
  "description": "crtr — agent runtime with memory, plugins, and marketplaces",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -157,8 +157,8 @@
157
157
  },
158
158
  "license": "UNLICENSED",
159
159
  "dependencies": {
160
- "@north-light/identity": "0.3.782",
161
- "@north-light/plugin": "0.3.782",
160
+ "@north-light/identity": "0.3.783",
161
+ "@north-light/plugin": "0.3.783",
162
162
  "@earendil-works/chord": "1.5.2",
163
163
  "@earendil-works/pi-agent-core": "1.5.2",
164
164
  "@earendil-works/pi-ai": "1.5.2",
@@ -12,7 +12,7 @@
12
12
  //
13
13
  // PURITY (spec §3.1): Node built-ins + `src/api/*` only.
14
14
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
15
- export const CONTRACT_LEVEL = '1.85';
15
+ export const CONTRACT_LEVEL = '1.86';
16
16
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
17
17
  export const REQUIRED_CONTRACT_HEADER = 'Crouter-Required-Contract';
18
18
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -1,4 +1,4 @@
1
1
  // The money ledger's read and limit surfaces: `charges.list`, `spend_limits.list`, `spend_limits.set`, `spend_limits.remove`.
2
2
  // (`limits.*` and `/v1/limits` are the per-app memory and disk caps; these are dollar limits.)
3
3
  /** Why a call was refused for payment. `reason` is what an app branches on; never the message text. */
4
- export const PAYMENT_REFUSAL_REASONS = ['trial_ended', 'card_required', 'card_limit', 'nothing_left', 'app_limit', 'team_limit', 'app_unpaid', 'account_held'];
4
+ export const PAYMENT_REFUSAL_REASONS = ['trial_ended', 'card_required', 'card_limit', 'nothing_left', 'app_limit', 'team_limit', 'app_unpaid', 'account_held', 'operator_stop', 'person_limit'];
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.782",
3
+ "version": "0.3.783",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.782",
3
+ "version": "0.3.783",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.782",
3
+ "version": "0.3.783",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.782",
31
- "@north-light/identity": "0.3.782"
30
+ "@north-light/api": "0.3.783",
31
+ "@north-light/identity": "0.3.783"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.782",
3
+ "version": "0.3.783",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.782",
9
+ "version": "0.3.783",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.782",
32
- "@north-light/plugin": "0.3.782",
31
+ "@north-light/identity": "0.3.783",
32
+ "@north-light/plugin": "0.3.783",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.782",
11905
+ "version": "0.3.783",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.782",
11910
+ "version": "0.3.783",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.782",
11915
+ "version": "0.3.783",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.782",
11923
+ "version": "0.3.783",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.782",
11927
- "@north-light/identity": "0.3.782"
11926
+ "@north-light/api": "0.3.783",
11927
+ "@north-light/identity": "0.3.783"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.782",
11932
+ "version": "0.3.783",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.782",
11936
- "@north-light/identity": "0.3.782",
11937
- "@north-light/plugin": "0.3.782",
11935
+ "@north-light/api": "0.3.783",
11936
+ "@north-light/identity": "0.3.783",
11937
+ "@north-light/plugin": "0.3.783",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {