@north-light/cli 0.3.598 → 0.3.600

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 (92) 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 +22 -0
  4. package/dist/api/dto/charges.js +1 -0
  5. package/dist/api/dto/modelauth.d.ts +26 -0
  6. package/dist/api/dto/node-outcomes.d.ts +4 -0
  7. package/dist/api/error-codes.d.ts +5 -0
  8. package/dist/api/error-codes.js +1 -1
  9. package/dist/builtin-memory/crouter-sdk/release-notes.md +11 -0
  10. package/dist/cli.js +4 -4
  11. package/dist/clients/attach/viewer.js +503 -503
  12. package/dist/commands/daemon-generation.d.ts +2 -0
  13. package/dist/commands/daemon-generation.js +1 -0
  14. package/dist/commands/sys/join.js +1 -1
  15. package/dist/core/auth-file.d.ts +3 -11
  16. package/dist/core/auth-file.js +1 -1
  17. package/dist/core/canvas/export-sqlite.js +1 -1
  18. package/dist/core/canvas/person.js +7 -7
  19. package/dist/core/canvas/recovery.js +2 -2
  20. package/dist/core/canvas/schema-pg/012-charge-admission.sql +62 -0
  21. package/dist/core/canvas/schema-pg/013-grant-removal-reset.sql +19 -0
  22. package/dist/core/canvas/schema-version.d.ts +1 -1
  23. package/dist/core/canvas/schema-version.js +1 -1
  24. package/dist/core/canvas/types.d.ts +3 -0
  25. package/dist/core/grants/hosted-endpoint.d.ts +28 -0
  26. package/dist/core/grants/hosted-endpoint.js +1 -0
  27. package/dist/core/grants/mirror.d.ts +1 -0
  28. package/dist/core/grants/mirror.js +2 -3
  29. package/dist/core/grants/sync.js +1 -1
  30. package/dist/core/import/load/run.js +2 -2
  31. package/dist/core/import/load/stage.d.ts +1 -1
  32. package/dist/core/import/load/stage.js +1 -1
  33. package/dist/core/import/load/stores.d.ts +2 -0
  34. package/dist/core/import/load/stores.js +2 -2
  35. package/dist/core/ledger/charges.js +1 -1
  36. package/dist/core/ledger/check.js +1 -1
  37. package/dist/core/ledger/chunks.js +2 -2
  38. package/dist/core/ledger/read.js +1 -1
  39. package/dist/core/ledger/types.d.ts +8 -0
  40. package/dist/core/llm/owner-candidates.d.ts +17 -0
  41. package/dist/core/llm/owner-candidates.js +1 -0
  42. package/dist/core/llm/run.js +2 -2
  43. package/dist/core/model-auth/activations.d.ts +37 -0
  44. package/dist/core/model-auth/activations.js +1 -0
  45. package/dist/core/model-auth/flows.js +1 -1
  46. package/dist/core/model-auth/handoff-jti.d.ts +10 -1
  47. package/dist/core/model-auth/handoff-jti.js +1 -1
  48. package/dist/core/model-auth/key-routes.d.ts +30 -0
  49. package/dist/core/model-auth/key-routes.js +1 -0
  50. package/dist/core/model-auth/readiness.d.ts +8 -1
  51. package/dist/core/model-auth/readiness.js +1 -1
  52. package/dist/core/model-config.js +1 -1
  53. package/dist/core/model-routes-pool.d.ts +2 -0
  54. package/dist/core/model-routes-pool.js +1 -1
  55. package/dist/core/model-routes.d.ts +12 -3
  56. package/dist/core/model-routes.js +1 -1
  57. package/dist/core/provider-failure.d.ts +5 -0
  58. package/dist/core/provider-failure.js +1 -1
  59. package/dist/core/providers/call.js +1 -1
  60. package/dist/core/runtime/broker/fault-retry.js +1 -1
  61. package/dist/core/runtime/broker/model-adapter.d.ts +6 -1
  62. package/dist/core/runtime/broker/model-adapter.js +3 -3
  63. package/dist/core/runtime/front-door.js +8 -8
  64. package/dist/core/runtime/launch-target.d.ts +2 -0
  65. package/dist/core/runtime/launch-target.js +1 -1
  66. package/dist/core/runtime/revive.js +2 -2
  67. package/dist/core/runtime/runner/blaxel/image-build.d.ts +4 -0
  68. package/dist/core/runtime/runner/blaxel/image-build.js +4 -4
  69. package/dist/core/runtime/start-check.d.ts +7 -1
  70. package/dist/core/runtime/start-check.js +1 -1
  71. package/dist/daemon/api/app-listener.js +12 -12
  72. package/dist/daemon/api/handlers/llm.js +3 -3
  73. package/dist/daemon/api/handlers/modelauth.js +1 -1
  74. package/dist/daemon/api/handlers/nodes.js +1 -1
  75. package/dist/daemon/api/key-signin.d.ts +9 -0
  76. package/dist/daemon/api/key-signin.js +124 -0
  77. package/dist/daemon/api/principal.d.ts +8 -3
  78. package/dist/daemon/api/principal.js +1 -1
  79. package/dist/daemon/api/server.js +1 -1
  80. package/dist/daemon/api/vendor-signin.d.ts +28 -1
  81. package/dist/daemon/api/vendor-signin.js +42 -24
  82. package/dist/daemon/cron/authority.js +1 -1
  83. package/dist/daemon/crtrd.js +12 -12
  84. package/dist/daemon/reconcilers/broker-supervision.d.ts +2 -2
  85. package/dist/daemon/reconcilers/broker-supervision.js +2 -2
  86. package/dist/daemon/reconcilers/grant-effects.js +1 -1
  87. package/dist/daemon/reconcilers/ledger-r2.js +6 -6
  88. package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
  89. package/docs/sdk/release-notes.md +11 -0
  90. package/package.json +2 -2
  91. package/packages/crouter-identity/package.json +1 -1
  92. package/runtime.lock.json +13 -13
@@ -1,24 +1,24 @@
1
- var Q=Object.defineProperty;var i=(e,n)=>Q(e,"name",{value:n,configurable:!0});import{AsyncResource as W}from"node:async_hooks";import{randomUUID as q}from"node:crypto";import{createServer as K}from"node:http";import{Router as V,causedByOf as Z}from"./router.js";import{toErrorBody as ee}from"./map.js";import{objectRoutes as te}from"./handlers/objects.js";import{customObjectRoutes as ne}from"./handlers/custom-objects.js";import{checkRoutes as re}from"./handlers/check.js";import{chargeRoutes as ae}from"./handlers/charges.js";import{docRoutes as oe}from"./handlers/docs.js";import{relationRoutes as ie}from"./handlers/relations.js";import{schemaRoutes as se}from"./handlers/schemas.js";import{OPERATIONS as ue}from"./operations.js";import{runtimeReadiness as de}from"../readiness.js";import{errorCodes as X}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as ce,RUNTIME_VERSION_HEADER as le,minimumRuntimeRefusal as me}from"../../api/runtime-version.js";import{CONTRACT_HEADER as fe,CONTRACT_LEVEL as $,REQUIRED_CONTRACT_HEADER as pe,contractRefusal as he}from"../../api/contract.js";import{crtrVersion as j}from"../../shared/crtr-version.js";import{newTraceId as we,parseTraceparent as ye}from"../../shared/traceparent.js";import{AppPrincipalResolver as _e}from"./principal.js";import{isDaemonRoute as ge,runtimeOwner as ve,servePeer as z}from"../peer/ingress.js";import{applySyncNotice as Re}from"./sync-notice.js";import{ownMachineId as Oe}from"../../core/peer/directory.js";import{handleRunOperation as be,integer as Ee}from"./handlers/runs.js";import{llmCallerOf as Ae,parseLlmRequest as Se,runLlm as Te}from"../../core/llm/run.js";import{parseUsageMonth as Ne,usageFor as Ce}from"../../core/ledger/index.js";import{capFields as Ie}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as Pe,MODEL_CONTEXT_BODY_MAX_BYTES as ke}from"../../core/llm/body-limits.js";import{RunError as m,cloudPersonScope as He,runIsRunning as Me}from"../../core/runs/operations.js";import{requireRun as J}from"./router.js";import{deferHead as De}from"./deferred-head.js";import{readRunEvents as G,registerGrantStream as xe,subscribeRunEvents as Be}from"../../core/runs/events.js";import{activeGrant as Y,payerOfGrant as je}from"../../core/grants/mirror.js";async function Je(e){if(await je(e)==="app")throw new m(401,"grant_revoked","this app-paid grant is no longer active");return null}i(Je,"appPaidGone");import{releaseGrantWaiters as Le}from"../../core/grants/watch.js";import{emitEvent as Ue}from"../../core/events/emit.js";import{runNotices as Ve}from"../run-notices.js";import{handleVendorSignIn as Xe,isVendorSignInPath as $e}from"./vendor-signin.js";import{listAppProfiles as ze}from"./handlers/app-profiles.js";import{handleTransferDownload as Ge,handleTransferOperation as Ye,TRANSFER_OPERATIONS as Fe}from"./handlers/transfer.js";import{handleQuestionOperation as Qe,QUESTION_OPERATIONS as We}from"./handlers/questions.js";import{removeVendorAccount as qe,vendorStatus as Ke}from"./handlers/vendor-status.js";import{handleMemoryOperation as Ze,MEMORY_OPERATIONS as et}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as tt,handleExec as nt}from"./handlers/exec.js";import{abortOnClose as F,callerFromApp as rt,handleProviderOperation as at,PROVIDER_OPERATIONS as ot,providerFailure as it}from"./handlers/providers.js";function st(e){return Object.prototype.hasOwnProperty.call(X,e)?X[e]:void 0}i(st,"fixedRow");function ut(e){const n=st(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(ut,"errorType");function dt(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(dt,"appDetails");function B(e,n,o){const l=dt(e.details);return{error:{code:e.code,message:e.message,...l===void 0?{}:{details:l},type:ut(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:n,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...Ie(e),...e.code==="all_routes_exhausted"?{retry_after_s:e.details.retry_after_s}:{}}}}i(B,"envelope");function ct(e,n,o,l,d){const w=n instanceof m?n:new m(500,"server_failure","runtime request failed");if(n instanceof m||console.error("[app-listener]",`trace_id=${l}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
1
+ var W=Object.defineProperty;var i=(e,n)=>W(e,"name",{value:n,configurable:!0});import{AsyncResource as q}from"node:async_hooks";import{randomUUID as K}from"node:crypto";import{createServer as Z}from"node:http";import{Router as $,causedByOf as ee}from"./router.js";import{toErrorBody as te}from"./map.js";import{objectRoutes as ne}from"./handlers/objects.js";import{customObjectRoutes as re}from"./handlers/custom-objects.js";import{checkRoutes as ae}from"./handlers/check.js";import{chargeRoutes as oe}from"./handlers/charges.js";import{docRoutes as ie}from"./handlers/docs.js";import{relationRoutes as se}from"./handlers/relations.js";import{schemaRoutes as ue}from"./handlers/schemas.js";import{OPERATIONS as de}from"./operations.js";import{runtimeReadiness as ce}from"../readiness.js";import{errorCodes as V}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as me,RUNTIME_VERSION_HEADER as fe,minimumRuntimeRefusal as le}from"../../api/runtime-version.js";import{CONTRACT_HEADER as pe,CONTRACT_LEVEL as z,REQUIRED_CONTRACT_HEADER as he,contractRefusal as we}from"../../api/contract.js";import{crtrVersion as J}from"../../shared/crtr-version.js";import{newTraceId as ye,parseTraceparent as _e}from"../../shared/traceparent.js";import{AppPrincipalResolver as ge}from"./principal.js";import{isDaemonRoute as ve,runtimeOwner as Re,servePeer as G}from"../peer/ingress.js";import{applySyncNotice as Oe}from"./sync-notice.js";import{ownMachineId as be}from"../../core/peer/directory.js";import{handleRunOperation as Ee,integer as Ae}from"./handlers/runs.js";import{llmCallerOf as Se,parseLlmRequest as Te,runLlm as Ne}from"../../core/llm/run.js";import{parseUsageMonth as Ce,usageFor as Ie}from"../../core/ledger/index.js";import{capFields as Pe}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as ke,MODEL_CONTEXT_BODY_MAX_BYTES as He}from"../../core/llm/body-limits.js";import{RunError as f,cloudPersonScope as Me,runIsRunning as De}from"../../core/runs/operations.js";import{requireRun as L}from"./router.js";import{deferHead as xe}from"./deferred-head.js";import{readRunEvents as Y,registerGrantStream as Be,subscribeRunEvents as je}from"../../core/runs/events.js";import{activeGrant as F,payerOfGrant as Je}from"../../core/grants/mirror.js";async function Le(e){if(await Je(e)==="app")throw new f(401,"grant_revoked","this app-paid grant is no longer active");return null}i(Le,"appPaidGone");import{releaseGrantWaiters as Ue}from"../../core/grants/watch.js";import{emitEvent as Xe}from"../../core/events/emit.js";import{runNotices as $e}from"../run-notices.js";import{handleRuntimeSignIn as Ve,isRuntimeSignInPath as ze}from"./key-signin.js";import{listAppProfiles as Ge}from"./handlers/app-profiles.js";import{handleTransferDownload as Ye,handleTransferOperation as Fe,TRANSFER_OPERATIONS as Qe}from"./handlers/transfer.js";import{handleQuestionOperation as We,QUESTION_OPERATIONS as qe}from"./handlers/questions.js";import{removeVendorAccount as Ke,vendorStatus as Ze}from"./handlers/vendor-status.js";import{handleMemoryOperation as et,MEMORY_OPERATIONS as tt}from"./handlers/memory.js";import{EXEC_BODY_MAX_BYTES as nt,handleExec as rt}from"./handlers/exec.js";import{abortOnClose as Q,callerFromApp as at,handleProviderOperation as ot,PROVIDER_OPERATIONS as it,providerFailure as st}from"./handlers/providers.js";function ut(e){return Object.prototype.hasOwnProperty.call(V,e)?V[e]:void 0}i(ut,"fixedRow");function dt(e){const n=ut(e);return n?n.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}i(dt,"errorType");function ct(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:n,...o}=e;return o}i(ct,"appDetails");function B(e,n,o){const m=ct(e.details);return{error:{code:e.code,message:e.message,...m===void 0?{}:{details:m},type:dt(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:n,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...Pe(e),...j(e)!==void 0?{retry_after_s:j(e)}:{}}}}i(B,"envelope");const j=i(e=>e.code==="all_routes_exhausted"?e.details.retry_after_s:void 0,"retryAfterOf");function mt(e,n,o,m,d){const w=n instanceof f?n:new f(500,"server_failure","runtime request failed");if(n instanceof f||console.error("[app-listener]",`trace_id=${m}`,n),e.headersSent&&!String(e.getHeader("Content-Type")??"").startsWith("text/event-stream")){e.destroy();return}if(e.headersSent){e.end(`event: error
2
2
  data: ${JSON.stringify(B(w,o,d))}
3
3
 
4
- `);return}e.writeHead(w.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...w.code==="all_routes_exhausted"?{"Retry-After":String(w.details.retry_after_s)}:{}}),e.end(JSON.stringify(B(w,o,d)))}i(ct,"fail");function L(e){return Array.isArray(e)?e[0]:e}i(L,"headerValue");function g(e,n,o){e.writeHead(n,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(g,"json");async function I(e,n=Pe){const o=[];let l=0;for await(const d of e){if(l+=d.length,l>n)throw new m(400,"invalid_request","request body too large");o.push(d)}if(l)try{return JSON.parse(Buffer.concat(o).toString("utf8"))}catch{throw new m(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function lt(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new m(400,"invalid_request","invalid cursor","after");return Ee(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(lt,"cursor");function mt(e){return`id: ${e.sequence_number}
4
+ `);return}e.writeHead(w.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...j(w)!==void 0?{"Retry-After":String(j(w))}:{}}),e.end(JSON.stringify(B(w,o,d)))}i(mt,"fail");function U(e){return Array.isArray(e)?e[0]:e}i(U,"headerValue");function g(e,n,o){e.writeHead(n,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}i(g,"json");async function I(e,n=ke){const o=[];let m=0;for await(const d of e){if(m+=d.length,m>n)throw new f(400,"invalid_request","request body too large");o.push(d)}if(m)try{return JSON.parse(Buffer.concat(o).toString("utf8"))}catch{throw new f(400,"invalid_request","invalid JSON body")}}i(I,"bodyOf");function ft(e,n){const o=e.headers["last-event-id"]??n.get("after");if(Array.isArray(o))throw new f(400,"invalid_request","invalid cursor","after");return Ae(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}i(ft,"cursor");function lt(e){return`id: ${e.sequence_number}
5
5
  event: ${e.type}
6
6
  data: ${JSON.stringify(e)}
7
7
 
8
- `}i(mt,"frame");const ft=6e4;async function pt(e,n,o,l,d,w,A,S={},r){await J(l,o);let t=await G(o,d);if(d>t.latest_sequence)throw new m(400,"invalid_request","cursor is beyond the run","after");if(d<t.latest_sequence&&(t.earliest_sequence===null||d<t.earliest_sequence-1))throw new m(409,"stream_gap","events have expired",void 0,{earliest_sequence:t.earliest_sequence,latest_sequence:t.latest_sequence});if(n.destroyed)return n.destroy(),Promise.resolve();n.writeHead(200,{"Content-Type":A==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),A==="sse"?n.write(`: connected
8
+ `}i(lt,"frame");const pt=6e4;async function ht(e,n,o,m,d,w,A,S={},r){await L(m,o);let t=await Y(o,d);if(d>t.latest_sequence)throw new f(400,"invalid_request","cursor is beyond the run","after");if(d<t.latest_sequence&&(t.earliest_sequence===null||d<t.earliest_sequence-1))throw new f(409,"stream_gap","events have expired",void 0,{earliest_sequence:t.earliest_sequence,latest_sequence:t.latest_sequence});if(n.destroyed)return n.destroy(),Promise.resolve();n.writeHead(200,{"Content-Type":A==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),A==="sse"?n.write(`: connected
9
9
 
10
- `):n.flushHeaders();let p=d;const y=await Ve().streamOpened(o);let v=!1,T=!1,N=!1,O;const h=new Promise(f=>{O=f}),R=i(()=>{v||(v=!0,y(p).catch(f=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],f)),clearInterval(x),clearInterval(H),C(),u(),n.off("close",R),n.off("drain",a),n.end(),O())},"end"),a=i(()=>{N=!1,b()},"onDrain"),M=i(f=>{v||n.write(A==="sse"?`event: error
11
- data: ${JSON.stringify(B(f,w,o))}
10
+ `):n.flushHeaders();let p=d;const y=await $e().streamOpened(o);let v=!1,T=!1,N=!1,O;const h=new Promise(l=>{O=l}),R=i(()=>{v||(v=!0,y(p).catch(l=>console.error("[app-listener]",...r===void 0?[]:[`trace_id=${r}`],l)),clearInterval(x),clearInterval(H),C(),u(),n.off("close",R),n.off("drain",a),n.end(),O())},"end"),a=i(()=>{N=!1,b()},"onDrain"),M=i(l=>{v||n.write(A==="sse"?`event: error
11
+ data: ${JSON.stringify(B(l,w,o))}
12
12
 
13
- `:`${JSON.stringify({type:"error",...B(f,w,o)})}
14
- `),R()},"error"),b=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await J(l,o),t=await G(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){M(new m(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const f of t.events){if(N)break;N=!n.write(A==="sse"?mt(f):`${JSON.stringify(f)}
15
- `),p=f.sequence_number}}catch(f){M(f instanceof m?f:new m(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>M(new m(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in l||await Y(l.grant)!==null,"grantActive"),C=await Be(o,W.bind(b)),u="class"in l?()=>{}:xe(l.grant,P),x=setInterval(()=>{!v&&!N&&A==="sse"&&n.write(`: keepalive
13
+ `:`${JSON.stringify({type:"error",...B(l,w,o)})}
14
+ `),R()},"error"),b=i(async()=>{if(!(v||T)){T=!0;try{if(!await D()){P();return}if(await L(m,o),t=await Y(o,p),t.backlog_count>1e3||t.backlog_bytes>32*1024*1024){M(new f(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:p}));return}for(const l of t.events){if(N)break;N=!n.write(A==="sse"?lt(l):`${JSON.stringify(l)}
15
+ `),p=l.sequence_number}}catch(l){M(l instanceof f?l:new f(500,"server_failure","stream failed"))}finally{T=!1}}},"flush"),P=i(()=>M(new f(401,"grant_revoked","grant is not active")),"revoked"),D=i(async()=>"class"in m||await F(m.grant)!==null,"grantActive"),C=await je(o,q.bind(b)),u="class"in m?()=>{}:Be(m.grant,P),x=setInterval(()=>{!v&&!N&&A==="sse"&&n.write(`: keepalive
16
16
 
17
- `)},15e3),s=S.idleMs??ft,_=S.isRunning??Me;let c=Date.now(),E=p;const k=i(async()=>{if(v||A!=="sse")return;const f=Date.now();let U=!0;try{U=await _(o)}catch{}if(!v){if(U||p!==E){c=f,E=p;return}f-c<s||N||(n.write(`event: idle
17
+ `)},15e3),s=S.idleMs??pt,_=S.isRunning??De;let c=Date.now(),E=p;const k=i(async()=>{if(v||A!=="sse")return;const l=Date.now();let X=!0;try{X=await _(o)}catch{}if(!v){if(X||p!==E){c=l,E=p;return}l-c<s||N||(n.write(`event: idle
18
18
  data: {}
19
19
 
20
- `),R())}},"checkIdle"),H=setInterval(()=>{k().catch(f=>Ue({level:"error",event:"api.run_stream.idle_check_failed",error:f}))},S.idleCheckMs??1e3);return H.unref(),n.on("drain",a),n.on("close",R),await b(),h}i(pt,"streamRunEvents");function ht(e,n,o,l={}){const d=new V,w=new Map;for(const r of ue.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");d.register({method:r.method,pattern:r.path,handler:t}),w.set(t,r)}const A=new V().registerAll(te).registerAll(ne).registerAll(oe).registerAll(se).registerAll(ie).registerAll(re).registerAll(ae);return i((r,t,p)=>(async()=>{De(r,t,l.deferHead);const y=q();t.setHeader("Request-Id",y);const v=ye(L(r.headers.traceparent))??we();t.setHeader(le,j()),t.setHeader(fe,$);let T;try{const N=L(r.headers[ce.toLowerCase()]),O=me(N,j())??he(L(r.headers[pe.toLowerCase()]),$,{legacyMinimum:N,runtimeVersion:j()});if(O!==null)throw O.status===400?new m(400,O.code,O.message,O.param):new m(426,O.code,O.message,void 0,O.details);const h=new URL(r.url??"/","http://runtime.local");if($e(h.pathname)){await Xe(r,t,h,e);return}const R=d.match(r.method??"GET",h.pathname),a=R?w.get(R.handler):void 0,M=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status"||a?.name==="runtime.vendor-account-remove";let b,P;if(p!==void 0)b=p;else if(!M&&r.headers.authorization!==void 0)try{b=await e.verifyCall(r.headers.authorization)}catch(s){P=s}const D={issuer:e.issuer,jwks:e.jwks,audience:i(async()=>e.audience,"audience"),owner:ve,self:Oe,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(b?.chain[0]?.sub.startsWith("runtime:")){await z(r,t,D,b);return}if(b===void 0&&a===void 0&&await ge(r.method??"GET",h.pathname)){await z(r,t,D,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const s=await n(),_=await de({jwksReady:e.isReady(),grantsReady:i(()=>s,"grantsReady")});g(t,_.ready?200:503,_);return}if((r.method!=="GET"||h.pathname!=="/v1/health")&&(!e.isReady()||!await n()))throw new m(503,"runtime_starting","runtime_starting");if(!R||!a)throw new m(404,"not_found","unknown operation");T=R.params.run_id;const C=Z(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Re(await e.verifySyncNotice(r.headers.authorization),o,y),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_status"),g(t,200,await Ke());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await qe(await I(r)));return}if(b===void 0)throw P??new m(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(b,a.scope);if(t.setHeader("Request-Id",y),T&&await J(u,T,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=A.match(a.method,h.pathname);if(!s)throw new m(404,"not_found","unknown operation");const _={...C===void 0?{}:{causedBy:C},method:a.method,path:h.pathname,params:s.params,query:h.searchParams,body:await I(r,s.maxBodyBytes),ceiling:u.resolved,principal:{class:"app",app:u.grantee,scopes:u.resolved,sub:u.sub},req:r,res:t};let c;try{c=await s.handler(_)}catch(E){const{status:k,body:H}=ee(E);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,E),new m(k,H.error.code,H.error.message,void 0,H.error.details)}if(t.headersSent)return;if(c.rawBody!==void 0||c.status===204||c.body===void 0){t.writeHead(c.status,c.headers??{}),t.end(c.rawBody);return}t.writeHead(c.status,{"Content-Type":"application/json; charset=utf-8",...c.headers??{}}),t.end(JSON.stringify(c.body));return}if(a.stream==="bytes"){await Ge(r,t,u,h.searchParams);return}if(a.stream){await pt(r,t,T,u,lt(r,h.searchParams),y,"sse",l.stream,v);return}if(a.name==="llm"){const s=Se(await I(r,ke)),_=new AbortController,c=i(()=>_.abort(),"abort");t.on("close",c);try{const E=await Te(s,_.signal,s.stream?k=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(k)}
20
+ `),R())}},"checkIdle"),H=setInterval(()=>{k().catch(l=>Xe({level:"error",event:"api.run_stream.idle_check_failed",error:l}))},S.idleCheckMs??1e3);return H.unref(),n.on("drain",a),n.on("close",R),await b(),h}i(ht,"streamRunEvents");function wt(e,n,o,m={}){const d=new $,w=new Map;for(const r of de.filter(t=>t.stage!==void 0)){const t=i(()=>({status:500}),"handler");d.register({method:r.method,pattern:r.path,handler:t}),w.set(t,r)}const A=new $().registerAll(ne).registerAll(re).registerAll(ie).registerAll(ue).registerAll(se).registerAll(ae).registerAll(oe);return i((r,t,p)=>(async()=>{xe(r,t,m.deferHead);const y=K();t.setHeader("Request-Id",y);const v=_e(U(r.headers.traceparent))??ye();t.setHeader(fe,J()),t.setHeader(pe,z);let T;try{const N=U(r.headers[me.toLowerCase()]),O=le(N,J())??we(U(r.headers[he.toLowerCase()]),z,{legacyMinimum:N,runtimeVersion:J()});if(O!==null)throw O.status===400?new f(400,O.code,O.message,O.param):new f(426,O.code,O.message,void 0,O.details);const h=new URL(r.url??"/","http://runtime.local");if(ze(h.pathname)){await Ve(r,t,h,e);return}const R=d.match(r.method??"GET",h.pathname),a=R?w.get(R.handler):void 0,M=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status"||a?.name==="runtime.vendor-account-remove";let b,P;if(p!==void 0)b=p;else if(!M&&r.headers.authorization!==void 0)try{b=await e.verifyCall(r.headers.authorization)}catch(s){P=s}const D={issuer:e.issuer,jwks:e.jwks,audience:i(async()=>e.audience,"audience"),owner:Re,self:be,syncGrants:o,ready:i(async()=>e.isReady()&&await n(),"ready")};if(b?.chain[0]?.sub.startsWith("runtime:")){await G(r,t,D,b);return}if(b===void 0&&a===void 0&&await ve(r.method??"GET",h.pathname)){await G(r,t,D,{status:401,code:"unauthorized",message:P===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const s=await n(),_=await ce({jwksReady:e.isReady(),grantsReady:i(()=>s,"grantsReady")});g(t,_.ready?200:503,_);return}if((r.method!=="GET"||h.pathname!=="/v1/health")&&(!e.isReady()||!await n()))throw new f(503,"runtime_starting","runtime_starting");if(!R||!a)throw new f(404,"not_found","unknown operation");T=R.params.run_id;const C=ee(r.headers);if(a.name==="health"){g(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await Oe(await e.verifySyncNotice(r.headers.authorization),o,y),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_status"),g(t,200,await Ze());return}if(a.name==="runtime.vendor-account-remove"){await e.verifyDirectoryRead(r.headers.authorization,"vendor_account_remove"),g(t,200,await Ke(await I(r)));return}if(b===void 0)throw P??new f(401,"unauthorized","a directory access token is required");const u=await e.resolveVerified(b,a.scope);if(t.setHeader("Request-Id",y),T&&await L(u,T,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const s=A.match(a.method,h.pathname);if(!s)throw new f(404,"not_found","unknown operation");const _={...C===void 0?{}:{causedBy:C},method:a.method,path:h.pathname,params:s.params,query:h.searchParams,body:await I(r,s.maxBodyBytes),ceiling:u.resolved,principal:{class:"app",app:u.grantee,scopes:u.resolved,sub:u.sub},req:r,res:t};let c;try{c=await s.handler(_)}catch(E){const{status:k,body:H}=te(E);throw k>=500&&console.error("[app-listener]",`trace_id=${v}`,E),new f(k,H.error.code,H.error.message,void 0,H.error.details)}if(t.headersSent)return;if(c.rawBody!==void 0||c.status===204||c.body===void 0){t.writeHead(c.status,c.headers??{}),t.end(c.rawBody);return}t.writeHead(c.status,{"Content-Type":"application/json; charset=utf-8",...c.headers??{}}),t.end(JSON.stringify(c.body));return}if(a.stream==="bytes"){await Ye(r,t,u,h.searchParams);return}if(a.stream){await ht(r,t,T,u,ft(r,h.searchParams),y,"sse",m.stream,v);return}if(a.name==="llm"){const s=Te(await I(r,He)),_=new AbortController,c=i(()=>_.abort(),"abort");t.on("close",c);try{const E=await Ne(s,_.signal,s.stream?k=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(k)}
21
21
 
22
- `)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:y},Ae(await Y(u.grant)??await Je(u.grant)),C);s.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
22
+ `)}:void 0,void 0,{grantee:u.grantee,sub:u.sub,spend_cap:u.spend_cap,request:y},Se(await F(u.grant)??await Le(u.grant)),C);s.stream?(t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.end(`data: [DONE]
23
23
 
24
- `)):g(t,200,E.completion)}finally{t.off("close",c)}return}if(a.name==="exec"){const{signal:s,release:_}=F(t);try{g(t,200,await nt(u,await I(r,tt),s))}finally{_()}return}if(a.name==="usage.get"){g(t,200,await Ce(u.grantee,Ne(h.searchParams.get("month")),He(u.sub)));return}if(a.name==="profile.list"){g(t,200,await ze(u));return}if(We.has(a.name)){const s=await Qe(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(ot.has(a.name)){const{signal:s,release:_}=F(t);try{const c=await at(a.name,rt(u),{params:R.params,body:a.method==="POST"?await I(r):void 0,query:h.searchParams},{requestId:y,traceId:v,signal:s,...C===void 0?{}:{causedBy:C}});g(t,c.status,c.body)}catch(c){const E=it(c,y,!0);t.writeHead(E.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...E.headers}),t.end(JSON.stringify(E.body))}finally{_()}return}if(et.has(a.name)){const s=await Ze(a.name,{class:"app",app:u.grantee,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(Fe.has(a.name)){const s=await Ye(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const x=await be(a,u,T,h.searchParams,await I(r),r.headers["idempotency-key"],C);g(t,x.status,x.body)}catch(N){ct(t,N,y,v,T)}})(),"handle")}i(ht,"createAppRequestHandler");async function un(e,n,o,l={}){const d=e.listener;if(!e.issuer||!e.audience||!d?.address||!Number.isInteger(d.port)||d.port<1||d.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(d.address))throw new Error("runtime listener must bind a specific address");const w=new _e(e.issuer,e.audience,o,e.jwksUrl),A=ht(w,n,o,l),S=K((t,p)=>{A(t,p)});return{ready:new Promise((t,p)=>{S.once("error",p),S.listen(d.port,d.address,()=>{S.off("error",p),t()})}),close:i(async()=>{w.close(),Le(),S.closeAllConnections(),await new Promise((t,p)=>S.close(y=>y?p(y):t()))},"close")}}i(un,"createAppListener");export{ft as RUN_STREAM_IDLE_MS,un as createAppListener,ht as createAppRequestHandler,lt as cursor,pt as streamRunEvents};
24
+ `)):g(t,200,E.completion)}finally{t.off("close",c)}return}if(a.name==="exec"){const{signal:s,release:_}=Q(t);try{g(t,200,await rt(u,await I(r,nt),s))}finally{_()}return}if(a.name==="usage.get"){g(t,200,await Ie(u.grantee,Ce(h.searchParams.get("month")),Me(u.sub)));return}if(a.name==="profile.list"){g(t,200,await Ge(u));return}if(qe.has(a.name)){const s=await We(a.name,u,R.params.question_id,a.method==="POST"?await I(r):void 0);g(t,s.status,s.body);return}if(it.has(a.name)){const{signal:s,release:_}=Q(t);try{const c=await ot(a.name,at(u),{params:R.params,body:a.method==="POST"?await I(r):void 0,query:h.searchParams},{requestId:y,traceId:v,signal:s,...C===void 0?{}:{causedBy:C}});g(t,c.status,c.body)}catch(c){const E=st(c,y,!0);t.writeHead(E.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...E.headers}),t.end(JSON.stringify(E.body))}finally{_()}return}if(tt.has(a.name)){const s=await et(a.name,{class:"app",app:u.grantee,scopes:u.resolved},h.searchParams);g(t,s.status,s.body);return}if(Qe.has(a.name)){const s=await Fe(a,u,R.params,h.searchParams,await I(r));g(t,s.status,s.body);return}const x=await Ee(a,u,T,h.searchParams,await I(r),r.headers["idempotency-key"],C);g(t,x.status,x.body)}catch(N){mt(t,N,y,v,T)}})(),"handle")}i(wt,"createAppRequestHandler");async function dn(e,n,o,m={}){const d=e.listener;if(!e.issuer||!e.audience||!d?.address||!Number.isInteger(d.port)||d.port<1||d.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(d.address))throw new Error("runtime listener must bind a specific address");const w=new ge(e.issuer,e.audience,o,e.jwksUrl),A=wt(w,n,o,m),S=Z((t,p)=>{A(t,p)});return{ready:new Promise((t,p)=>{S.once("error",p),S.listen(d.port,d.address,()=>{S.off("error",p),t()})}),close:i(async()=>{w.close(),Ue(),S.closeAllConnections(),await new Promise((t,p)=>S.close(y=>y?p(y):t()))},"close")}}i(dn,"createAppListener");export{pt as RUN_STREAM_IDLE_MS,dn as createAppListener,wt as createAppRequestHandler,ft as cursor,ht as streamRunEvents};
@@ -1,3 +1,3 @@
1
- var k=Object.defineProperty;var s=(t,e)=>k(t,"name",{value:e,configurable:!0});import{randomUUID as y}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as x}from"../../../core/llm/body-limits.js";import{llmCallerOf as g,parseLlmRequest as O,runLlm as R}from"../../../core/llm/run.js";import{RunError as u}from"../../../core/runs/operations.js";import{errorCodes as S}from"../../../api/error-codes.js";import{getNode as T}from"../../../core/canvas/canvas.js";import{socketPrincipal as l}from"../server.js";import{activeGrant as E,activeGrantForApp as h,grantFor as I,grantsSource as w,payerOfGrant as N}from"../../../core/grants/mirror.js";import{parseUsageMonth as G,usageFor as L}from"../../../core/ledger/index.js";function b(t,e){if(e==="broker"||e==="person"||e===void 0||!t||typeof t!="object"||Array.isArray(t)||!("rate_limit"in t))return t;const{rate_limit:o,...a}=t;return a}s(b,"operatorDetails");const M="app:terminal";async function v(t,e){if(t?.class==="broker")return{grantee:t.app,sub:t.sub,node:t.node,run:e?.run_id??t.run};if(t?.class==="app"){const o=await w();if(o===null||o==="local")return{grantee:t.app};let a;try{a=await h(t.app)}catch{throw new u(401,"grant_revoked",`${t.app} has several active grants; a local token cannot name which user's cap applies`)}if(!a)throw new u(401,"grant_revoked",`${t.app} has no active grant`);return{grantee:t.app,sub:a.sub}}return{grantee:M}}s(v,"spendTarget");async function $(t){if(t?.class==="broker"){if(t.app==="app:terminal")return;const e=t.grant?await E(t.grant):await I(t.app,t.sub);if(!e&&await N(t.grant)==="app")throw new u(401,"grant_revoked",`${t.app}'s app-paid grant is no longer active`);return g(e&&e.grantee===t.app?e:null)}if(t?.class==="app"){const e=await w();return e===null||e==="local"?void 0:g(await h(t.app))}}s($,"llmCaller");function q(t){const e=S[t.code];return e?e.type:t.status===429?"rate_limit_error":t.status<500?"invalid_request_error":"server_error"}s(q,"errorType");function j(t){if(t.code!=="cap_exhausted")return{};const e=t.details??{};return{...e.limit!==void 0?{limit:e.limit}:{},...typeof e.usd=="number"?{usd:e.usd}:{},...typeof e.spend_cap=="number"?{spend_cap:e.spend_cap}:{},...typeof e.usd_equivalent=="number"?{usd_equivalent:e.usd_equivalent}:{},...typeof e.reset_at=="string"?{reset_at:e.reset_at}:{},...typeof e.user_action=="string"?{user_action:e.user_action}:{}}}s(j,"capFields");const z=[{method:"POST",pattern:"/v1/llm",scope:"crtr:llm",maxBodyBytes:x,handler:s(async({body:t,res:e,req:o,causedBy:a})=>{const i=y();e.setHeader("Request-Id",i);const p=new AbortController,_=s(()=>p.abort(),"abort");e.on("close",_);let f;try{const r=O(t),n=l(o),d=n?.class==="broker"?await T(n.node):null;if(n?.class==="broker"&&!d)throw new u(401,"unauthorized","node not found");const c={...await v(n,d??void 0),request:i},A=await R(r,p.signal,r.stream?m=>{typeof m.served_model=="string"&&(f=m.served_model),e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.write(`${JSON.stringify(m)}
2
- `)}:void 0,d?{cwd:d.cwd,profileId:d.profile_id??null}:void 0,c,await $(n),a);return r.stream?(e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.end(),{status:200}):{status:200,body:A.completion}}catch(r){if(e.headersSent){const n=r instanceof u?r:new u(503,"upstream_model_unavailable","model stream failed"),d=n.details&&typeof n.details=="object"&&!Array.isArray(n.details)?n.details:{},c=b(f!==void 0&&typeof d.served_model!="string"?{...d,served_model:f}:n.details,l(o)?.class);return e.end(`${JSON.stringify({error:{code:n.code,message:n.message,...c===void 0?{}:{details:c},type:"server_error",origin:"runtime",retryable:n.retryable,request_id:i}})}
3
- `),{status:200}}if(r instanceof u){const n=b(r.details,l(o)?.class);return r.code==="all_routes_exhausted"&&e.setHeader("Retry-After",String(r.details.retry_after_s)),{status:r.status,body:{error:{code:r.code,message:r.message,...n===void 0?{}:{details:n},type:q(r),...r.param?{param:r.param}:{},origin:"runtime",retryable:r.retryable,request_id:i,...r.code==="all_routes_exhausted"?{retry_after_s:r.details.retry_after_s}:{},...j(r)}}}}throw r}finally{e.off("close",_)}},"handler")},{method:"GET",pattern:"/v1/usage",handler:s(async({req:t})=>{const e=y(),o={"Request-Id":e};try{const a=await v(l(t));return{status:200,headers:o,body:await L(a.grantee,G(new URL(t.url??"/","http://runtime.local").searchParams.get("month")))}}catch(a){if(!(a instanceof u))throw a;return{status:a.status,headers:o,body:{error:{code:a.code,message:a.message,type:q(a),...a.param?{param:a.param}:{},origin:"runtime",retryable:!1,request_id:e}}}}},"handler")}];export{j as capFields,z as llmRoutes,v as spendTarget};
1
+ var k=Object.defineProperty;var d=(t,e)=>k(t,"name",{value:e,configurable:!0});import{randomUUID as _}from"node:crypto";import{MODEL_CONTEXT_BODY_MAX_BYTES as x}from"../../../core/llm/body-limits.js";import{llmCallerOf as g,parseLlmRequest as O,runLlm as R}from"../../../core/llm/run.js";import{RunError as u}from"../../../core/runs/operations.js";import{errorCodes as S}from"../../../api/error-codes.js";import{getNode as T}from"../../../core/canvas/canvas.js";import{socketPrincipal as l}from"../server.js";import{activeGrant as E,activeGrantForApp as h,grantFor as I,grantsSource as w,payerOfGrant as N}from"../../../core/grants/mirror.js";import{parseUsageMonth as G,usageFor as L}from"../../../core/ledger/index.js";function b(t,e){if(e==="broker"||e==="person"||e===void 0||!t||typeof t!="object"||Array.isArray(t)||!("rate_limit"in t))return t;const{rate_limit:o,...a}=t;return a}d(b,"operatorDetails");const M="app:terminal";async function v(t,e){if(t?.class==="broker")return{grantee:t.app,sub:t.sub,node:t.node,run:e?.run_id??t.run};if(t?.class==="app"){const o=await w();if(o===null||o==="local")return{grantee:t.app};let a;try{a=await h(t.app)}catch{throw new u(401,"grant_revoked",`${t.app} has several active grants; a local token cannot name which user's cap applies`)}if(!a)throw new u(401,"grant_revoked",`${t.app} has no active grant`);return{grantee:t.app,sub:a.sub}}return{grantee:M}}d(v,"spendTarget");async function $(t){if(t?.class==="broker"){if(t.app==="app:terminal")return;const e=t.grant?await E(t.grant):await I(t.app,t.sub);if(!e&&await N(t.grant)==="app")throw new u(401,"grant_revoked",`${t.app}'s app-paid grant is no longer active`);return g(e&&e.grantee===t.app?e:null)}if(t?.class==="app"){const e=await w();return e===null||e==="local"?void 0:g(await h(t.app))}}d($,"llmCaller");function A(t){const e=S[t.code];return e?e.type:t.status===429?"rate_limit_error":t.status<500?"invalid_request_error":"server_error"}d(A,"errorType");function j(t){if(t.code==="payment_refused"||t.code==="all_routes_exhausted"){const o=t.details?.payment;return o===void 0?{}:{payment:o}}if(t.code!=="cap_exhausted")return{};const e=t.details??{};return{...e.payment!==void 0?{payment:e.payment}:{},...e.limit!==void 0?{limit:e.limit}:{},...typeof e.usd=="number"?{usd:e.usd}:{},...typeof e.spend_cap=="number"?{spend_cap:e.spend_cap}:{},...typeof e.usd_equivalent=="number"?{usd_equivalent:e.usd_equivalent}:{},...typeof e.reset_at=="string"?{reset_at:e.reset_at}:{},...typeof e.user_action=="string"?{user_action:e.user_action}:{}}}d(j,"capFields");const z=[{method:"POST",pattern:"/v1/llm",scope:"crtr:llm",maxBodyBytes:x,handler:d(async({body:t,res:e,req:o,causedBy:a})=>{const i=_();e.setHeader("Request-Id",i);const p=new AbortController,y=d(()=>p.abort(),"abort");e.on("close",y);let f;try{const r=O(t),n=l(o),s=n?.class==="broker"?await T(n.node):null;if(n?.class==="broker"&&!s)throw new u(401,"unauthorized","node not found");const c={...await v(n,s??void 0),request:i},q=await R(r,p.signal,r.stream?m=>{typeof m.served_model=="string"&&(f=m.served_model),e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.write(`${JSON.stringify(m)}
2
+ `)}:void 0,s?{cwd:s.cwd,profileId:s.profile_id??null}:void 0,c,await $(n),a);return r.stream?(e.headersSent||e.writeHead(200,{"content-type":"application/x-ndjson; charset=utf-8","cache-control":"no-cache"}),e.end(),{status:200}):{status:200,body:q.completion}}catch(r){if(e.headersSent){const n=r instanceof u?r:new u(503,"upstream_model_unavailable","model stream failed"),s=n.details&&typeof n.details=="object"&&!Array.isArray(n.details)?n.details:{},c=b(f!==void 0&&typeof s.served_model!="string"?{...s,served_model:f}:n.details,l(o)?.class);return e.end(`${JSON.stringify({error:{code:n.code,message:n.message,...c===void 0?{}:{details:c},type:"server_error",origin:"runtime",retryable:n.retryable,request_id:i}})}
3
+ `),{status:200}}if(r instanceof u){const n=b(r.details,l(o)?.class),s=r.code==="all_routes_exhausted"?r.details.retry_after_s:void 0;return s!==void 0&&e.setHeader("Retry-After",String(s)),{status:r.status,body:{error:{code:r.code,message:r.message,...n===void 0?{}:{details:n},type:A(r),...r.param?{param:r.param}:{},origin:"runtime",retryable:r.retryable,request_id:i,...s!==void 0?{retry_after_s:s}:{},...j(r)}}}}throw r}finally{e.off("close",y)}},"handler")},{method:"GET",pattern:"/v1/usage",handler:d(async({req:t})=>{const e=_(),o={"Request-Id":e};try{const a=await v(l(t));return{status:200,headers:o,body:await L(a.grantee,G(new URL(t.url??"/","http://runtime.local").searchParams.get("month")))}}catch(a){if(!(a instanceof u))throw a;return{status:a.status,headers:o,body:{error:{code:a.code,message:a.message,type:A(a),...a.param?{param:a.param}:{},origin:"runtime",retryable:!1,request_id:e}}}}},"handler")}];export{j as capFields,z as llmRoutes,v as spendTarget};
@@ -1 +1 @@
1
- var O=Object.defineProperty;var o=(n,e)=>O(n,"name",{value:e,configurable:!0});import{deleteAuthCredential as y,readAuthCredentials as S,setAuthCredential as b,storedApiKey as E}from"../../../core/auth-file.js";import{ApiError as i}from"../../../api/index.js";import{RunError as g}from"../../../core/runs/operations.js";import{usage as u}from"../../../core/errors.js";import{modelAuthReadiness as D}from"../../../core/model-auth/readiness.js";import{MANAGED_PROVIDER_IDS as v,OPENAI_CHATGPT_PROVIDER_ID as I,DuplicateSubscriptionError as P,commitManagedLogin as $,isManagedProvider as l,promoteSubscription as T,readSubscriptionPool as m,removeAllManagedAccounts as j,removeManagedAccount as F,renameSubscription as M}from"../../../core/subscription-state.js";import{cancelModelAuthFlow as C,completeModelAuthFlow as R,startModelAuthFlow as L,waitModelAuthFlow as G}from"../../../core/model-auth/flows.js";import{waitSeconds as N}from"../long-poll-wait.js";function k(n,e){if(typeof e!="string"||e==="")throw new i(400,"invalid_request",`oauth credential requires \`${n}\``);const t=Date.parse(e);if(Number.isNaN(t))throw new i(400,"invalid_request",`\`${n}\` is not a valid ISO timestamp`);return t}o(k,"parseExpiry");function c(n,e,t){if(typeof t!="string"||t==="")throw new i(400,"invalid_request",`${n} credential requires \`${e}\``);return t}o(c,"requireField");function K(n,e=Date.now()){const t=Object.entries(n.modelCooldowns??{}).filter(([,a])=>a>e).map(([a,r])=>({family:a,rate_limited_until:new Date(r).toISOString()}));return{label:n.label,expires_at:new Date(n.expires).toISOString(),rate_limited_until:new Date(n.rateLimitedUntil).toISOString(),...t.length?{model_cooldowns:t}:{},...n.authFailure?{auth_failure:n.authFailure}:{},...n.accountId?{account_id:n.accountId}:{}}}o(K,"toManagedAccountStatus");async function p(n){const e=(await m(n)).map(t=>K(t));return{provider:n,managed:!0,configured:e.length>0,accounts:e}}o(p,"managedStatus");function f(n,e){const t=n.query.getAll(e);if(t.length>1)throw u(`${e} must appear at most once`);return t[0]}o(f,"singleQueryValue");async function U(){const n=await S(),e=new Set;for(const r of v)r===I&&n[r]!==void 0&&(await m(r)).length===0&&e.add(r);const t=o(r=>e.has(r),"legacyApiKey"),a=await Promise.all(v.filter(r=>!t(r)).map(p));for(const[r,d]of Object.entries(n))l(r)&&!t(r)&&(d.type!=="api_key"||await E(r)===void 0)||d.type!=="api_key"&&d.type!=="oauth"||a.push({provider:r,managed:!1,configured:!0,kind:d.type});return{status:200,body:{providers:a}}}o(U,"handleList");async function V(n){for(const[s]of n.query)if(s!=="profile"&&s!=="cwd"&&s!=="kind"&&s!=="model")throw u(`unknown model-auth readiness query parameter: ${s}`);const e=f(n,"profile"),t=f(n,"cwd"),a=f(n,"kind"),r=f(n,"model");if(a!==void 0&&a.trim()==="")throw u("kind must be a non-empty string when provided");if(r!==void 0&&r.trim()==="")throw u("model must be a non-empty string when provided");return{status:200,body:await D({...e!==void 0?{profile:e}:{},...t!==void 0?{cwd:t}:{},...a!==void 0?{kind:a}:{},...r!==void 0?{model:r}:{}})}}o(V,"handleReadiness");async function H(n){const e=n.params.provider,t=n.body;if(t===void 0||typeof t!="object"||typeof t.kind!="string")throw new i(400,"invalid_request","a credential `kind` is required");switch(t.kind){case"api_key":{const a=c("api_key","api_key",t.api_key);return await b(e,{type:"api_key",key:a}),{status:200,body:{provider:e,installed:!0,managed:!1}}}case"oauth":{if(l(e))throw new i(422,"unprocessable",`provider ${e} stores oauth credentials as managed accounts \u2014 use kind \`managed_account\``);const a=c("oauth","access_token",t.access_token),r=c("oauth","refresh_token",t.refresh_token),d=k("expires_at",t.expires_at),s=t.extra??{};await b(e,{type:"oauth",...s,access:a,refresh:r,expires:d});const w={provider:e,installed:!0,managed:!1};return typeof t.account_id=="string"&&t.account_id!==""&&(w.account_id=t.account_id),{status:200,body:w}}case"managed_account":{if(!l(e))throw new i(422,"unprocessable",`provider ${e} does not support managed accounts`);const a=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0;if(!a&&t.auto_label!==!0)throw new i(400,"invalid_request","managed_account credential requires `label` or `auto_label`");const r=typeof t.account_id=="string"&&t.account_id!==""?t.account_id:void 0,d=c("managed_account","access_token",t.access_token),s=c("managed_account","refresh_token",t.refresh_token),w=k("expires_at",t.expires_at),A=typeof t.last_rate_limited_at=="number"?t.last_rate_limited_at:Math.max(0,...(await m(e)).map(q=>q.lastRateLimitedAt));await $(e,a,{refresh:s,access:d,expires:w,...r?{accountId:r}:{},lastRateLimitedAt:A,autoLabel:t.auto_label===!0});const _={provider:e,installed:!0,managed:!0};return r&&(_.account_id=r),{status:200,body:_}}default:throw new i(400,"invalid_request",`unknown credential kind: ${String(t.kind)}`)}}o(H,"handleInstall");async function x(n){const e=n.params.provider;if(l(e)){const a=await j(e),r=await y(e);return{status:200,body:{provider:e,removed_accounts:a+(r?1:0)}}}const t=await y(e)?1:0;return{status:200,body:{provider:e,removed_accounts:t}}}o(x,"handleDelete");async function J(n){const e=n.params.provider;if(!l(e))throw new i(400,"invalid_request",`${e} has no managed accounts`);const t=h(n);for(const r of Object.keys(t))if(r!=="label"&&r!=="preferred")throw new i(400,"invalid_request",`unknown account field: ${r}`);if(t.label!==void 0&&typeof t.label!="string")throw new i(400,"invalid_request","`label` must be a string");if(t.preferred!==void 0&&t.preferred!==!0)throw new i(400,"invalid_request","`preferred` can only be true");if(t.label===void 0&&t.preferred===void 0)throw new i(400,"invalid_request","send `label` and/or `preferred`");let a=n.params.label;try{t.label!==void 0&&(await M(e,a,t.label),a=t.label.trim()),t.preferred&&await T(e,a)}catch(r){throw r instanceof Error&&/^Unknown .* subscription:/.test(r.message)?new i(404,"not_found",r.message):r instanceof P?new i(409,"conflict",r.message):r}return{status:200,body:await p(e)}}o(J,"handlePatchAccount");async function Q(n){const e=n.params.provider;if(!l(e))throw new i(400,"invalid_request",`${e} has no managed accounts`);try{await F(e,n.params.label)}catch(t){throw t instanceof Error&&/^Unknown .* subscription:/.test(t.message)?new i(404,"not_found",t.message):t}return{status:200,body:await p(e)}}o(Q,"handleDeleteAccount");function h(n){const e=n.body;if(e===void 0)return{};if(typeof e!="object"||e===null||Array.isArray(e))throw new i(400,"invalid_request","request body must be a JSON object");return e}o(h,"bodyObject");async function z(n){const e=h(n);return{status:200,body:await L({provider:e.provider,...e.redirect!==void 0?{redirect:e.redirect}:{},...e.label!==void 0?{label:e.label}:{}})}}o(z,"handleFlowStart");async function B(n){const e=h(n);return{status:200,body:await R(n.params.flow_id,e.input)}}o(B,"handleFlowComplete");async function W(n){const e=await C(n.params.flow_id);if(!e)throw new g(400,"invalid_request","no sign-in has this flow_id","flow_id");const{jti:t,...a}=e;return{status:200,body:a}}o(W,"handleFlowCancel");async function X(n){for(const[s]of n.query)if(s!=="wait")throw u(`unknown model-auth flow query parameter: ${s}`);f(n,"wait");const e=N("model_auth.get",n.query),t=new AbortController;n.res.once("close",()=>t.abort());const a=await G(n.params.flow_id,e*1e3,t.signal);if(!a)throw new g(404,"not_found","no sign-in has this flow_id","flow_id");const{jti:r,...d}=a;return{status:200,body:d}}o(X,"handleFlowGet");const se=[{method:"POST",pattern:"/v1/model-auth/flows",ownerOnly:!0,handler:z},{method:"POST",pattern:"/v1/model-auth/flows/:flow_id/complete",ownerOnly:!0,handler:B},{method:"POST",pattern:"/v1/model-auth/flows/:flow_id/cancel",ownerOnly:!0,handler:W},{method:"GET",pattern:"/v1/model-auth/flows/:flow_id",ownerOnly:!0,handler:X},{method:"GET",pattern:"/v1/model-auth",handler:U},{method:"GET",pattern:"/v1/model-auth/readiness",handler:V},{method:"PUT",pattern:"/v1/model-auth/:provider",ownerOnly:!0,handler:H},{method:"DELETE",pattern:"/v1/model-auth/:provider",ownerOnly:!0,handler:x},{method:"DELETE",pattern:"/v1/model-auth/:provider/accounts/:label",ownerOnly:!0,handler:Q},{method:"PATCH",pattern:"/v1/model-auth/:provider/accounts/:label",ownerOnly:!0,handler:J}];export{p as managedStatus,se as modelAuthRoutes};
1
+ var E=Object.defineProperty;var i=(n,e)=>E(n,"name",{value:e,configurable:!0});import{deleteAuthCredential as b,readAuthCredentials as I,setAuthCredential as v,storedApiKey as D}from"../../../core/auth-file.js";import{ApiError as o}from"../../../api/index.js";import{RunError as g}from"../../../core/runs/operations.js";import{usage as u}from"../../../core/errors.js";import{modelAuthReadiness as R}from"../../../core/model-auth/readiness.js";import{recordActivation as k}from"../../../core/model-auth/activations.js";import{withCanvasWrite as P}from"../../../core/canvas/db.js";import{KeyRouteError as $,listKeyRoutes as T,removeKeyRoute as j,saveKeyRoute as C}from"../../../core/model-auth/key-routes.js";import{MANAGED_PROVIDER_IDS as A,OPENAI_CHATGPT_PROVIDER_ID as F,DuplicateSubscriptionError as M,commitManagedLogin as K,isManagedProvider as l,promoteSubscription as L,readSubscriptionPool as p,removeAllManagedAccounts as G,removeManagedAccount as N,renameSubscription as U}from"../../../core/subscription-state.js";import{cancelModelAuthFlow as V,completeModelAuthFlow as H,startModelAuthFlow as x,waitModelAuthFlow as J}from"../../../core/model-auth/flows.js";import{waitSeconds as Q}from"../long-poll-wait.js";function q(n,e){if(typeof e!="string"||e==="")throw new o(400,"invalid_request",`oauth credential requires \`${n}\``);const t=Date.parse(e);if(Number.isNaN(t))throw new o(400,"invalid_request",`\`${n}\` is not a valid ISO timestamp`);return t}i(q,"parseExpiry");function c(n,e,t){if(typeof t!="string"||t==="")throw new o(400,"invalid_request",`${n} credential requires \`${e}\``);return t}i(c,"requireField");function W(n,e=Date.now()){const t=Object.entries(n.modelCooldowns??{}).filter(([,r])=>r>e).map(([r,a])=>({family:r,rate_limited_until:new Date(a).toISOString()}));return{label:n.label,expires_at:new Date(n.expires).toISOString(),rate_limited_until:new Date(n.rateLimitedUntil).toISOString(),...t.length?{model_cooldowns:t}:{},...n.authFailure?{auth_failure:n.authFailure}:{},...n.accountId?{account_id:n.accountId}:{}}}i(W,"toManagedAccountStatus");async function h(n){const e=(await p(n)).map(t=>W(t));return{provider:n,managed:!0,configured:e.length>0,accounts:e}}i(h,"managedStatus");function f(n,e){const t=n.query.getAll(e);if(t.length>1)throw u(`${e} must appear at most once`);return t[0]}i(f,"singleQueryValue");async function z(){const n=await I(),e=new Set;for(const a of A)a===F&&n[a]!==void 0&&(await p(a)).length===0&&e.add(a);const t=i(a=>e.has(a),"legacyApiKey"),r=await Promise.all(A.filter(a=>!t(a)).map(h));for(const[a,d]of Object.entries(n))l(a)&&!t(a)&&(d.type!=="api_key"||await D(a)===void 0)||d.type!=="api_key"&&d.type!=="oauth"||r.push({provider:a,managed:!1,configured:!0,kind:d.type});return{status:200,body:{providers:r,keys:await T()}}}i(z,"handleList");async function B(n){for(const[s]of n.query)if(s!=="profile"&&s!=="cwd"&&s!=="kind"&&s!=="model")throw u(`unknown model-auth readiness query parameter: ${s}`);const e=f(n,"profile"),t=f(n,"cwd"),r=f(n,"kind"),a=f(n,"model");if(r!==void 0&&r.trim()==="")throw u("kind must be a non-empty string when provided");if(a!==void 0&&a.trim()==="")throw u("model must be a non-empty string when provided");return{status:200,body:await R({...e!==void 0?{profile:e}:{},...t!==void 0?{cwd:t}:{},...r!==void 0?{kind:r}:{},...a!==void 0?{model:a}:{}})}}i(B,"handleReadiness");async function X(n){const e=n.params.provider,t=n.body;if(t===void 0||typeof t!="object"||typeof t.kind!="string")throw new o(400,"invalid_request","a credential `kind` is required");switch(t.kind){case"api_key":{const r=c("api_key","api_key",t.api_key);if(t.models!==void 0){let d;try{d=await C(e,r,t.models)}catch(s){throw s instanceof $?new o(400,"invalid_request",s.message):s}return{status:200,body:{provider:e,installed:!0,managed:!1,...d.activationId!==null?{activation_id:d.activationId}:{}}}}const a=await P(async()=>(await v(e,{type:"api_key",key:r}),k({kind:"api_key",provider:e})));return{status:200,body:{provider:e,installed:!0,managed:!1,...a!==null?{activation_id:a}:{}}}}case"oauth":{if(l(e))throw new o(422,"unprocessable",`provider ${e} stores oauth credentials as managed accounts \u2014 use kind \`managed_account\``);const r=c("oauth","access_token",t.access_token),a=c("oauth","refresh_token",t.refresh_token),d=q("expires_at",t.expires_at),s=t.extra??{};await v(e,{type:"oauth",...s,access:r,refresh:a,expires:d});const m={provider:e,installed:!0,managed:!1};return typeof t.account_id=="string"&&t.account_id!==""&&(m.account_id=t.account_id),{status:200,body:m}}case"managed_account":{if(!l(e))throw new o(422,"unprocessable",`provider ${e} does not support managed accounts`);const r=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0;if(!r&&t.auto_label!==!0)throw new o(400,"invalid_request","managed_account credential requires `label` or `auto_label`");const a=typeof t.account_id=="string"&&t.account_id!==""?t.account_id:void 0,d=c("managed_account","access_token",t.access_token),s=c("managed_account","refresh_token",t.refresh_token),m=q("expires_at",t.expires_at),O=typeof t.last_rate_limited_at=="number"?t.last_rate_limited_at:Math.max(0,...(await p(e)).map(S=>S.lastRateLimitedAt));await K(e,r,{refresh:s,access:d,expires:m,...a?{accountId:a}:{},lastRateLimitedAt:O,autoLabel:t.auto_label===!0});const _=await k({kind:"subscription",provider:e}),w={provider:e,installed:!0,managed:!0};return a&&(w.account_id=a),_!==null&&(w.activation_id=_),{status:200,body:w}}default:throw new o(400,"invalid_request",`unknown credential kind: ${String(t.kind)}`)}}i(X,"handleInstall");async function Y(n){const e=n.params.provider;if(await j(e),l(e)){const r=await G(e),a=await b(e);return{status:200,body:{provider:e,removed_accounts:r+(a?1:0)}}}const t=await b(e)?1:0;return{status:200,body:{provider:e,removed_accounts:t}}}i(Y,"handleDelete");async function Z(n){const e=n.params.provider;if(!l(e))throw new o(400,"invalid_request",`${e} has no managed accounts`);const t=y(n);for(const a of Object.keys(t))if(a!=="label"&&a!=="preferred")throw new o(400,"invalid_request",`unknown account field: ${a}`);if(t.label!==void 0&&typeof t.label!="string")throw new o(400,"invalid_request","`label` must be a string");if(t.preferred!==void 0&&t.preferred!==!0)throw new o(400,"invalid_request","`preferred` can only be true");if(t.label===void 0&&t.preferred===void 0)throw new o(400,"invalid_request","send `label` and/or `preferred`");let r=n.params.label;try{t.label!==void 0&&(await U(e,r,t.label),r=t.label.trim()),t.preferred&&await L(e,r)}catch(a){throw a instanceof Error&&/^Unknown .* subscription:/.test(a.message)?new o(404,"not_found",a.message):a instanceof M?new o(409,"conflict",a.message):a}return{status:200,body:await h(e)}}i(Z,"handlePatchAccount");async function ee(n){const e=n.params.provider;if(!l(e))throw new o(400,"invalid_request",`${e} has no managed accounts`);try{await N(e,n.params.label)}catch(t){throw t instanceof Error&&/^Unknown .* subscription:/.test(t.message)?new o(404,"not_found",t.message):t}return{status:200,body:await h(e)}}i(ee,"handleDeleteAccount");function y(n){const e=n.body;if(e===void 0)return{};if(typeof e!="object"||e===null||Array.isArray(e))throw new o(400,"invalid_request","request body must be a JSON object");return e}i(y,"bodyObject");async function te(n){const e=y(n);return{status:200,body:await x({provider:e.provider,...e.redirect!==void 0?{redirect:e.redirect}:{},...e.label!==void 0?{label:e.label}:{}})}}i(te,"handleFlowStart");async function ne(n){const e=y(n);return{status:200,body:await H(n.params.flow_id,e.input)}}i(ne,"handleFlowComplete");async function ae(n){const e=await V(n.params.flow_id);if(!e)throw new g(400,"invalid_request","no sign-in has this flow_id","flow_id");const{jti:t,...r}=e;return{status:200,body:r}}i(ae,"handleFlowCancel");async function re(n){for(const[s]of n.query)if(s!=="wait")throw u(`unknown model-auth flow query parameter: ${s}`);f(n,"wait");const e=Q("model_auth.get",n.query),t=new AbortController;n.res.once("close",()=>t.abort());const r=await J(n.params.flow_id,e*1e3,t.signal);if(!r)throw new g(404,"not_found","no sign-in has this flow_id","flow_id");const{jti:a,...d}=r;return{status:200,body:d}}i(re,"handleFlowGet");const ye=[{method:"POST",pattern:"/v1/model-auth/flows",ownerOnly:!0,handler:te},{method:"POST",pattern:"/v1/model-auth/flows/:flow_id/complete",ownerOnly:!0,handler:ne},{method:"POST",pattern:"/v1/model-auth/flows/:flow_id/cancel",ownerOnly:!0,handler:ae},{method:"GET",pattern:"/v1/model-auth/flows/:flow_id",ownerOnly:!0,handler:re},{method:"GET",pattern:"/v1/model-auth",handler:z},{method:"GET",pattern:"/v1/model-auth/readiness",handler:B},{method:"PUT",pattern:"/v1/model-auth/:provider",ownerOnly:!0,handler:X},{method:"DELETE",pattern:"/v1/model-auth/:provider",ownerOnly:!0,handler:Y},{method:"DELETE",pattern:"/v1/model-auth/:provider/accounts/:label",ownerOnly:!0,handler:ee},{method:"PATCH",pattern:"/v1/model-auth/:provider/accounts/:label",ownerOnly:!0,handler:Z}];export{h as managedStatus,ye as modelAuthRoutes};
@@ -1 +1 @@
1
- var $e=Object.defineProperty;var s=(e,n)=>$e(e,"name",{value:n,configurable:!0});import{envProfileId as Ne}from"../../../shared/env.js";import{pausedCanvasProfiles as Ce}from"../../../core/profiles/manifest.js";import{existsSync as C,realpathSync as ee,statSync as ne}from"node:fs";import{isAbsolute as K,resolve as D}from"node:path";import{appendSituationalContext as Ee,formatSituationalProse as Te}from"../../../core/runtime/situational-context.js";import{closeNode as Pe}from"../../../core/runtime/close.js";import{reviveNode as De}from"../../../core/runtime/revive.js";import{nowIso as x}from"../../../core/fs-utils.js";import{appPaidLaunch as Le,assertLaunchModelRegistered as V,forkNode as je,resolveForkSource as te,spawnChildPrepared as Me}from"../../../core/runtime/spawn.js";import{forkSourceNode as ie,newNodeId as re}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as oe,childrenOf as Ge,completeCreateRequest as ae,findCreateRequest as de,getNode as R,recordCreateRequestNode as Fe,reserveCreateRequest as se,reserveCreateRequestNode as Be,listNodes as Ke,recordRespawnAttempt as xe,subscribersOf as Ve,subscriptionsOf as le,updateNode as E}from"../../../core/canvas/canvas.js";import{armControllerWait as We}from"../../../core/canvas/waits.js";import{withCanvasWrite as W}from"../../../core/canvas/db.js";import{markNodeRead as ze}from"../../../core/canvas/recovery.js";import{nodeObject as Je}from"../../../core/graph/objects.js";import{recordActedOn as Ue}from"../../../core/graph/edges.js";import{publish as Ye}from"../../../core/graph/events.js";import{readerFor as He}from"../reader.js";import{relocateSessionCwd as Qe,unbindSession as Xe}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as Ze}from"../../../core/canvas/attention.js";import{isSafeNodeId as qe}from"../../../core/canvas/paths.js";import{contextDir as ce,nodeAgentDir as z}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as en,cronRefusalError as nn}from"../../cron/authority.js";import{cronBirthPlacement as tn}from"../../cron/armed-context.js";import{existsBeneath as rn,isAbsentOrRefused as on,isBeneathRefusal as an,readdirBeneath as dn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as sn,readNodeSession as ln,readNodeSnapshot as cn,transcriptMarkdown as un}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as fn}from"../../../core/substrate/subject.js";import{reviveAll as pn}from"../../../core/runtime/revive-all.js";import{promoteAsync as mn,requestYieldAsync as wn,reshapeNodeAsync as J}from"../../../core/runtime/promote.js";import{recycleNode as hn}from"../../../core/runtime/recycle.js";import{relaunchRoot as yn}from"../../../core/runtime/reset.js";import{assertReopenGate as _n}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as gn}from"./broker-recovery.js";import{readOutputRequest as bn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as vn,readGoal as kn,captureGoalIfAbsent as Sn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as Rn,hasRoadmap as In}from"../../../core/runtime/roadmap.js";import{renameWindow as On}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as An,explicitModelIntent as $n,normalizeModel as Nn,readMergedLaunchConfigAsync as ue}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Cn}from"../../../core/model-routes.js";import{persistDormantModel as En,setModelLive as Tn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as fe}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Pn}from"../../../core/runtime/broker-request.js";import{boundFleet as L}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Dn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Ln}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as pe}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as jn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Mn}from"../../../core/human-actions.js";import{parseDurationMs as Gn}from"../../../core/wake.js";import{claimWarmNode as Fn,refillWarmPool as me,resumeWarmClaim as Bn,warmPoolEnabled as Kn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as U,isLaunchKind as xn,resolveLaunchTarget as Vn}from"../../../core/runtime/launch-target.js";import{fullName as Wn}from"../../../core/canvas/labels.js";import{reportsForNode as we}from"./reports.js";import{requireUsableProfile as zn}from"./profiles.js";import{assertProfileActive as Jn,loadExactProfileManifest as Un}from"../../../core/profiles/manifest.js";import{getCron as he}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Yn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Hn}from"../../control.js";import{notFound as T,usage as w}from"../../../core/errors.js";import{assertScope as Qn,validateScopes as ye}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Xn,toNodeDetailDTO as Y,toNodeSummaryDTO as Zn,toReviveResultDTO as qn}from"../map.js";import{ApiError as p}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{runsOnBlaxel as et}from"../environment-of.js";import{actsAsPerson as j,canReadNode as $,mayOnNode as nt,readableNodeIds as tt,resolvedScopes as it}from"../router.js";import{forwardVerb as rt,queryWithoutMachine as ot,relayError as at,unknownError as dt,withMachine as st}from"../../peer/forward.js";import{fileRoot as lt}from"../../../core/spaces/file-root.js";import{activeGrant as ct,payerOfGrant as ut}from"../../../core/grants/mirror.js";import{nodeTerminalGrant as ft}from"../../../core/grants/terminal.js";import{appRungForGrant as pt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as mt}from"../../../core/model-routes.js";import{listProfileEnvNames as wt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as ht,NO_PROVIDER_CREDENTIAL_MESSAGE as _e}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as yt,mapAsync as ge}from"../../../core/async-array.js";async function m(e){const n=await R(e);if(n===null)throw T(`unknown node: ${e}`,{received:e});return n}s(m,"requireMeta");async function H(e){return{subscribesTo:await le(e),subscribers:await Ve(e),children:await Ge(e)}}s(H,"edgesFor");async function b(e){const n=await m(e);return await Y(n,await H(e))}s(b,"detailOf");async function _t(e){let n=(await we(e)).length;try{n+=dn(await z(e),await ce(e)).length}catch(t){if(!on(t))throw t}return n}s(_t,"countFiles");function gt(e){if(typeof e!="object"||e===null)throw w("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw w("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw w("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw w("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&ye(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new p(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw w("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw w("request_key must be a non-empty string of at most 128 characters when provided");return n}s(gt,"parseCreateBody");function bt(e){if(e===void 0)return;const n=Gn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new p(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}s(bt,"parseDeadline");function vt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new p(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!jn.test(e.action))throw new p(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new p(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>pe)throw new p(413,"payload_too_large",`serialized payload exceeds ${pe} bytes`)}return e}}s(vt,"parseOutcomeDelivery");function kt(e,n){const t=Mn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new p(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new p(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}s(kt,"resolveOutcomeDelivery");function St(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=D(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}s(St,"buildRecipe");function Rt(e,n,t){return!Kn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}s(Rt,"warmRequestFor");import{resolveCreateKind as Nr}from"../../../core/runtime/launch-target.js";function be(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Cn(e.model,n,e.modelExact===!0)}s(be,"requestFromLaunch");function It(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!O(n,r));if(t.length===0)return e;throw new p(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}s(It,"withinCeiling");async function ve(e,n,t){const r=(await An(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await V(be(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}s(ve,"assertNodeModelChangeRegistered");async function ke(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron")return;const r=lt({app:t.app,resolved:await it(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new p(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}s(ke,"assertCallerReaches");const Q=new Map;async function Ot(e,n={},t={}){const r=It(gt(e.body),e.ceiling);if(e.principal.class==="broker"){const d=e.principal;if(r.prefer_warm===!0&&d.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await m(r.parent);if(o.grantee!==d.app)throw new p(403,"other_app_run","cannot create a child under another app's node");if(!await $(d,o.grantee??"app:terminal",r.parent))throw T(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==d.node)throw new p(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await ie(await te(r.fork_from))}catch{}if(o?.grantee!==d.app||!await $(d,o.grantee,o.node_id))throw new p(403,"other_app_run","cannot fork another app's conversation")}r.creator=d.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const d=r.fork_from===void 0?null:await ie(await te(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,d?.node_id])if(o!=null&&await R(o)!==null&&!await nt(e.principal,"edit",o))throw T(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const d=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new p(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await re(),d.isolated&&(r.isolated=!0,r.cwd=await z(r.node_id,d.app));const o=await en({grantee:d.app,sub:d.sub,grant_id:d.grant,scopes:d.scopes,from_exec:d.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw nn(o);if(r.scopes!==void 0){const l=r.scopes.find(f=>!O(o.effectiveScopes,f)||!O(d.scopes,f));if(l!==void 0)throw new p(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else d.scopes!==null&&(r.scopes=[...d.scopes])}r.creator!==void 0&&Qn(await m(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&qe(r.node_id)&&await R(r.node_id)!==null&&(await de(i))?.nodeId!==r.node_id)return M(e,r,n,t);const a=Q.get(i);if(a!==void 0)return a;const u=$t(e,r,i,n,t);Q.set(i,u);try{return await u}finally{Q.delete(i)}}s(Ot,"handleCreate");const Se="create_request_in_progress";async function At(e,n,t){const r=Date.now()+1e4;for(;t!==null;){const i=await R(t);if(i!==null){if(!j(e.principal)&&!await $(e.principal,i.grantee??"app:terminal",t))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(t)}}if(Date.now()>=r||(await de(n))?.nodeId!==t)break;await new Promise(a=>setTimeout(a,100))}throw new p(409,Se,"another create with this request_key is in progress; retry it")}s(At,"awaitForeignCreate");async function $t(e,n,t,r,i){const a=await se(t);if(a.nodeId!==null&&await R(a.nodeId)!==null){if(a.state!=="warm_claimed"){const u=await R(a.nodeId);if(!j(e.principal)&&!await $(e.principal,u.grantee??"app:terminal",a.nodeId))throw new p(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(a.nodeId)}}return M(e,n,r,i,a)}try{return await M(e,n,r,i,a)}catch(u){if(u instanceof p&&u.code===Se)throw u;const d=await se(t);throw(d.nodeId===null||await R(d.nodeId)===null)&&await oe(t,d.nodeId),u}}s($t,"handleKeyedCreateRequest");async function M(e,n,t,r,i=void 0){const a=r.deadlineAt??bt(n.deadline),u=vt(n.outcome_delivery),d=e.principal.class==="cron"?await tn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await he(e.principal.cron))?.created_by??null},n.node_id):null;d!==null&&(n.root=d.root===!0);const o=d?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw w("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw w("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw w("output_schema must be a JSON schema object");await Ln(l)}const{profileId:f,kind:h,cwd:c,launch:S}=await Vn(n,{validateKind:Ae,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}});if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!C(c)&&!await et(f))throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${c}`,received:c,field:"cwd",next:"Pass an existing directory with --cwd."});await ke(e,c),n.worktree!==void 0&&await ke(e,D(n.pin_cwd??n.cwd??c));const _={...n,kind:h},v=u===void 0?void 0:kt(u,c),Z=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await R(o))?.grant_id??null);if(await V(be(await Le(S,Z,n.model)),{cwd:c,profileId:f},t.modelRegistry),await ut(Z)!=="app"&&!await ht(f===null?[]:await wt(f)))throw new p(412,"no_provider_credential",_e,{error:"no_provider_credential",message:_e,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let F=null;{const A=i===void 0||i.nodeId===null||i.state==="warm_claimed"?Rt(_,c,f):null,B=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Dn(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=A===null?null:await Bn(A,i.nodeId,B);if(g===null)throw await oe(i.requestKey,i.nodeId),new p(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await ae(i.requestKey,g),{status:201,body:await b(g)}}if(A!==null){const g=await Fn(A,{...a===void 0?{}:{deadlineAt:a},...v===void 0?{}:{outcomeDelivery:v},...i===void 0?{}:{requestKey:i.requestKey}},B);if(g!==null)return i!==void 0&&await ae(i.requestKey,g),me(A),{status:201,body:await b(g)};F=A}const P=i?.nodeId??n.node_id??(i===void 0?void 0:await re());if(i!==void 0&&i.nodeId===null){const g=await Be(i.requestKey,P);if(g!==P)return await At(e,i.requestKey,g)}const I=St(P===void 0?_:{..._,node_id:P},o,c);d!==null&&(d.rootLifecycle!==void 0&&(I.rootLifecycle=d.rootLifecycle),d.scopes!==void 0&&_.scopes===void 0&&(I.scopes=d.scopes),d.run!==void 0&&(I.run=d.run),d.withinCreate!==void 0&&(I.withinCreate=d.withinCreate)),a!==void 0&&(I.deadlineAt=a),v!==void 0&&(I.outcomeDelivery=v),I.readiness=n.root===!0?"await":"launch";const q=await Me(I,B,()=>{F!==null&&me(F)});return i!==void 0&&await Fe(i.requestKey,q.node.node_id),{status:201,body:await b(q.node.node_id)}}}s(M,"handleCreateRequest");function k(e,n){const t=e.query.getAll(n);if(t.length>1)throw w(`${n} must appear at most once`);return t[0]}s(k,"singleQueryValue");function X(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw w(`${n} must be true or false`)}}s(X,"optionalBoolean");function G(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw w(`${n} must be one of: ${t.join(", ")}`)}}s(G,"oneOf");function Nt(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[_]of e.query)if(!n.has(_))throw w(`unknown nodes query parameter: ${_}`);const t=G(k(e,"status"),"status",["active","idle","done","dead","canceled"]),r=G(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=k(e,"kind"),a=G(k(e,"mode"),"mode",["base","orchestrator"]),u=k(e,"profile_id"),d=k(e,"profile_prefix"),o=k(e,"parent"),l=X(k(e,"top_level"),"top_level"),f=k(e,"under"),h=X(k(e,"under_inclusive"),"under_inclusive"),c=X(k(e,"hanging"),"hanging"),S=G(k(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw w("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...u!==void 0?{profile_id:u}:{},...d!==void 0?{profile_prefix:d}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...f!==void 0?{under:f}:{},...h!==void 0?{under_inclusive:h}:{},...c!==void 0?{hanging:c}:{},...S!==void 0?{include:S}:{}}}s(Nt,"parseListQuery");async function Ct(e){const n=Nt(e);let t=await Ke({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await tt(e.principal);r!==null&&(t=t.filter(d=>r.has(d.node_id)));const i=n.include==="activity"?await Ze(t.map(d=>d.node_id)):null,a=t.length>0?Ce():new Set;return{status:200,body:await ge(t,async d=>{const o=await Zn(d,d.profile_id!==null&&a.has(d.profile_id));if(i!==null){const l=await we(d.node_id);o.activity={latest_report:l[0]??null,final_report:d.final_report===null?null:l.find(f=>f.name===d.final_report)??null,pending_human_count:i[d.node_id]??0}}return o})}}s(Ct,"handleList");async function Et(e){const n=e.params.id,t=await rt(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:ot(e)});if(t.kind==="unknown")throw dt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw at(t.status,t.body);return{status:t.status,body:st(t.body,t.machine)}}return await m(n),{status:200,body:await b(n)}}s(Et,"handleDetail");async function Tt(e){const n=e.params.id;await m(n);const t=await cn(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:x()}}}s(Tt,"handleSnapshot");async function Pt(e){const n=e.params.id,t=await fn(n);if(t===null)throw T(`unknown node: ${n}`,{received:n});return{status:200,body:t}}s(Pt,"handleSubject");function Dt(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw w(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw w("cursor must appear at most once");if(t.length>1)throw w("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw w("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}s(Dt,"parseMessagesQuery");async function Lt(e){const n=e.params.id,t=await sn(n,Dt(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:x()}}}s(Lt,"handleMessages");async function jt(e){const n=e.params.id;await m(n);const t=await ln(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:x()}}}s(jt,"handleSession");async function Mt(e){const n=e.params.id;return await m(n),{status:200,body:{node_id:n,markdown:await un(n)}}}s(Mt,"handleTranscript");async function Gt(e){const n=e.params.id;await m(n);const t=s(async(i,a)=>({node_id:i,label:(await R(i))?.name??i,dir:await ce(i),self:a,files:await _t(i)}),"root"),r=await yt([await t(n,!0),...await ge(await le(n),async i=>await t(i.node_id,!1))],async i=>await Ft(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}s(Gt,"handleContext");async function Ft(e,n){try{return rn(await z(e),n)}catch(t){if(an(t))return!1;throw t}}s(Ft,"hasDir");async function Bt(e){const n=await m(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>O(t,a)),...t.filter(a=>O(n.scopes,a))])],i=await je(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await b(i.node.node_id)}}s(Bt,"handleFork");const Kt=1e4;async function xt(e){const n=e.params.id;await m(n);const t=e.body,r=t?.resume??!0,i=t?.reopen??!1;await _n(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!r&&t?.cron_id!==void 0?await he(t.cron_id):null,u=await De(n,{resume:r,capacity:"refuse",...a!==null?{wakeReason:await Yn(a,"schedule_revive")}:{}});u.outcome!=="already-live"&&await xe(n,{failures:0,notBefore:null});const d=(await R(n))?.status??"active",o=(u.launch??L().get(n)?.handle)?.exited,l=u.outcome!=="frozen"&&await fe(n,o,Kt);return{status:200,body:qn(n,u,d,l)}}s(xt,"handleRevive");async function Vt(e){const n=e.params.id;return{status:200,body:{newNodeId:(await yn(n))?.newNodeId??null}}}s(Vt,"handleRelaunchRoot");async function Wt(e){const n=e.params.id;await m(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw w("caller_pid must be a positive integer when provided");const r=Hn(),i=new Promise(u=>{e.res.once("close",()=>u())}),a=await Pe(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Xn(a)}}s(Wt,"handleClose");async function zt(e){if(!j(e.principal))throw new p(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await m(n),await ze(n),{status:204}}s(zt,"handleMarkRead");async function Jt(e){const n=e.params.id;await m(n);const t=await hn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}s(Jt,"handleRecycle");async function Ut(e){const n=e.params.id;return await m(n),await J(n,{lifecycle:"terminal"}),await N(e,n,["lifecycle"]),{status:200,body:await b(n)}}s(Ut,"handleDemote");async function Yt(e,n={}){const t=e.params.id,r=await m(t),i=e.body??{};i.kind!==void 0&&await U(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ve(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await mn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await N(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const u=await Y(a.meta,await H(t));return u.roadmap_written=a.roadmapWritten,u.roadmap_ref=a.roadmapRef,u.goal_path=a.goalPath,{status:200,body:u}}s(Yt,"handlePromote");async function Ht(e){const n=e.params.id;return await m(n),{status:200,body:{request:await bn(n)}}}s(Ht,"handleBrokerStructuredRequest");async function Qt(e){const n=e.params.id,t=e.body??{};if(await gn(n,t.expected_execution_id),typeof t.text!="string")throw new p(400,"invalid_request","text must be a string");return await m(n),{status:200,body:{captured:await Sn(n,t.text)}}}s(Qt,"handleBrokerGoal");async function Xt(e,n={}){const t=e.params.id,r=await m(t),i=e.body??{};i.kind!==void 0&&await U(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ve(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await vn(t,a);const u=await wn(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await Y(u.meta,await H(t))}}s(Xt,"handleYield");async function Zt(e){const n=e.params.id;await m(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw w("a wait requires a controller node id");const r=await R(t.controller);if(r===null)throw T(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new p(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await We(n,t.controller),{status:200,body:await b(n)}}s(Zt,"handleWait");async function qt(e){const n=e.principal,t=await pn(n.class==="broker"?async i=>i.grantee===n.app&&await $(n,i.grantee,i.node_id):n.class==="person"&&!j(n)?async i=>await $(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}s(qt,"handleReviveAll");const ei=new Set(["interrupt","steer","after-turn","next-turn"]);function ni(e){if(e===null)return null;const n=s(r=>{throw new y({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!ei.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}s(ni,"listenJson");async function N(e,n,t,r){t.length===0&&r===void 0||await W(async i=>{if(r?.(i),t.length===0)return;const a=await Je(i,n),u=await He(i,e),d=u.class==="person"?u.person:u.class==="app"?u.app:u.node;await Ue(i,d,a),await Ye(i,{event:"configured",object:a,actor:d,attrs:{changed:t.join(",")}})})}s(N,"recordConfigured");function Re(e){const n=L().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}s(Re,"restartLiveBroker");function Ie(e,n){try{return ee(e)===ee(n)}catch{return!1}}s(Ie,"sameDirectory");async function ti(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(h=>h!=="profile"&&h!=="restart"&&i[h]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await m(t),l=await zn(e,i.profile);Jn(l.profileId);const f=Un(l.profileId).manifest.grantee??"app:terminal";if(f!==(o.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${f}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(xn(o.kind)?(await U(o.kind,o.cwd,l.profileId),await J(t,{profileId:l.profileId})):await E(t,{profile_id:l.profileId}),await N(e,t,["profile"])),i.restart===!0&&Re(t),{status:200,body:await b(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(c=>c!=="cwd"&&c!=="keep_session"&&c!=="restart"&&i[c]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await m(t),f=C(l.cwd);if(i.keep_session===!0||f&&K(o)&&C(o)&&Ie(l.cwd,o)){if(!K(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const c=D(o);let S=!1;try{S=ne(c).isDirectory()}catch{}if(!S)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${c}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(f&&!Ie(l.cwd,c))throw new y({error:"cwd_not_same_directory",message:`${c} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const _=l.cwd;return _!==c&&(await W(async v=>{await E(t,{cwd:c}),await v.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(c,t,_),await Qe(t,_,c)}),await N(e,t,["cwd"])),i.restart===!0&&Re(t),{status:200,body:await b(t)}}if(await L().has(t)){const c=`${t} cannot repair its cwd while its broker is live`;throw new p(409,"cwd_node_live",c,{error:"cwd_node_live",message:c,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new y({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(C(l.cwd))throw new y({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!K(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const h=D(o);if(!C(h))throw new y({error:"cwd_missing",message:`cwd does not exist: ${h}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ne(h).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${h}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(c){throw c instanceof y?c:new y({error:"cwd_missing",message:`cwd does not exist: ${h}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await W(async()=>{await E(t,{cwd:h}),await Xe(t)}),await N(e,t,["cwd"]),{status:200,body:await b(t)}}let a=await m(t);const u=i.listen===void 0?void 0:ni(i.listen);if(i.scopes!==void 0){const o=ye(i.scopes),l=a.grantee==="app:terminal"?await ft(a):a.grant_id?await ct(a.grant_id):null;if(!o.every(f=>O(a.scopes,f)&&l!==null&&O(l.resolved,f)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!O(o,"crtr:llm"))throw new p(400,"invalid_scope","crtr:act requires crtr:llm");a=await E(t,{scopes:o})}if(i.situational_context!==void 0&&await Ee(t,Te(i.situational_context)),i.model!==void 0){const o=(await ue(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=$n(i.model,o),f=await pt(a.grant_id,i.model,l===void 0),h=f?{family:mt,strength:f.strength}:l,c=f?f.model:Nn(i.model,o);await V({kind:"concrete",spec:c},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const S=L();let _=!1;if(await S.isClaimed(t)&&await fe(t,S.get(t)?.handle.exited)&&(_=await Tn(t,c,h).then(()=>!0,v=>{if(v instanceof Pn)return!1;throw v})),!_){if(await S.isClaimed(t)){const v=`${t}'s broker did not accept the model switch; the model was not changed`;throw new p(409,"broker_not_ready",v,{error:"broker_not_ready",message:v,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!c.includes("/"))throw w(`model must resolve to a provider/id spec: ${i.model}`);await En(t,c,h)}a=await m(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Ae(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,f=i.lifecycle??a.lifecycle;let h;l==="orchestrator"&&!await In(t)&&(h=s(async()=>{const c=await kn(t);await Rn(t,c!==null&&c.trim()!==""?{goal:c.trim()}:{})},"beforePersist")),a=await J(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:f}:{}},h)}i.name!==void 0&&(a=await E(t,{name:i.name}),a.window&&On(a.window,Wn(a)));const d=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await N(e,t,d,u===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(u,t)}),{status:200,body:await b(t)}}s(ti,"handleConfig");async function Oe(e="app:terminal"){return(await ue(process.cwd(),Ne()||null,e)).kinds}s(Oe,"daemonKinds");async function Ae(e,n="app:terminal"){const t=Object.keys(await Oe(n));if(!t.includes(e))throw w(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}s(Ae,"assertKindServer");async function ii(){const e=await Oe();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}s(ii,"handleListKinds");const Or=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:Ot},{method:"GET",pattern:"/v1/nodes",handler:Ct},{method:"GET",pattern:"/v1/kinds",handler:s(()=>ii(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:qt},{method:"GET",pattern:"/v1/nodes/:id",handler:Et},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Tt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Pt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:Lt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:jt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Mt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Gt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:xt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Vt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Wt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:zt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Jt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ut},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Yt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Xt},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Ht},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Qt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Zt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:ti}];export{ti as handleConfig,Ot as handleCreate,Bt as handleFork,Ct as handleList,Yt as handlePromote,Xt as handleYield,Or as nodeRoutes,Nr as resolveCreateKind};
1
+ var Ee=Object.defineProperty;var s=(e,n)=>Ee(e,"name",{value:n,configurable:!0});import{envProfileId as Ne}from"../../../shared/env.js";import{pausedCanvasProfiles as Ce}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as ne,statSync as te}from"node:fs";import{isAbsolute as x,resolve as L}from"node:path";import{appendSituationalContext as Te,formatSituationalProse as Pe}from"../../../core/runtime/situational-context.js";import{closeNode as De}from"../../../core/runtime/close.js";import{reviveNode as Le}from"../../../core/runtime/revive.js";import{nowIso as V}from"../../../core/fs-utils.js";import{appPaidLaunch as je,assertLaunchModelRegistered as W,forkNode as Me,resolveForkSource as ie,spawnChildPrepared as Ge}from"../../../core/runtime/spawn.js";import{forkSourceNode as re,newNodeId as oe}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as ae,childrenOf as Fe,completeCreateRequest as de,findCreateRequest as se,getNode as R,recordCreateRequestNode as Be,reserveCreateRequest as le,reserveCreateRequestNode as Ke,listNodes as xe,recordRespawnAttempt as Ve,subscribersOf as We,subscriptionsOf as ce,updateNode as C}from"../../../core/canvas/canvas.js";import{armControllerWait as ze}from"../../../core/canvas/waits.js";import{withCanvasWrite as z}from"../../../core/canvas/db.js";import{markNodeRead as Je}from"../../../core/canvas/recovery.js";import{nodeObject as Ue}from"../../../core/graph/objects.js";import{recordActedOn as Ye}from"../../../core/graph/edges.js";import{publish as He}from"../../../core/graph/events.js";import{readerFor as Qe}from"../reader.js";import{relocateSessionCwd as Xe,unbindSession as Ze}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as qe}from"../../../core/canvas/attention.js";import{isSafeNodeId as en}from"../../../core/canvas/paths.js";import{contextDir as ue,nodeAgentDir as J}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as nn,cronRefusalError as tn}from"../../cron/authority.js";import{cronBirthPlacement as rn}from"../../cron/armed-context.js";import{existsBeneath as on,isAbsentOrRefused as an,isBeneathRefusal as dn,readdirBeneath as sn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as ln,readNodeSession as cn,readNodeSnapshot as un,transcriptMarkdown as fn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as pn}from"../../../core/substrate/subject.js";import{reviveAll as mn}from"../../../core/runtime/revive-all.js";import{promoteAsync as wn,requestYieldAsync as hn,reshapeNodeAsync as U}from"../../../core/runtime/promote.js";import{recycleNode as yn}from"../../../core/runtime/recycle.js";import{relaunchRoot as _n}from"../../../core/runtime/reset.js";import{assertReopenGate as gn}from"../../../core/runtime/reopen.js";import{requireCurrentExecution as bn}from"./broker-recovery.js";import{readOutputRequest as vn}from"../../../core/runtime/output-result.js";import{writeYieldMessage as kn,readGoal as Sn,captureGoalIfAbsent as Rn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as In,hasRoadmap as On}from"../../../core/runtime/roadmap.js";import{renameWindow as An}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as $n,explicitModelIntent as En,normalizeModel as Nn,readMergedLaunchConfigAsync as fe}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Cn}from"../../../core/model-routes.js";import{persistDormantModel as Tn,setModelLive as Pn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as pe}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Dn}from"../../../core/runtime/broker-request.js";import{boundFleet as j}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Ln}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as jn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as me}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Mn}from"../../../core/human/action-binding.js";import{resolveHumanAction as Gn}from"../../../core/human-actions.js";import{parseDurationMs as Fn}from"../../../core/wake.js";import{claimWarmNode as Bn,refillWarmPool as we,resumeWarmClaim as Kn,warmPoolEnabled as xn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as Y,isLaunchKind as Vn,resolveLaunchTarget as Wn}from"../../../core/runtime/launch-target.js";import{fullName as zn}from"../../../core/canvas/labels.js";import{reportsForNode as he}from"./reports.js";import{requireUsableProfile as Jn}from"./profiles.js";import{assertProfileActive as Un,loadExactProfileManifest as Yn}from"../../../core/profiles/manifest.js";import{getCron as ye}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Hn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Qn}from"../../control.js";import{notFound as T,usage as h}from"../../../core/errors.js";import{assertScope as Xn,validateScopes as _e}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Zn,toNodeDetailDTO as H,toNodeSummaryDTO as qn,toReviveResultDTO as et}from"../map.js";import{ApiError as f}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{runsOnBlaxel as nt}from"../environment-of.js";import{actsAsPerson as M,canReadNode as $,mayOnNode as tt,readableNodeIds as it,resolvedScopes as rt}from"../router.js";import{forwardVerb as ot,queryWithoutMachine as at,relayError as dt,unknownError as st,withMachine as lt}from"../../peer/forward.js";import{fileRoot as ct}from"../../../core/spaces/file-root.js";import{activeGrant as ut,payerOfGrant as ft}from"../../../core/grants/mirror.js";import{launchUsesHostedEndpoint as pt}from"../../../core/model-auth/readiness.js";import{nodeTerminalGrant as mt}from"../../../core/grants/terminal.js";import{appRungForGrant as wt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as ht}from"../../../core/model-routes.js";import{listProfileEnvNames as yt}from"../../../core/profiles/env-store.js";import{hasConfiguredProviderCredential as _t,NO_PROVIDER_CREDENTIAL_MESSAGE as ge}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as gt,mapAsync as be}from"../../../core/async-array.js";async function w(e){const n=await R(e);if(n===null)throw T(`unknown node: ${e}`,{received:e});return n}s(w,"requireMeta");async function Q(e){return{subscribesTo:await ce(e),subscribers:await We(e),children:await Fe(e)}}s(Q,"edgesFor");async function b(e){const n=await w(e);return await H(n,await Q(e))}s(b,"detailOf");async function bt(e){let n=(await he(e)).length;try{n+=sn(await J(e),await ue(e)).length}catch(t){if(!an(t))throw t}return n}s(bt,"countFiles");function vt(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw h("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&_e(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new f(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return n}s(vt,"parseCreateBody");function kt(e){if(e===void 0)return;const n=Fn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new f(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}s(kt,"parseDeadline");function St(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new f(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Mn.test(e.action))throw new f(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>me)throw new f(413,"payload_too_large",`serialized payload exceeds ${me} bytes`)}return e}}s(St,"parseOutcomeDelivery");function Rt(e,n){const t=Gn(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new f(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new f(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}s(Rt,"resolveOutcomeDelivery");function It(e,n,t){const r={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(r.mode=e.mode),e.name!==void 0&&(r.name=e.name),e.description!==void 0&&(r.description=e.description),n!==void 0&&(r.parent=n),e.creator!==void 0&&(r.creator=e.creator),e.scopes!==void 0&&(r.scopes=e.scopes),e.isolated!==void 0&&(r.isolated=e.isolated),e.root===!0&&(r.root=!0),e.root_lifecycle!==void 0&&(r.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(r.worktree=!0),typeof e.worktree=="string"&&(r.worktreeBase=e.worktree),e.worktree!==void 0&&(r.worktreeCwd=L(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(r.forkFrom=e.fork_from),e.model!==void 0&&(r.model=e.model),e.profile!==void 0&&(r.profile=e.profile),e.situational_context!==void 0&&(r.situationalContext=e.situational_context),e.node_id!==void 0&&(r.nodeId=e.node_id),r}s(It,"buildRecipe");function Ot(e,n,t){return!xn()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0||e.isolated!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}s(Ot,"warmRequestFor");import{resolveCreateKind as Tr}from"../../../core/runtime/launch-target.js";function ve(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Cn(e.model,n,e.modelExact===!0)}s(ve,"requestFromLaunch");function At(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(r=>!O(n,r));if(t.length===0)return e;throw new f(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}s(At,"withinCeiling");async function ke(e,n,t){const r=(await $n(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null,app:e.grantee??"app:terminal"})).launch;await W(ve(r),{cwd:e.cwd,profileId:e.profile_id??null},t)}s(ke,"assertNodeModelChangeRegistered");async function Se(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron")return;const r=ct({app:t.app,resolved:await rt(t),launched:t.scopes},n,"read");if("root"in r)return;const i="missing"in r?r.missing:null;throw new f(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}s(Se,"assertCallerReaches");const X=new Map;async function $t(e,n={},t={}){const r=At(vt(e.body),e.ceiling);if(e.principal.class==="broker"){const d=e.principal;if(r.prefer_warm===!0&&d.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const o=await w(r.parent);if(o.grantee!==d.app)throw new f(403,"other_app_run","cannot create a child under another app's node");if(!await $(d,o.grantee??"app:terminal",r.parent))throw T(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==d.node)throw new f(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let o=null;try{o=await re(await ie(r.fork_from))}catch{}if(o?.grantee!==d.app||!await $(d,o.grantee,o.node_id))throw new f(403,"other_app_run","cannot fork another app's conversation")}r.creator=d.node}if(e.principal.class==="person"&&e.principal.sub!==void 0){const d=r.fork_from===void 0?null:await re(await ie(r.fork_from)).catch(()=>null);for(const o of[r.parent,r.creator,d?.node_id])if(o!=null&&await R(o)!==null&&!await tt(e.principal,"edit",o))throw T(`unknown node: ${o}`,{received:o})}if(e.principal.class==="cron"){const d=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new f(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1,r.node_id=await oe(),d.isolated&&(r.isolated=!0,r.cwd=await J(r.node_id,d.app));const o=await nn({grantee:d.app,sub:d.sub,grant_id:d.grant,scopes:d.scopes,from_exec:d.from_exec},{profile:r.profile,cwd:r.cwd,pin_cwd:r.pin_cwd,kind:r.kind,model:r.model,mode:r.mode});if(!o.allowed)throw tn(o);if(r.scopes!==void 0){const l=r.scopes.find(p=>!O(o.effectiveScopes,p)||!O(d.scopes,p));if(l!==void 0)throw new f(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else d.scopes!==null&&(r.scopes=[...d.scopes])}r.creator!==void 0&&Xn(await w(r.creator),"crtr:act");const i=r.request_key?.trim();if(i===void 0||r.node_id!==void 0&&en(r.node_id)&&await R(r.node_id)!==null&&(await se(i))?.nodeId!==r.node_id)return G(e,r,n,t);const a=X.get(i);if(a!==void 0)return a;const c=Nt(e,r,i,n,t);X.set(i,c);try{return await c}finally{X.delete(i)}}s($t,"handleCreate");const Re="create_request_in_progress";async function Et(e,n,t){const r=Date.now()+1e4;for(;t!==null;){const i=await R(t);if(i!==null){if(!M(e.principal)&&!await $(e.principal,i.grantee??"app:terminal",t))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(t)}}if(Date.now()>=r||(await se(n))?.nodeId!==t)break;await new Promise(a=>setTimeout(a,100))}throw new f(409,Re,"another create with this request_key is in progress; retry it")}s(Et,"awaitForeignCreate");async function Nt(e,n,t,r,i){const a=await le(t);if(a.nodeId!==null&&await R(a.nodeId)!==null){if(a.state!=="warm_claimed"){const c=await R(a.nodeId);if(!M(e.principal)&&!await $(e.principal,c.grantee??"app:terminal",a.nodeId))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(a.nodeId)}}return G(e,n,r,i,a)}try{return await G(e,n,r,i,a)}catch(c){if(c instanceof f&&c.code===Re)throw c;const d=await le(t);throw(d.nodeId===null||await R(d.nodeId)===null)&&await ae(t,d.nodeId),c}}s(Nt,"handleKeyedCreateRequest");async function G(e,n,t,r,i=void 0){const a=r.deadlineAt??kt(n.deadline),c=St(n.outcome_delivery),d=e.principal.class==="cron"?await rn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:e.principal.kind==="exec"?null:(await ye(e.principal.cron))?.created_by??null},n.node_id):null;d!==null&&(n.root=d.root===!0);const o=d?.parent??n.parent??void 0;if(o==null&&n.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(n.output_schema!==void 0){try{l=JSON.parse(n.output_schema)}catch{throw h("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw h("output_schema must be a JSON schema object");await jn(l)}const p=await Wn(n,{validateKind:$e,...e.principal.class==="broker"||e.principal.class==="cron"?{app:e.principal.app}:{}}),{profileId:m,kind:u,cwd:_,launch:S}=p;if(n.pin_cwd!==void 0&&n.pin_cwd!==""&&n.worktree===void 0&&n.isolated!==!0&&!N(_)&&!await nt(m))throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${_}`,received:_,field:"cwd",next:"Pass an existing directory with --cwd."});await Se(e,_),n.worktree!==void 0&&await Se(e,L(n.pin_cwd??n.cwd??_));const v={...n,kind:u},P=c===void 0?void 0:Rt(c,_),q=("grant"in e.principal?e.principal.grant:null)??(o==null?null:(await R(o))?.grant_id??null);if(await W(ve(await je(S,q,n.model)),{cwd:_,profileId:m},t.modelRegistry),await ft(q)!=="app"&&!await _t(m===null?[]:await yt(m))&&!await pt(p))throw new f(412,"no_provider_credential",ge,{error:"no_provider_credential",message:ge,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let B=null;{const A=i===void 0||i.nodeId===null||i.state==="warm_claimed"?Ot(v,_,m):null,K=l===null&&r.beforeBrokerLaunch===void 0?void 0:async g=>{l!==null&&await Ln(g,"terminal",l),r.beforeBrokerLaunch?.(g)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const g=A===null?null:await Kn(A,i.nodeId,K);if(g===null)throw await ae(i.requestKey,i.nodeId),new f(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await de(i.requestKey,g),{status:201,body:await b(g)}}if(A!==null){const g=await Bn(A,{...a===void 0?{}:{deadlineAt:a},...P===void 0?{}:{outcomeDelivery:P},...i===void 0?{}:{requestKey:i.requestKey}},K);if(g!==null)return i!==void 0&&await de(i.requestKey,g),we(A),{status:201,body:await b(g)};B=A}const D=i?.nodeId??n.node_id??(i===void 0?void 0:await oe());if(i!==void 0&&i.nodeId===null){const g=await Ke(i.requestKey,D);if(g!==D)return await Et(e,i.requestKey,g)}const I=It(D===void 0?v:{...v,node_id:D},o,_);d!==null&&(d.rootLifecycle!==void 0&&(I.rootLifecycle=d.rootLifecycle),d.scopes!==void 0&&v.scopes===void 0&&(I.scopes=d.scopes),d.run!==void 0&&(I.run=d.run),d.withinCreate!==void 0&&(I.withinCreate=d.withinCreate)),a!==void 0&&(I.deadlineAt=a),P!==void 0&&(I.outcomeDelivery=P),I.readiness=n.root===!0?"await":"launch";const ee=await Ge(I,K,()=>{B!==null&&we(B)});return i!==void 0&&await Be(i.requestKey,ee.node.node_id),{status:201,body:await b(ee.node.node_id)}}}s(G,"handleCreateRequest");function k(e,n){const t=e.query.getAll(n);if(t.length>1)throw h(`${n} must appear at most once`);return t[0]}s(k,"singleQueryValue");function Z(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${n} must be true or false`)}}s(Z,"optionalBoolean");function F(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw h(`${n} must be one of: ${t.join(", ")}`)}}s(F,"oneOf");function Ct(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[S]of e.query)if(!n.has(S))throw h(`unknown nodes query parameter: ${S}`);const t=F(k(e,"status"),"status",["active","idle","done","dead","canceled"]),r=F(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=k(e,"kind"),a=F(k(e,"mode"),"mode",["base","orchestrator"]),c=k(e,"profile_id"),d=k(e,"profile_prefix"),o=k(e,"parent"),l=Z(k(e,"top_level"),"top_level"),p=k(e,"under"),m=Z(k(e,"under_inclusive"),"under_inclusive"),u=Z(k(e,"hanging"),"hanging"),_=F(k(e,"include"),"include",["activity"]);if(o!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...r!==void 0?{lifecycle:r}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...c!==void 0?{profile_id:c}:{},...d!==void 0?{profile_prefix:d}:{},...o!==void 0?{parent:o}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{under_inclusive:m}:{},...u!==void 0?{hanging:u}:{},..._!==void 0?{include:_}:{}}}s(Ct,"parseListQuery");async function Tt(e){const n=Ct(e);let t=await xe({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});const r=await it(e.principal);r!==null&&(t=t.filter(d=>r.has(d.node_id)));const i=n.include==="activity"?await qe(t.map(d=>d.node_id)):null,a=t.length>0?Ce():new Set;return{status:200,body:await be(t,async d=>{const o=await qn(d,d.profile_id!==null&&a.has(d.profile_id));if(i!==null){const l=await he(d.node_id);o.activity={latest_report:l[0]??null,final_report:d.final_report===null?null:l.find(p=>p.name===d.final_report)??null,pending_human_count:i[d.node_id]??0}}return o})}}s(Tt,"handleList");async function Pt(e){const n=e.params.id,t=await ot(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:at(e)});if(t.kind==="unknown")throw st(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw dt(t.status,t.body);return{status:t.status,body:lt(t.body,t.machine)}}return await w(n),{status:200,body:await b(n)}}s(Pt,"handleDetail");async function Dt(e){const n=e.params.id;await w(n);const t=await un(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:V()}}}s(Dt,"handleSnapshot");async function Lt(e){const n=e.params.id,t=await pn(n);if(t===null)throw T(`unknown node: ${n}`,{received:n});return{status:200,body:t}}s(Lt,"handleSubject");function jt(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw h(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw h("cursor must appear at most once");if(t.length>1)throw h("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const r=t[0],i=Number(r);if(!Number.isSafeInteger(i)||r==="")throw h("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}s(jt,"parseMessagesQuery");async function Mt(e){const n=e.params.id,t=await ln(n,jt(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:V()}}}s(Mt,"handleMessages");async function Gt(e){const n=e.params.id;await w(n);const t=await cn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:V()}}}s(Gt,"handleSession");async function Ft(e){const n=e.params.id;return await w(n),{status:200,body:{node_id:n,markdown:await fn(n)}}}s(Ft,"handleTranscript");async function Bt(e){const n=e.params.id;await w(n);const t=s(async(i,a)=>({node_id:i,label:(await R(i))?.name??i,dir:await ue(i),self:a,files:await bt(i)}),"root"),r=await gt([await t(n,!0),...await be(await ce(n),async i=>await t(i.node_id,!1))],async i=>await Kt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:r}}}s(Bt,"handleContext");async function Kt(e,n){try{return on(await J(e),n)}catch(t){if(dn(t))return!1;throw t}}s(Kt,"hasDir");async function xt(e){const n=await w(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>O(t,a)),...t.filter(a=>O(n.scopes,a))])],i=await Me(n.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await b(i.node.node_id)}}s(xt,"handleFork");const Vt=1e4;async function Wt(e){const n=e.params.id;await w(n);const t=e.body,r=t?.resume??!0,i=t?.reopen??!1;await gn(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!r&&t?.cron_id!==void 0?await ye(t.cron_id):null,c=await Le(n,{resume:r,capacity:"refuse",...a!==null?{wakeReason:await Hn(a,"schedule_revive")}:{}});c.outcome!=="already-live"&&await Ve(n,{failures:0,notBefore:null});const d=(await R(n))?.status??"active",o=(c.launch??j().get(n)?.handle)?.exited,l=c.outcome!=="frozen"&&await pe(n,o,Vt);return{status:200,body:et(n,c,d,l)}}s(Wt,"handleRevive");async function zt(e){const n=e.params.id;return{status:200,body:{newNodeId:(await _n(n))?.newNodeId??null}}}s(zt,"handleRelaunchRoot");async function Jt(e){const n=e.params.id;await w(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=Qn(),i=new Promise(c=>{e.res.once("close",()=>c())}),a=await De(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Zn(a)}}s(Jt,"handleClose");async function Ut(e){if(!M(e.principal))throw new f(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await w(n),await Je(n),{status:204}}s(Ut,"handleMarkRead");async function Yt(e){const n=e.params.id;await w(n);const t=await yn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}s(Yt,"handleRecycle");async function Ht(e){const n=e.params.id;return await w(n),await U(n,{lifecycle:"terminal"}),await E(e,n,["lifecycle"]),{status:200,body:await b(n)}}s(Ht,"handleDemote");async function Qt(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(r,{kind:i.kind??r.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":r.lifecycle,model:i.model},n.modelRegistry);const a=await wn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await E(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const c=await H(a.meta,await Q(t));return c.roadmap_written=a.roadmapWritten,c.roadmap_ref=a.roadmapRef,c.goal_path=a.goalPath,{status:200,body:c}}s(Qt,"handlePromote");async function Xt(e){const n=e.params.id;return await w(n),{status:200,body:{request:await vn(n)}}}s(Xt,"handleBrokerStructuredRequest");async function Zt(e){const n=e.params.id,t=e.body??{};if(await bn(n,t.expected_execution_id),typeof t.text!="string")throw new f(400,"invalid_request","text must be a string");return await w(n),{status:200,body:{captured:await Rn(n,t.text)}}}s(Zt,"handleBrokerGoal");async function qt(e,n={}){const t=e.params.id,r=await w(t),i=e.body??{};i.kind!==void 0&&await Y(i.kind,r.cwd,r.profile_id??null),i.model!==void 0&&await ke(r,{kind:i.kind??r.kind,mode:i.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await kn(t,a);const c=await hn(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await H(c.meta,await Q(t))}}s(qt,"handleYield");async function ei(e){const n=e.params.id;await w(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw h("a wait requires a controller node id");const r=await R(t.controller);if(r===null)throw T(`unknown controller: ${t.controller}`,{received:t.controller});if(r.status!=="active"&&r.status!=="idle")throw new f(422,"unprocessable",`controller ${t.controller} is ${r.status}`);return await ze(n,t.controller),{status:200,body:await b(n)}}s(ei,"handleWait");async function ni(e){const n=e.principal,t=await mn(n.class==="broker"?async i=>i.grantee===n.app&&await $(n,i.grantee,i.node_id):n.class==="person"&&!M(n)?async i=>await $(n,i.grantee??"app:terminal",i.node_id):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}s(ni,"handleReviveAll");const ti=new Set(["interrupt","steer","after-turn","next-turn"]);function ii(e){if(e===null)return null;const n=s(r=>{throw new y({error:"invalid_listen",message:r,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[r,i]of t)/^(?:[1-9]|10)$/.test(r)||n(`listen level must be 1..10: ${r}`),(typeof i!="string"||!ti.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}s(ii,"listenJson");async function E(e,n,t,r){t.length===0&&r===void 0||await z(async i=>{if(r?.(i),t.length===0)return;const a=await Ue(i,n),c=await Qe(i,e),d=c.class==="person"?c.person:c.class==="app"?c.app:c.node;await Ye(i,d,a),await He(i,{event:"configured",object:a,actor:d,attrs:{changed:t.join(",")}})})}s(E,"recordConfigured");function Ie(e){const n=j().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}s(Ie,"restartLiveBroker");function Oe(e,n){try{return ne(e)===ne(n)}catch{return!1}}s(Oe,"sameDirectory");async function ri(e,n={}){const t=e.params.id,r=e.body;let i;if(r===void 0)i={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))i=r;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:r,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(m=>m!=="profile"&&m!=="restart"&&i[m]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const o=await w(t),l=await Jn(e,i.profile);Un(l.profileId);const p=Yn(l.profileId).manifest.grantee??"app:terminal";if(p!==(o.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${t} to ${o.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(o.profile_id??null)!==l.profileId&&(Vn(o.kind)?(await Y(o.kind,o.cwd,l.profileId),await U(t,{profileId:l.profileId})):await C(t,{profile_id:l.profileId}),await E(e,t,["profile"])),i.restart===!0&&Ie(t),{status:200,body:await b(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const o=i.cwd;if(typeof o!="string"||o==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:o,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await w(t),p=N(l.cwd);if(i.keep_session===!0||p&&x(o)&&N(o)&&Oe(l.cwd,o)){if(!x(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const u=L(o);let _=!1;try{_=te(u).isDirectory()}catch{}if(!_)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:o,field:"cwd",next:"Send an existing absolute directory."});if(p&&!Oe(l.cwd,u))throw new y({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:o,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:o,field:"cwd",next:"Reconcile the managed worktree first."});const S=l.cwd;return S!==u&&(await z(async v=>{await C(t,{cwd:u}),await v.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,S),await Xe(t,S,u)}),await E(e,t,["cwd"])),i.restart===!0&&Ie(t),{status:200,body:await b(t)}}if(await j().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new f(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:o,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(l.fork_from!=null)throw new y({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:o,field:"cwd",next:`Restore ${l.cwd}, then revive the fork normally.`});if(l.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:o,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(N(l.cwd))throw new y({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:o,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!x(o))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${o}`,received:o,field:"cwd",next:"Send an absolute path."});const m=L(o);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!te(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:o,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof y?u:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:o,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await z(async()=>{await C(t,{cwd:m}),await Ze(t)}),await E(e,t,["cwd"]),{status:200,body:await b(t)}}let a=await w(t);const c=i.listen===void 0?void 0:ii(i.listen);if(i.scopes!==void 0){const o=_e(i.scopes),l=a.grantee==="app:terminal"?await mt(a):a.grant_id?await ut(a.grant_id):null;if(!o.every(p=>O(a.scopes,p)&&l!==null&&O(l.resolved,p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:o,field:"scopes",next:"Send only scopes the node currently holds."});if(o.includes("crtr:act")&&!O(o,"crtr:llm"))throw new f(400,"invalid_scope","crtr:act requires crtr:llm");a=await C(t,{scopes:o})}if(i.situational_context!==void 0&&await Te(t,Pe(i.situational_context)),i.model!==void 0){const o=(await fe(a.cwd,a.profile_id??null,a.grantee??"app:terminal")).modelLadders,l=En(i.model,o),p=await wt(a.grant_id,i.model,l===void 0),m=p?{family:ht,strength:p.strength}:l,u=p?p.model:Nn(i.model,o);await W({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const _=j();let S=!1;if(await _.isClaimed(t)&&await pe(t,_.get(t)?.handle.exited)&&(S=await Pn(t,u,m).then(()=>!0,v=>{if(v instanceof Dn)return!1;throw v})),!S){if(await _.isClaimed(t)){const v=`${t}'s broker did not accept the model switch; the model was not changed`;throw new f(409,"broker_not_ready",v,{error:"broker_not_ready",message:v,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw h(`model must resolve to a provider/id spec: ${i.model}`);await Tn(t,u,m)}a=await w(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await $e(i.kind,a.grantee??"app:terminal");const o=i.kind??a.kind,l=i.mode??a.mode,p=i.lifecycle??a.lifecycle;let m;l==="orchestrator"&&!await On(t)&&(m=s(async()=>{const u=await Sn(t);await In(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await U(t,{...i.kind!==void 0?{kind:o}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},m)}i.name!==void 0&&(a=await C(t,{name:i.name}),a.window&&An(a.window,zn(a)));const d=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(o=>i[o]!==void 0);return await E(e,t,d,c===void 0?void 0:async o=>{await o.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(c,t)}),{status:200,body:await b(t)}}s(ri,"handleConfig");async function Ae(e="app:terminal"){return(await fe(process.cwd(),Ne()||null,e)).kinds}s(Ae,"daemonKinds");async function $e(e,n="app:terminal"){const t=Object.keys(await Ae(n));if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}s($e,"assertKindServer");async function oi(){const e=await Ae();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}s(oi,"handleListKinds");const Er=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:$t},{method:"GET",pattern:"/v1/nodes",handler:Tt},{method:"GET",pattern:"/v1/kinds",handler:s(()=>oi(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:ni},{method:"GET",pattern:"/v1/nodes/:id",handler:Pt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Dt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Lt},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:Mt},{method:"GET",pattern:"/v1/nodes/:id/session",handler:Gt},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Ft},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:xt},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Wt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:zt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Jt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Ut},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Yt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ht},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Qt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:qt},{method:"GET",pattern:"/v1/nodes/:id/broker/structured-request",handler:Xt},{method:"POST",pattern:"/v1/nodes/:id/broker/goal",handler:Zt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:ei},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:ri}];export{ri as handleConfig,$t as handleCreate,xt as handleFork,Tt as handleList,Qt as handlePromote,qt as handleYield,Er as nodeRoutes,Tr as resolveCreateKind};
@@ -0,0 +1,9 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type AppPrincipalResolver } from './principal.js';
3
+ export declare const KEY_SIGNIN_PATH = "/signin/key";
4
+ /** Every runtime sign-in page path: the vendor sign-in page and the API key page. */
5
+ export declare function isRuntimeSignInPath(pathname: string): boolean;
6
+ /** Serve one runtime sign-in request; errors propagate as RunErrors for the listener's error envelope. On a cloud role a key call runs
7
+ * as the person the handoff's `sub` names, with that person's settings loaded. */
8
+ export declare function handleRuntimeSignIn(req: IncomingMessage, res: ServerResponse, url: URL, principal: AppPrincipalResolver): Promise<void>;
9
+ export declare function keyPage(nonce: string, directoryOrigin: string): string;
@@ -0,0 +1,124 @@
1
+ var S=Object.defineProperty;var l=(e,r)=>S(e,"name",{value:r,configurable:!0});import{randomBytes as _,randomUUID as T}from"node:crypto";import{isCloudRole as $,runAsPerson as C}from"../../core/canvas/person.js";import{directoryIssuer as E}from"../../core/directory/issuer.js";import{emitEvent as v}from"../../core/events/emit.js";import{activationRecorded as I,awaitActivationAck as A}from"../../core/model-auth/activations.js";import{consumeHandoffJti as P,handoffActivation as R,handoffJtiConsumed as g,linkHandoffActivation as j,releaseHandoffJti as U}from"../../core/model-auth/handoff-jti.js";import{KEY_ROUTE_PROVIDERS as y,KeyRouteError as b,isKeyRouteProvider as L,keyRouteModels as O,saveKeyRoute as N,validateKeyRouteModels as H}from"../../core/model-auth/key-routes.js";import{RunError as u}from"../../core/runs/operations.js";import{loadPersonSettings as M}from"../../core/scoped-state/person-rows.js";import{personHasSnapshot as Y}from"../../core/scoped-state/person-store.js";import{unauthorizedHandoff as p}from"./principal.js";import{bearer as K,handleVendorSignIn as q,icon as m,isVendorSignInPath as w,jsonBody as B,page as G,sendJson as k,verifyOwnerHandoff as J}from"./vendor-signin.js";const f="/signin/key",h=`${f}/session`,z={anthropic:"Anthropic",openai:"OpenAI",openrouter:"OpenRouter",moonshotai:"Moonshot (Kimi)"};function pe(e){return w(e)||e===f||e===h}l(pe,"isRuntimeSignInPath");async function me(e,r,t,n){if(w(t.pathname)){await q(e,r,t,n);return}const a=e.method??"GET";if(t.pathname===f&&a==="GET"){F(r,n);return}const s=t.pathname===h&&a==="GET"?D:t.pathname===f&&a==="POST"?V:void 0;if(s===void 0)throw new u(404,"not_found","unknown operation");const o=await J(n,K(e),"model_credential");if(!$()){await s(e,r,t,n,o);return}await C(o.sub,async()=>{Y()||await M(o.sub),await s(e,r,t,n,o)})}l(me,"handleRuntimeSignIn");async function D(e,r,t,n,a){if(await g(a.jti))throw p("model_credential");const s=t.searchParams.getAll("return_to");let o;try{o=s.length===1?new URL(s[0]).origin:void 0}catch{o=void 0}if(o!==new URL(n.issuer).origin)throw new u(400,"invalid_request","return_to must be an absolute URL on the directory origin","return_to");const c=await Promise.all(y.map(async d=>({id:d,name:z[d],models:(await O(d)).map(i=>({...i,tools:!0}))})));k(r,200,{providers:c})}l(D,"session");async function V(e,r,t,n,a){const s=await B(e),o=s.api_key;if(o===void 0){const i=await R(a.jti);if(i===void 0)throw p("model_credential");await x(r,i);return}if(await g(a.jti))throw p("model_credential");const c=s.provider;if(typeof c!="string"||!L(c))throw new u(400,"invalid_request",`provider must be one of ${y.join(", ")}`,"provider");if(typeof o!="string"||o.trim()==="")throw new u(400,"invalid_request","api_key is required","api_key");try{await H(c,s.models)}catch(i){throw i instanceof b?new u(400,"invalid_request",i.message,"models"):i}if(E()===null)throw new u(503,"runtime_starting","this runtime has not joined a directory yet");if(!await P(a.jti,a.exp))throw p("model_credential");const d=T();await j(a.jti,d);try{if((await N(c,o.trim(),s.models,d)).activationId===null)throw new u(503,"runtime_starting","this runtime has not joined a directory yet")}catch(i){throw await I(d)||await U(a.jti),v({level:"error",event:"key_signin.save_failed",error:i,fields:{provider:c}}),i instanceof b?new u(400,"invalid_request",i.message,"models"):i}v({level:"info",event:"key_signin.saved",fields:{provider:c,activation_id:d}}),await x(r,d)}l(V,"save");async function x(e,r){const t=await A(r);k(e,200,t.status==="acknowledged"?{status:"active",trial:t.trial}:{status:"saved",ack:"pending"})}l(x,"answer");function F(e,r){const t=_(16).toString("base64");e.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff","Content-Security-Policy":`default-src 'none'; script-src 'nonce-${t}'; style-src 'nonce-${t}'; connect-src 'self'; form-action 'none'; base-uri 'none'; frame-ancestors 'none'`}),e.end(Z(t,new URL(r.issuer).origin))}l(F,"servePage");const X=[{id:"ultra",label:"Ultra"},{id:"strong",label:"Strong"},{id:"medium",label:"Medium"},{id:"light",label:"Light"}],Q=`
2
+ .lead{color:var(--muted)}
3
+ select,input[type=password]{width:100%;min-width:0;height:2.75rem;padding:0 .875rem;background:var(--surface);color:var(--text);border:1px solid var(--line-strong);border-radius:8px;font:400 .9375rem/1.5 var(--sans)}
4
+ input[type=password]{height:3rem;font-family:var(--mono)}
5
+ select:focus,input[type=password]:focus{outline:2px solid var(--focus);outline-offset:2px}
6
+ select:disabled{color:var(--disabled);border-color:var(--line);cursor:default}
7
+ select[aria-invalid=true],input[type=password][aria-invalid=true]{border-color:var(--danger-line)}
8
+ fieldset{margin:0;padding:0;border:0;display:flex;flex-direction:column;gap:.75rem;min-width:0}
9
+ legend{padding:0;margin-bottom:.25rem;font-weight:500}
10
+ .strengths{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem}
11
+ #key-form{gap:1.25rem}
12
+ .alert.info{background:var(--zone)}
13
+ .alert.info>.ic{color:var(--muted)}
14
+ .done-mark{display:flex;align-items:center;justify-content:center;width:3.5rem;height:3.5rem;flex:none;border-radius:12px;background:var(--accent-subtle);color:var(--accent-fg)}
15
+ .done-mark .ic{width:1.5rem;height:1.5rem}
16
+ .loading{display:flex;align-items:center;gap:.75rem;color:var(--muted)}
17
+ .loading .spin{width:1rem;height:1rem;color:var(--accent-fg);fill:none;stroke:currentColor;stroke-width:3;stroke-linecap:round}
18
+ @media (prefers-reduced-motion:no-preference){.loading .spin{animation:spin 1s linear infinite}}
19
+ @media (max-width:30rem){.strengths{grid-template-columns:minmax(0,1fr)}}
20
+ `,W=`
21
+ (function(){
22
+ function $(id){return document.getElementById(id);}
23
+ var frag=new URLSearchParams(location.hash.slice(1));
24
+ var cfg=JSON.parse($('cfg').textContent);
25
+ var handoff=frag.get('handoff'),returnTo=frag.get('return_to');
26
+ history.replaceState(null,'',location.pathname);
27
+ // Only a return_to on the directory's origin is ever linked or redirected to.
28
+ try{if(returnTo&&new URL(returnTo).origin!==cfg.directory)returnTo=null;}catch(e){returnTo=null;}
29
+ var auth={'Authorization':'Bearer '+handoff};
30
+ var providers=[];
31
+ function show(id){['loading','form-card','pending-card','done-card','stop-card'].forEach(function(x){$(x).hidden=x!==id;});}
32
+ function stop(title,text){$('stop-title').textContent=title;$('stop-text').textContent=text;$('stop-back').hidden=!returnTo;show('stop-card');}
33
+ function backUrl(status){var u=new URL(returnTo);if(status)u.searchParams.set('status',status);return u.toString();}
34
+ function used(){stop('This link no longer works','It has expired or was already used. Go back to your account and choose Add an API key again.');}
35
+ if(returnTo){$('stop-back').href=backUrl();}
36
+ if(!handoff||!returnTo){stop('This link is incomplete','Go back to your account and choose Add an API key again.');return;}
37
+ function setError(msg){$('error-text').textContent=msg;$('error').className=msg?'err on':'err';}
38
+ var form=$('key-form'),providerSel=$('provider'),keyInput=$('api-key'),strengths=['ultra','strong','medium','light'];
39
+ function fillModels(){
40
+ var p=providers.filter(function(x){return x.id===providerSel.value;})[0];
41
+ strengths.forEach(function(s){
42
+ var sel=$('model-'+s);sel.innerHTML='';sel.removeAttribute('aria-invalid');
43
+ var none=document.createElement('option');none.value='';none.textContent=p?'Choose a model':'Choose a provider first';none.disabled=true;none.selected=true;sel.appendChild(none);
44
+ (p?p.models:[]).forEach(function(m){var o=document.createElement('option');o.value=p.id+'/'+m.id;o.textContent=m.name;sel.appendChild(o);});
45
+ sel.disabled=!p;
46
+ });
47
+ }
48
+ fetch('${h}?return_to='+encodeURIComponent(returnTo),{headers:auth})
49
+ .then(function(r){return r.json().then(function(b){return {s:r.status,b:b};});})
50
+ .then(function(x){
51
+ if(x.s===401){used();return;}
52
+ if(x.s!==200){stop('Something went wrong',(x.b&&x.b.error&&x.b.error.message)||'Your runtime could not load this page. Try again in a moment.');return;}
53
+ providers=x.b.providers;
54
+ providers.forEach(function(p){var o=document.createElement('option');o.value=p.id;o.textContent=p.name;providerSel.appendChild(o);});
55
+ fillModels();show('form-card');
56
+ })
57
+ .catch(function(){stop('Could not reach your runtime','Check your connection and reload this page.');});
58
+ providerSel.addEventListener('change',fillModels);
59
+ function post(body){
60
+ return fetch('${f}',{method:'POST',headers:Object.assign({'Content-Type':'application/json'},auth),body:JSON.stringify(body)})
61
+ .then(function(r){return r.json().then(function(b){return {s:r.status,b:b};});});
62
+ }
63
+ function outcome(x){
64
+ if(x.s===200&&x.b.status==='active'){$('done-back').href=backUrl('connected');show('done-card');$('done-back').focus();return true;}
65
+ if(x.s===200&&x.b.status==='saved'){show('pending-card');return true;}
66
+ if(x.s===401){used();return true;}
67
+ return false;
68
+ }
69
+ form.addEventListener('submit',function(e){
70
+ e.preventDefault();setError('');
71
+ var bad=null;
72
+ if(!providerSel.value)bad=bad||providerSel;
73
+ keyInput.removeAttribute('aria-invalid');
74
+ if(!keyInput.value.trim()){keyInput.setAttribute('aria-invalid','true');bad=bad||keyInput;}
75
+ var models={};
76
+ strengths.forEach(function(s){var sel=$('model-'+s);sel.removeAttribute('aria-invalid');if(!sel.value){sel.setAttribute('aria-invalid','true');bad=bad||sel;}else models[s]=sel.value;});
77
+ if(bad){setError(!providerSel.value?'Choose a provider.':!keyInput.value.trim()?'Paste your API key.':'Choose a model for every strength.');bad.focus();return;}
78
+ var button=$('save');button.disabled=true;$('save-label').textContent='Saving\\u2026';
79
+ post({provider:providerSel.value,api_key:keyInput.value.trim(),models:models}).then(function(x){
80
+ // A 401 may mean this handoff's save already went through and its answer was lost: ask for that save's acknowledgement.
81
+ return x.s===401?post({}):x;
82
+ }).then(function(x){
83
+ if(outcome(x)){keyInput.value='';return;}
84
+ setError((x.b&&x.b.error&&x.b.error.message)||'Your key was not saved. Try again.');
85
+ }).catch(function(){setError('Could not reach your runtime. Try again.');})
86
+ .then(function(){button.disabled=false;$('save-label').textContent='Save key';});
87
+ });
88
+ $('retry').addEventListener('click',function(){
89
+ var button=$('retry');button.disabled=true;
90
+ // The handoff's save is already stored: a retry carries no key and only asks for that save's acknowledgement.
91
+ post({}).then(function(x){if(!outcome(x)){$('pending-text').textContent='Northlight still has not confirmed it. Try again in a moment.';}})
92
+ .catch(function(){$('pending-text').textContent='Could not reach your runtime. Try again in a moment.';})
93
+ .then(function(){button.disabled=false;});
94
+ });
95
+ })();
96
+ `;function Z(e,r){const t=l(n=>`<div class="field"><label for="model-${n.id}">${n.label}</label><select id="model-${n.id}" name="${n.id}" required disabled></select></div>`,"strengthField");return G({nonce:e,title:"Add an API key",style:Q,script:W,config:{directory:r},body:`<div class="card" id="loading"><div class="loading" aria-live="polite">
97
+ <svg class="spin" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M21 12a9 9 0 1 1-9-9"/></svg><span>Loading\u2026</span></div></div>
98
+ <div class="card" id="form-card" hidden>
99
+ <div><h1>Add an API key</h1><p class="lead">Your key goes straight to your runtime, where it is stored encrypted.</p></div>
100
+ <form id="key-form" autocomplete="off" novalidate>
101
+ <div class="field"><label for="provider">Provider</label><select id="provider" name="provider" required><option value="" disabled selected>Choose a provider</option></select></div>
102
+ <div class="field"><label for="api-key">API key</label><input type="password" id="api-key" name="api_key" required spellcheck="false" autocapitalize="off" autocomplete="off"></div>
103
+ <fieldset><legend>Model for each strength</legend>
104
+ <p class="small">Northlight's apps ask for a strength, from Ultra (the most capable) to Light (the fastest). The model you choose for a strength answers those requests.</p>
105
+ <div class="strengths">${X.map(t).join("")}</div>
106
+ </fieldset>
107
+ <div class="alert info">${m("alert")}<div class="text">Some models may not work well with Northlight's apps.</div></div>
108
+ <div id="error" class="err" role="alert">${m("alert")}<span id="error-text"></span></div>
109
+ <button class="btn primary lg wide" type="submit" id="save"><span id="save-label">Save key</span></button>
110
+ </form>
111
+ </div>
112
+ <div class="card" id="pending-card" hidden>
113
+ <div class="alert" role="alert">${m("warn")}<div class="text"><strong>Your key is saved, but the switch is not confirmed yet</strong><span id="pending-text">Northlight has not confirmed the change. Try again in a moment.</span></div>
114
+ <div class="act"><button class="btn primary sm" type="button" id="retry">Try again</button></div></div>
115
+ </div>
116
+ <div class="card" id="done-card" hidden>
117
+ <div class="head"><div class="done-mark">${m("check")}</div><h1>Your API key is on</h1></div>
118
+ <p>Your agents now use your key.</p>
119
+ <a class="btn primary lg wide" id="done-back" href="#">Back to your account</a>
120
+ </div>
121
+ <div class="card" id="stop-card" hidden>
122
+ <div><h1 id="stop-title"></h1><p class="lead" id="stop-text"></p></div>
123
+ <a class="btn" id="stop-back" href="#" hidden>Back to your account</a>
124
+ </div>`})}l(Z,"keyPage");export{f as KEY_SIGNIN_PATH,me as handleRuntimeSignIn,pe as isRuntimeSignInPath,Z as keyPage};