@north-light/cli 0.3.511 → 0.3.513
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.d.ts +3 -1
- package/dist/api/client.js +3 -3
- package/dist/api/command-manifest/object-kinds.js +1 -1
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/canvas.d.ts +12 -0
- package/dist/api/dto/custom-objects.d.ts +1 -0
- package/dist/api/dto/health.d.ts +8 -0
- package/dist/api/dto/objects.d.ts +1 -0
- package/dist/api/routes.d.ts +1 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/crouter-sdk/release-notes.md +12 -0
- package/dist/builtin-memory/crouter-sdk/resources.md +1 -1
- package/dist/clients/attach/chrome/canvas-panels.d.ts +5 -0
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/chrome/object-wait.d.ts +4 -0
- package/dist/clients/attach/chrome/object-wait.js +1 -0
- package/dist/clients/attach/chrome/roster.d.ts +3 -0
- package/dist/clients/attach/chrome/roster.js +4 -4
- package/dist/clients/attach/session/editor-inventory.js +2 -2
- package/dist/clients/attach/session/readonly-popup.d.ts +15 -0
- package/dist/clients/attach/session/readonly-popup.js +1 -0
- package/dist/clients/attach/viewer.js +604 -604
- package/dist/commands/custom-object/register.js +1 -1
- package/dist/core/canvas/canvas.d.ts +0 -13
- package/dist/core/canvas/canvas.js +16 -18
- package/dist/core/canvas/migrations.js +40 -22
- package/dist/core/canvas/remote-canvas-source.js +1 -1
- package/dist/core/canvas/render-source.d.ts +1 -1
- package/dist/core/canvas/types.d.ts +0 -4
- package/dist/core/canvas/waits.d.ts +23 -2
- package/dist/core/canvas/waits.js +9 -4
- package/dist/core/graph/custom.d.ts +1 -0
- package/dist/core/graph/custom.js +2 -2
- package/dist/core/graph/events.js +6 -6
- package/dist/core/graph/kinds/custom.d.ts +1 -0
- package/dist/core/graph/kinds/custom.js +1 -1
- package/dist/core/graph/kinds/kind.d.ts +3 -0
- package/dist/core/graph/object-waits.d.ts +11 -0
- package/dist/core/graph/object-waits.js +1 -0
- package/dist/core/human/page-schema.d.ts +1 -1
- package/dist/core/llm/run.js +2 -2
- package/dist/core/runtime/broker/model-adapter.js +2 -2
- package/dist/core/runtime/lifecycle.js +2 -2
- package/dist/core/runtime/nodes.js +1 -1
- package/dist/core/runtime/stop-guard.js +3 -3
- package/dist/daemon/api/app-listener.js +12 -12
- package/dist/daemon/api/handlers/canvas.js +5 -5
- package/dist/daemon/api/handlers/health.js +3 -3
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/readiness.d.ts +10 -0
- package/dist/daemon/readiness.js +1 -0
- package/dist/daemon/reconcilers/live-obligation.js +1 -1
- package/dist/types.d.ts +1 -0
- package/docs/sdk/release-notes.md +12 -0
- package/docs/sdk/resources.md +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +12 -12
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var _=Object.defineProperty;var r=(t,e)=>_(t,"name",{value:e,configurable:!0});import{hasActiveLiveSubscription as S,
|
|
2
|
-
WHERE d.destination_id = ? AND d.wake = 1 AND m.kind IN ('message', 'completed') AND d.created_at > ? LIMIT 1`).get(t,e.at)!==void 0?{count:0,at:e.at}:e}r(R,"effectiveSchemaReprompts");function
|
|
1
|
+
var _=Object.defineProperty;var r=(t,e)=>_(t,"name",{value:e,configurable:!0});import{hasActiveLiveSubscription as S,hasPendingCronWake as v,getNode as c}from"../canvas/index.js";import{hasLiveControllerWait as w,hasLiveObjectWait as O}from"../canvas/waits.js";import{contextDir as m}from"../canvas/node-agent-paths.js";import{activeBackgroundBashJobs as f}from"../bash-jobs.js";import{hasOpenReplyBearingRequestByRequester as L}from"../human/requests.js";import{formatCard as o,formatStructuredOutputReprompt as b,STALL_REPROMPT as A}from"../../shared/generated-context.js";import{readOutputRequest as d,readSchemaReprompts as N,writeSchemaReprompts as q}from"./structured-output.js";import{openDb as x}from"../canvas/db.js";import{prepared as y}from"../sqlite-statements.js";const h=3;function g(t){return t.parent==null&&t.run_id===t.node_id&&t.metadata_json!=null}r(g,"isAppRunRoot");function R(t){const e=N(t);return e.count===0?e:y(x(),`SELECT 1 FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
2
|
+
WHERE d.destination_id = ? AND d.wake = 1 AND m.kind IN ('message', 'completed') AND d.created_at > ? LIMIT 1`).get(t,e.at)!==void 0?{count:0,at:e.at}:e}r(R,"effectiveSchemaReprompts");function E(t){const{count:e}=R(t);return e>=h?!1:(q(t,{count:e+1,at:Date.now()}),!0)}r(E,"takeRunSchemaReprompt");function U(t){return t.pi_pid!=null&&g(t)&&d(t.node_id).state==="valid"&&R(t.node_id).count<h&&u(t.node_id,f(m(t.node_id)).length>0)===null}r(U,"runSchemaRepromptPending");import{STALL_REPROMPT as z}from"../../shared/generated-context.js";function P(t,e){return o("stop-guard",{},b(JSON.stringify(e,null,2),t))}r(P,"formatValidStructuredOutputReprompt");function T(t){return o("stop-guard",{},`Structured-output request file is invalid and cannot be used: ${t}
|
|
3
3
|
|
|
4
4
|
You have two options:
|
|
5
5
|
1. Remove the invalid file (the output-schema.json in your node directory has been corrupted)
|
|
6
6
|
2. Fix the corruption if you know the original request schema
|
|
7
7
|
|
|
8
|
-
After resolving the file, call the \`submit_result\` tool again (with \`decline\` when the schema cannot be honestly satisfied). If this is unexpected, escalate to the user using \`crtr human send\`.`)}r(
|
|
8
|
+
After resolving the file, call the \`submit_result\` tool again (with \`decline\` when the schema cannot be honestly satisfied). If this is unexpected, escalate to the user using \`crtr human send\`.`)}r(T,"formatInvalidStructuredOutputReprompt");function u(t,e){return v(t)?"scheduled":S(t)||w(t)||O(t)||L(t)||e?"awaiting":null}r(u,"wakeCapableWait");function V(t,e,i=f(m(t)).length>0){if(e.pushedFinal)return{action:"allow",reason:"finished"};const a=d(t);if(a.state==="valid"){const l=u(t,i);if(l!==null)return{action:"allow",reason:l};const p=c(t);return p!==null&&g(p)&&!E(t)?{action:"allow",reason:"dormant"}:{action:"reprompt",reason:"stalled",message:P(a.request.request_id,a.request.schema)}}if(a.state==="invalid")return{action:"reprompt",reason:"stalled",message:T(a.error)};const n=c(t);if(n!==null&&(n.final_report!=null||n.status==="done"||n.status==="dead"||n.status==="canceled"))return{action:"allow",reason:"finished"};if(n!==null&&n.lifecycle==="resident")return{action:"allow",reason:"dormant"};const s=u(t,i);return s!==null?{action:"allow",reason:s}:{action:"reprompt",reason:"stalled",message:o("stop-guard",{},A)}}r(V,"evaluateStop");export{h as RUN_SCHEMA_REPROMPT_LIMIT,z as STALL_REPROMPT,V as evaluateStop,g as isAppRunRoot,U as runSchemaRepromptPending};
|
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
var G=Object.defineProperty;var
|
|
1
|
+
var G=Object.defineProperty;var s=(e,r)=>G(e,"name",{value:r,configurable:!0});import{randomUUID as F}from"node:crypto";import{createServer as Y}from"node:http";import{Router as J}from"./router.js";import{toErrorBody as q}from"./map.js";import{objectRoutes as Q}from"./handlers/objects.js";import{customObjectRoutes as W}from"./handlers/custom-objects.js";import{docRoutes as K}from"./handlers/docs.js";import{OPERATIONS as Z}from"./operations.js";import{runtimeReadiness as ee}from"../readiness.js";import{errorCodes as L}from"../../api/error-codes.js";import{MINIMUM_RUNTIME_VERSION_HEADER as te,RUNTIME_VERSION_HEADER as ne,minimumRuntimeRefusal as re}from"../../api/runtime-version.js";import{CONTRACT_HEADER as ae,CONTRACT_LEVEL as U,REQUIRED_CONTRACT_HEADER as oe,contractRefusal as ie}from"../../api/contract.js";import{crtrVersion as j}from"../../shared/crtr-version.js";import{AppPrincipalResolver as se}from"./principal.js";import{isDaemonRoute as ue,runtimeOwner as de,servePeer as V}from"../peer/ingress.js";import{applySyncNotice as ce}from"./sync-notice.js";import{ownMachineId as le}from"../../core/peer/directory.js";import{handleRunOperation as fe,integer as me}from"./handlers/runs.js";import{llmCallerOf as pe,parseLlmRequest as he,runLlm as ye}from"../../core/llm/run.js";import{parseUsageMonth as we,usageFor as _e}from"../../core/usage/ledger.js";import{capFields as ge}from"./handlers/llm.js";import{CONTROL_BODY_MAX_BYTES as ve,MODEL_CONTEXT_BODY_MAX_BYTES as Re}from"../../core/llm/body-limits.js";import{RunError as l,runIsRunning as Oe}from"../../core/runs/operations.js";import{requireRun as x}from"./router.js";import{deferHead as Ee}from"./deferred-head.js";import{readRunEvents as X,registerGrantStream as be,subscribeRunEvents as Se}from"../../core/runs/events.js";import{activeGrant as $,payerOfGrant as Te}from"../../core/grants/mirror.js";function Ae(e){if(Te(e)==="app")throw new l(401,"grant_revoked","this app-paid grant is no longer active");return null}s(Ae,"appPaidGone");import{releaseGrantWaiters as Ne}from"../../core/grants/watch.js";import{runNotices as Ce}from"../run-notices.js";import{handleVendorSignIn as Pe,isVendorSignInPath as Ie}from"./vendor-signin.js";import{listAppProfiles as ke}from"./handlers/app-profiles.js";import{handleTransferDownload as He,handleTransferOperation as Me,TRANSFER_OPERATIONS as De}from"./handlers/transfer.js";import{handleQuestionOperation as je,QUESTION_OPERATIONS as xe}from"./handlers/questions.js";import{vendorStatus as Be}from"./handlers/vendor-status.js";import{handleMemoryOperation as Je,MEMORY_OPERATIONS as Le}from"./handlers/memory.js";import{abortOnClose as Ue,callerFromApp as Ve,handleProviderOperation as Xe,PROVIDER_OPERATIONS as $e,providerFailure as ze}from"./handlers/providers.js";function Ge(e){return Object.prototype.hasOwnProperty.call(L,e)?L[e]:void 0}s(Ge,"fixedRow");function Fe(e){const r=Ge(e);return r?r.type:e==="stream_gap"||e==="provider_error"||e==="runtime_version_unsupported"?"invalid_request_error":"server_error"}s(Fe,"errorType");function Ye(e){if(!e||typeof e!="object"||Array.isArray(e)||!("rate_limit"in e))return e;const{rate_limit:r,...o}=e;return o}s(Ye,"appDetails");function D(e,r,o){const f=Ye(e.details);return{error:{code:e.code,message:e.message,...f===void 0?{}:{details:f},type:Fe(e.code),...e.param?{param:e.param}:{},origin:"runtime",retryable:e.retryable||e.code==="stream_dropped",request_id:r,...o?{run_id:o}:{},...e.scope?{scope:e.scope}:{},...e.code==="unauthorized"?{user_action:"reconnect"}:{},...ge(e),...e.code==="all_routes_exhausted"?{retry_after_s:e.details.retry_after_s}:{}}}}s(D,"envelope");function qe(e,r,o,f){const u=r instanceof l?r:new l(500,"server_failure","runtime request failed");if(r instanceof l||console.error("[app-listener]",r),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(D(u,o,f))}
|
|
3
3
|
|
|
4
|
-
`);return}e.writeHead(u.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...u.code==="all_routes_exhausted"?{"Retry-After":String(u.details.retry_after_s)}:{}}),e.end(JSON.stringify(D(u,o,f)))}
|
|
4
|
+
`);return}e.writeHead(u.status,{"Content-Type":"application/json; charset=utf-8","Request-Id":o,"X-Content-Type-Options":"nosniff",...u.code==="all_routes_exhausted"?{"Retry-After":String(u.details.retry_after_s)}:{}}),e.end(JSON.stringify(D(u,o,f)))}s(qe,"fail");function z(e){return Array.isArray(e)?e[0]:e}s(z,"headerValue");function O(e,r,o){e.writeHead(r,{"Content-Type":"application/json; charset=utf-8"}),e.end(JSON.stringify(o))}s(O,"json");async function P(e,r=ve){const o=[];let f=0;for await(const u of e){if(f+=u.length,f>r)throw new l(400,"invalid_request","request body too large");o.push(u)}if(f)try{return JSON.parse(Buffer.concat(o).toString("utf8"))}catch{throw new l(400,"invalid_request","invalid JSON body")}}s(P,"bodyOf");function Qe(e,r){const o=e.headers["last-event-id"]??r.get("after");if(Array.isArray(o))throw new l(400,"invalid_request","invalid cursor","after");return me(o??null,"after",0,Number.MAX_SAFE_INTEGER,0)}s(Qe,"cursor");function We(e){return`id: ${e.sequence_number}
|
|
5
5
|
event: ${e.type}
|
|
6
6
|
data: ${JSON.stringify(e)}
|
|
7
7
|
|
|
8
|
-
`}
|
|
8
|
+
`}s(We,"frame");const Ke=6e4;function Ze(e,r,o,f,u,y,E,A={}){x(f,o);let g=X(o,u);if(u>g.latest_sequence)throw new l(400,"invalid_request","cursor is beyond the run","after");if(u<g.latest_sequence&&(g.earliest_sequence===null||u<g.earliest_sequence-1))throw new l(409,"stream_gap","events have expired",void 0,{earliest_sequence:g.earliest_sequence,latest_sequence:g.latest_sequence});if(r.destroyed||e.destroyed)return r.destroy(),Promise.resolve();r.writeHead(200,{"Content-Type":E==="sse"?"text/event-stream":"application/x-ndjson","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),E==="sse"?r.write(`: connected
|
|
9
9
|
|
|
10
|
-
`):r.flushHeaders();let w=u;const B=
|
|
11
|
-
data: ${JSON.stringify(D(m,
|
|
10
|
+
`):r.flushHeaders();let w=u;const B=Ce().streamOpened(o);let n=!1,t=!1,h=!1,b;const N=new Promise(m=>{b=m}),_=s(()=>{n||(n=!0,B(w),clearInterval(d),clearInterval(R),I(),H(),r.off("close",_),r.off("drain",p),r.end(),b())},"end"),p=s(()=>{h=!1,a()},"onDrain"),v=s(m=>{n||r.write(E==="sse"?`event: error
|
|
11
|
+
data: ${JSON.stringify(D(m,y,o))}
|
|
12
12
|
|
|
13
|
-
`:`${JSON.stringify({type:"error",...D(m,
|
|
14
|
-
`),
|
|
15
|
-
`),w=m.sequence_number}}catch(m){v(m instanceof l?m:new l(500,"server_failure","stream failed"))}finally{t=!1}}},"flush"),k=
|
|
13
|
+
`:`${JSON.stringify({type:"error",...D(m,y,o)})}
|
|
14
|
+
`),_()},"error"),a=s(()=>{if(!(n||t)){t=!0;try{if(!T()){k();return}if(x(f,o),g=X(o,w),g.backlog_count>1e3||g.backlog_bytes>32*1024*1024){v(new l(503,"stream_dropped","stream reader fell behind",void 0,{last_sequence:w}));return}for(const m of g.events){if(h)break;h=!r.write(E==="sse"?We(m):`${JSON.stringify(m)}
|
|
15
|
+
`),w=m.sequence_number}}catch(m){v(m instanceof l?m:new l(500,"server_failure","stream failed"))}finally{t=!1}}},"flush"),k=s(()=>v(new l(401,"grant_revoked","grant is not active")),"revoked"),T=s(()=>"class"in f||$(f.grant)!==null,"grantActive"),I=Se(o,a),H="class"in f?()=>{}:be(f.grant,k),d=setInterval(()=>{!n&&!h&&E==="sse"&&r.write(`: keepalive
|
|
16
16
|
|
|
17
|
-
`)},15e3),M=A.idleMs??
|
|
17
|
+
`)},15e3),M=A.idleMs??Ke,i=A.isRunning??Oe;let S=Date.now(),c=w;const R=setInterval(()=>{if(n||E!=="sse")return;const m=Date.now();let C=!0;try{C=i(o)}catch{}if(C||w!==c){S=m,c=w;return}m-S<M||h||(r.write(`event: idle
|
|
18
18
|
data: {}
|
|
19
19
|
|
|
20
|
-
`),
|
|
20
|
+
`),_())},A.idleCheckMs??1e3);return R.unref(),r.on("drain",p),r.on("close",_),a(),N}s(Ze,"streamRunEvents");function xt(e,r,o,f={}){const u=e.listener;if(!e.issuer||!e.audience||!u?.address||!Number.isInteger(u.port)||u.port<1||u.port>65535)throw new Error("runtime issuer, audience and listener address/port are required");if(["0.0.0.0","::","[::]"].includes(u.address))throw new Error("runtime listener must bind a specific address");const y=new se(e.issuer,e.audience,o,e.jwksUrl),E=new J,A=new Map;for(const n of Z.filter(t=>t.stage!==void 0)){const t=s(()=>({status:500}),"handler");E.register({method:n.method,pattern:n.path,handler:t}),A.set(t,n)}const g=new J().registerAll(Q).registerAll(W).registerAll(K),w=Y((n,t)=>{(async()=>{Ee(n,t,f.deferHead);const h=F();t.setHeader("Request-Id",h),t.setHeader(ne,j()),t.setHeader(ae,U);let b;try{const N=z(n.headers[te.toLowerCase()]),_=re(N,j())??ie(z(n.headers[oe.toLowerCase()]),U,{legacyMinimum:N,runtimeVersion:j()});if(_!==null)throw _.status===400?new l(400,_.code,_.message,_.param):new l(426,_.code,_.message,void 0,_.details);const p=new URL(n.url??"/","http://runtime.local");if(Ie(p.pathname)){await Pe(n,t,p,y);return}const v=E.match(n.method??"GET",p.pathname),a=v?A.get(v.handler):void 0,k=a?.name==="runtime.sync-notice"||a?.name==="runtime.vendor-status";let T,I;if(!k&&n.headers.authorization!==void 0)try{T=await y.verifyCall(n.headers.authorization)}catch(i){I=i}const H={issuer:e.issuer,jwks:y.jwks,audience:s(()=>e.audience,"audience"),owner:de,self:le,syncGrants:o,ready:s(()=>y.isReady()&&r(),"ready")};if(T?.chain[0]?.sub.startsWith("runtime:")){await V(n,t,H,T);return}if(T===void 0&&a===void 0&&await ue(n.method??"GET",p.pathname)){await V(n,t,H,{status:401,code:"unauthorized",message:I===void 0?"a machine token is required":"invalid machine token"});return}if(a?.name==="ready"){const i=ee({jwksReady:y.isReady(),grantsReady:r});O(t,i.ready?200:503,i);return}if((n.method!=="GET"||p.pathname!=="/v1/health")&&(!y.isReady()||!r()))throw new l(503,"runtime_starting","runtime_starting");if(!v||!a)throw new l(404,"not_found","unknown operation");if(b=v.params.run_id,a.name==="health"){O(t,200,{status:"ok",api_version:"2026-09-23"});return}if(a.name==="runtime.sync-notice"){await ce(await y.verifySyncNotice(n.headers.authorization),o,h),t.writeHead(204),t.end();return}if(a.name==="runtime.vendor-status"){await y.verifyDirectoryRead(n.headers.authorization,"vendor_status"),O(t,200,Be());return}if(T===void 0)throw I??new l(401,"unauthorized","a directory access token is required");const d=await y.resolveVerified(T,a.scope);if(t.setHeader("Request-Id",h),b&&x(d,b,["run.message","run.interrupt","run.cancel","run.rename","run.delete"].includes(a.name),a.name==="run.delete"),a.stage==="objects"){const i=g.match(a.method,p.pathname);if(!i)throw new l(404,"not_found","unknown operation");const S={method:a.method,path:p.pathname,params:i.params,query:p.searchParams,body:await P(n,i.maxBodyBytes),ceiling:d.resolved,principal:{class:"app",app:d.grantee,scopes:d.resolved},req:n,res:t};let c;try{c=await i.handler(S)}catch(R){const{status:m,body:C}=q(R);throw m>=500&&console.error("[app-listener]",R),new l(m,C.error.code,C.error.message,void 0,C.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 He(n,t,d,p.searchParams);return}if(a.stream){Ze(n,t,b,d,Qe(n,p.searchParams),h,"sse",f.stream);return}if(a.name==="llm"){const i=he(await P(n,Re)),S=new AbortController,c=s(()=>S.abort(),"abort");t.on("close",c);try{const R=await ye(i,S.signal,i.stream?m=>{t.headersSent||t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache","X-Accel-Buffering":"no"}),t.write(`data: ${JSON.stringify(m)}
|
|
21
21
|
|
|
22
|
-
`)}:void 0,void 0,{grantee:d.grantee,spend_cap:d.spend_cap},
|
|
22
|
+
`)}:void 0,void 0,{grantee:d.grantee,spend_cap:d.spend_cap},pe($(d.grant)??Ae(d.grant)));i.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
|
-
`)):
|
|
24
|
+
`)):O(t,200,R.completion)}finally{t.off("close",c)}return}if(a.name==="usage.get"){O(t,200,_e(d.grantee,d.spend_cap,we(p.searchParams.get("month"))));return}if(a.name==="profile.list"){O(t,200,ke(d));return}if(xe.has(a.name)){const i=await je(a.name,d,v.params.question_id,a.method==="POST"?await P(n):void 0);O(t,i.status,i.body);return}if($e.has(a.name)){const{signal:i,release:S}=Ue(t);try{const c=await Xe(a.name,Ve(d),{params:v.params,body:a.method==="POST"?await P(n):void 0,query:p.searchParams},{requestId:h,signal:i});O(t,c.status,c.body)}catch(c){const R=ze(c,h,!0);t.writeHead(R.status,{"Content-Type":"application/json; charset=utf-8","X-Content-Type-Options":"nosniff",...R.headers}),t.end(JSON.stringify(R.body))}finally{S()}return}if(Le.has(a.name)){const i=Je(a.name,{class:"app",app:d.grantee,scopes:d.resolved},p.searchParams);O(t,i.status,i.body);return}if(De.has(a.name)){const i=await Me(a,d,v.params,p.searchParams,await P(n));O(t,i.status,i.body);return}const M=await fe(a,d,b,p.searchParams,await P(n),n.headers["idempotency-key"]);O(t,M.status,M.body)}catch(N){qe(t,N,h,b)}})()});return{ready:new Promise((n,t)=>{w.once("error",t),w.listen(u.port,u.address,()=>{w.off("error",t),n()})}),close:s(async()=>{y.close(),Ne(),w.closeAllConnections(),await new Promise((n,t)=>w.close(h=>h?t(h):n()))},"close")}}s(xt,"createAppListener");export{Ke as RUN_STREAM_IDLE_MS,xt as createAppListener,Qe as cursor,Ze as streamRunEvents};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var l=(t,e)=>Y(t,"name",{value:e,configurable:!0});import{gzipSync as V}from"node:zlib";import{browseNodes as P,graphNodes as X,listNodes as F,pruneNodes as Z,pruneToLimit as ee,rosterEdges as w,rosterNodes as te}from"../../../core/canvas/canvas.js";import{
|
|
2
|
-
`);if(e.length>0){const
|
|
3
|
-
`).forEach((
|
|
1
|
+
var Y=Object.defineProperty;var l=(t,e)=>Y(t,"name",{value:e,configurable:!0});import{gzipSync as V}from"node:zlib";import{browseNodes as P,graphNodes as X,listNodes as F,pruneNodes as Z,pruneToLimit as ee,rosterEdges as w,rosterNodes as te}from"../../../core/canvas/canvas.js";import{liveObjectWaitsNamed as ne,readControllerWait as oe}from"../../../core/canvas/waits.js";import{activeBackgroundBashJobs as se}from"../../../core/bash-jobs.js";import{contextDir as re}from"../../../core/canvas/node-agent-paths.js";import{nowIso as I}from"../../../core/fs-utils.js";import{isPidPresent as ie}from"../../../core/canvas/pid.js";import{dashboardRowsAllFromSource as ae,enrichRowsFromSource as de}from"../../../core/canvas/render-source.js";import{localCanvasSource as G}from"../../../core/canvas/source.js";import{ticketCountsForNodes as D,ticketsAcrossCanvas as le}from"../../../core/canvas/attention.js";import{buildCorpus as ce,groupCorpus as ue,resolveRef as fe}from"../../../core/canvas/history.js";import{listFocuses as q,reapEmptyNodes as pe}from"../../../core/runtime/placement.js";import{boundFleet as me}from"../../../core/runtime/fleet.js";import{retentionHold as _e}from"../../reconcilers/live-obligation.js";import{notFound as he,usage as _}from"../../../core/errors.js";import{openDb as ye}from"../../../core/canvas/db.js";import{prepared as be}from"../../../core/sqlite-statements.js";import{view as ge}from"../../../core/canvas/tree.js";import{isLiveStatus as ve}from"../../../core/canvas/node-order.js";import{readNodeRecap as ke}from"../../../core/canvas/node-recap.js";import{readGoal as Se}from"../../../core/runtime/kickoff.js";import{faultSummary as we}from"../../../core/canvas/status-glyph.js";import{listPendingAsks as Ne}from"../../../core/human/requests.js";import{toGraphNodeDTO as Re}from"../map.js";import{actsAsPerson as Ce,canReadNode as T,canReadRun as je}from"../router.js";import{ApiError as $}from"../../../api/errors.js";function N(t){return t.principal.class==="person"?null:new Set(F().filter(e=>T(t.principal,e.grantee??"app:terminal",e.node_id)).map(e=>e.node_id))}l(N,"visibleNodes");function H(t){return t.principal.class==="person"?null:new Set(F().filter(e=>e.run_id?je(t.principal,e.grantee??"app:terminal",e.node_id):T(t.principal,e.grantee??"app:terminal",e.node_id)).map(e=>e.node_id))}l(H,"visibleHistoryNodes");function Ie(t){const e=N(t);return{status:200,body:{items:le().filter(n=>e===null||e.has(n.node_id)).map(n=>({node_id:n.node_id,name:n.name,cwd:n.cwd,count:n.count,subjects:n.subjects}))}}}l(Ie,"handleAttention");function Me(t){const e=t.body;if(e===null||typeof e!="object"||!Array.isArray(e.node_ids))throw _("attention count request requires node_ids: string[]");const r=e.node_ids;if(!r.every(s=>typeof s=="string"))throw _("attention count request node_ids must contain only strings");const n=N(t);return{status:200,body:{counts:D(r.filter(s=>n===null||n.has(s)))}}}l(Me,"handleAttentionCounts");function x(t){return Buffer.from(String(t),"utf8").toString("base64")}l(x,"encodeCursor");function z(t){const e=Number(Buffer.from(t,"base64").toString("utf8"));if(!Number.isInteger(e)||e<0)throw _(`invalid cursor: ${t}`);return e}l(z,"decodeCursor");function Le(t,e,r){const a=t.loadBody().split(`
|
|
2
|
+
`);if(e.length>0){const c=a.findIndex(p=>{const f=p.toLowerCase();return e.some(h=>f.includes(h))});if(c!==-1)return a.slice(c,c+r).map(p=>p.trim()).filter(p=>p!=="").join(" \u23CE ")}const s=a.map(c=>c.trim()).filter(c=>c!=="").slice(0,r).join(" \u23CE ");return s!==""?s:t.title}l(Le,"snippet");function Oe(t,e,r){const n=[...t];return e==="relevance"&&r!==void 0?n.sort((a,s)=>(r.get(s.ref)??0)-(r.get(a.ref)??0)||s.tsMs-a.tsMs||a.ref.localeCompare(s.ref)):e==="oldest"?n.sort((a,s)=>a.tsMs-s.tsMs||a.ref.localeCompare(s.ref)):n.sort((a,s)=>s.tsMs-a.tsMs||a.ref.localeCompare(s.ref)),n}l(Oe,"sortArtifacts");function Ee(t){if(t==null)return{};if(typeof t!="object")throw _("history search body must be a JSON object");return t}l(Ee,"parseSearchBody");function Te(t){if(t===null||typeof t!="object")throw _("history grep body must be a JSON object");const e=t;if(typeof e.pattern!="string"||e.pattern==="")throw _("history grep body requires a non-empty pattern");return e}l(Te,"parseGrepBody");function B(t,e){const r={cwd:t.cwd,allCwds:t.all_cwds===!0,under:t.under,nodes:t.nodes},n={types:t.types,kinds:t.kinds,statuses:t.statuses,sinceMs:t.since_ms,untilMs:t.until_ms,origins:t.origins,roles:t.roles,from:t.from},a=H(e);return ce(r,n).filter(s=>a===null||a.has(s.nodeId))}l(B,"buildCorpusFromQuery");function $e(t){if(t==null)return{};if(typeof t!="object")throw _("history stats body must be a JSON object");return t}l($e,"parseStatsBody");const J=["origin","node","kind","day","type","role"];function Be(t){const e=$e(t.body),r=e.group_by??"type";if(!J.includes(r))throw _(`--group-by must be one of: ${J.join(", ")}; received: ${String(e.group_by)}`);const n=B(e,t),a=ue(n,r);return{status:200,body:{group_by:r,groups:a,total:a.reduce((c,p)=>c+p.count,0),scanned:n.length}}}l(Be,"handleHistoryStats");function Ae(t){const e=Te(t.body),r=Math.min(100,Math.max(1,e.limit??20)),n=B(e,t),a=e.cursor!==void 0?z(e.cursor):0;let s;try{s=new RegExp(e.pattern,"i")}catch{throw _(`invalid regex pattern: ${e.pattern}`)}const c=[];for(const i of n)i.loadBody().split(`
|
|
3
|
+
`).forEach((u,g)=>{s.test(u)&&c.push({ref:i.ref,node:`${i.nodeName} (${i.nodeId})`,ts:i.ts,line:g+1,text:u.trim()})});c.sort((i,o)=>i.ref.localeCompare(o.ref)||i.line-o.line);const p=c.slice(a,a+r),f=a+r<c.length?x(a+r):null;return{status:200,body:{hits:p,next_cursor:f,total:c.length}}}l(Ae,"handleHistoryGrep");function Pe(t){const e=Ee(t.body),r=(e.query??"").trim(),n=e.weigh_body===!0,a=e.full===!0,s=Math.max(1,e.snippet_lines??1),c=Math.min(100,Math.max(1,e.limit??20)),p=e.per_node===!0;if(p&&(e.nodes===void 0||e.nodes.length===0))throw new $(400,"invalid_request","`per_node` requires a non-empty `nodes` list",{param:"nodes"});const f=B(e,t),h=e.cursor!==void 0?z(e.cursor):0,i=r.toLowerCase().split(/\s+/).filter(d=>d.length>0);let o=f,u;const g=e.sort??(i.length>0?"relevance":"recency");if(i.length>0&&g==="relevance"){u=new Map;const d=[];for(const m of f){const E=m.title.toLowerCase(),U=m.nodeName.toLowerCase(),Q=m.nodeDesc.toLowerCase(),A=n?m.loadBody().toLowerCase():null;let S=0;for(const j of i)E.includes(j)&&(S+=10),U.includes(j)&&(S+=5),Q.includes(j)&&(S+=3),A!==null&&A.includes(j)&&(S+=1);S>0&&(u.set(m.ref,S),d.push(m))}o=d}else i.length>0&&(o=f.filter(d=>{const m=`${d.title}
|
|
4
4
|
${d.nodeName}
|
|
5
|
-
${d.nodeDesc}${
|
|
6
|
-
`+d.loadBody():""}`.toLowerCase();return i.some(
|
|
5
|
+
${d.nodeDesc}${n?`
|
|
6
|
+
`+d.loadBody():""}`.toLowerCase();return i.some(E=>m.includes(E))}));let b=Oe(o,g,u);if(p){const d=new Set;b=b.filter(m=>!d.has(m.nodeId)&&d.add(m.nodeId))}const v=p?b:b.slice(h,h+c),y=!p&&h+c<b.length?x(h+c):null;return{status:200,body:{hits:v.map(d=>{const m={ref:d.ref,node:`${d.nodeName} (${d.nodeId})`,kind:d.nodeKind,source:d.source,ts:d.ts,...p?{node_id:d.nodeId}:{}};return g==="relevance"&&u!==void 0&&(m.score=u.get(d.ref)??0),a?m.body=d.loadBody():m.snippet=Le(d,i,s),m}),next_cursor:y,total:b.length}}}l(Pe,"handleHistorySearch");function Fe(t){const e=(t.query.get("ref")??"").trim();if(!e.includes(":"))throw _(`ref must be <node-id>:inbox/<n>, <node-id>:session, or <node-id>:session/<n>; received: ${e}`,{received:e,next:"Get a valid ref from `crtr canvas history search`. Reports and documents are `crtr canvas read <name>`."});const r=fe(e);if(r===null)throw he(`no inbox entry or message for ref: ${e}`,{ref:e,next:"Re-run `crtr canvas history search` for a current ref. Reports and documents are `crtr canvas read <name>`."});if(H(t)?.has(r.nodeId)===!1)throw new $(404,"not_found","artifact not found");const n=r.source,s=t.query.get("format")==="raw"&&r.raw!==null?r.raw:r.body;return{status:200,body:{ref:e,node:`${r.nodeName} (${r.nodeId})`,source:n,ts:r.ts,content:s}}}l(Fe,"handleHistoryRead");function Ge(t){for(const[n]of t.query)if(n!=="live")throw _(`unknown snapshot query parameter: ${n}`);const e=t.query.getAll("live");if(e.length>1)throw _("live must appear at most once");const r=e[0];if(r===void 0||r==="false"||r==="0")return!1;if(r==="true"||r==="1")return!0;throw _("live must be true or false")}l(Ge,"snapshotLiveOnly");async function De(t){const e=new Set(q().map(i=>i.node_id)),r=N(t),n=(await ae(G,e,Ge(t))).filter(i=>r===null||r.has(i.node_id)),a=D(n.map(i=>i.node_id));await de(G,n,a);const s=n.map(i=>{const o=i.srcRow,u=o?.host_kind??"tmux";return{node_id:i.node_id,name:i.name,title:i.handle??i.name,description:i.description??null,kind:i.kind,mode:i.mode,lifecycle:i.lifecycle??o?.lifecycle,status:i.status,cwd:i.cwd,profile_id:i.profile_id??null,parent:o?.parent??null,created:i.created,host_kind:u,enterable:u==="broker",attention_count:i.asks,...o?.cycles!=null?{cycles:o.cycles}:{},...i.mtimeMs!==void 0?{last_activity:new Date(i.mtimeMs).toISOString()}:{},ctx_tokens:i.ctx_tokens,streaming:i.streaming??!1,jobs_active:o!==void 0&&ie(o.pi_pid)?se(re(i.node_id)).length:0,waiting_for:oe(i.node_id)?.controllerId??null,hanging:i.hanging??null,viewed:i.viewed??!1,final_report:o?.final_report??null,finalized_at:o?.finalized_at??null}}),c=new Map;for(const i of w()){const o=c.get(i.from_id);o===void 0?c.set(i.from_id,[i.to_id]):o.push(i.to_id)}const p=new Set(n.map(i=>i.node_id)),f=Object.fromEntries(n.map(i=>[i.node_id,(c.get(i.node_id)??[]).filter(o=>p.has(o))]));return{status:200,body:{generated_at:I(),nodes:s,subscriptions:f}}}l(De,"handleSnapshot");function K(){const t=te().map(n=>{const a=n.host_kind??"tmux";return{node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:a,enterable:a==="broker",parent:n.parent,created:n.created}}),e=w().map(n=>({from_id:n.from_id,to_id:n.to_id,active:n.active,created:n.created})),r=ne().map(n=>({node_id:n.nodeId,object_id:n.objectId,object_type:n.objectType,object_name:n.objectName,created:new Date(n.createdAt).toISOString()}));return{generated_at:I(),nodes:t,edges:e,object_waits:r}}l(K,"buildRoster");let R=null,M=null;function qe(){return R===null?(R=Promise.resolve().then(()=>K()).finally(()=>{R=null}),R):(M===null&&(M=R.then(()=>K()).finally(()=>{M=null})),M)}l(qe,"rosterCoalesced");async function He(t){const e=await qe(),r=N(t);return r===null?{status:200,body:e}:{status:200,body:{...e,nodes:e.nodes.filter(n=>r.has(n.node_id)),edges:e.edges.filter(n=>r.has(n.from_id)&&r.has(n.to_id)),object_waits:(e.object_waits??[]).filter(n=>r.has(n.node_id))}}}l(He,"handleRoster");function W(t){if(t.name!==""&&t.name!==t.kind)return t.name;const e=(t.description??"").trim();return e!==""?e:t.name}l(W,"liveRootName");const xe=1440*6e4;function ze(){const t=P(),e=new Map(t.map(o=>[o.node_id,o])),r=new Map(be(ye(),"SELECT node_id, reply_at, read_at, intent FROM nodes WHERE parent IS NULL").all().map(o=>[o.node_id,o])),n=Ne(),a=new Map;for(const o of n)a.set(o.requester_node_id,(a.get(o.requester_node_id)??0)+1);const s=new Date(Date.now()-xe).toISOString(),c=l(o=>{const u=r.get(o.node_id);return u?.reply_at!=null&&(u.read_at==null||u.reply_at>u.read_at)||(a.get(o.node_id)??0)>0?!0:o.status!=="done"||u?.intent!=="parked"?!1:[o.created,o.telemetry_updated_at,u.reply_at].reduce((v,y)=>y!=null&&y>v?y:v,"")>=s},"keepFinished"),p=t.filter(o=>o.parent===null&&o.kind!=="human"&&(ve(o.status)||c(o))),f=new Map;for(const o of w())f.set(o.from_id,[...f.get(o.from_id)??[],o.to_id]);const h=l(o=>{const u=e.get(o)?.fault;return u&&u.link!=="broker\u2194crtrd"?we(u):null},"faultOf"),i=p.map(o=>{const u=[o.node_id,...ge(o.node_id)].filter(d=>e.get(d)?.kind!=="human"&&e.has(d)),g=new Set(u),b=n.filter(d=>g.has(d.requester_node_id)),v=r.get(o.node_id),y=v?.reply_at??null,O=v?.read_at??null;let k=o.created;for(const d of u){const m=e.get(d).telemetry_updated_at;m!=null&&m>k&&(k=m)}return y!==null&&y>k&&(k=y),{node_id:o.node_id,name:W(o),cwd:o.cwd,profile_id:o.profile_id,status:o.status,state_line:(()=>{const d=ke(o.node_id)?.state.trim();return d||null})(),goal:Se(o.node_id)?.trim()||null,asks:b.length,first_ask_ticket_id:b[0]?.inbox_ticket_id??null,fault:u.map(h).find(d=>d!==null)??null,running_count:u.filter(d=>e.get(d).streaming===!0).length,unread:y!==null&&(O===null||y>O),last_activity:k,children:(f.get(o.node_id)??[]).filter(d=>e.has(d)&&e.get(d).kind!=="human").map(d=>{const m=e.get(d);return{node_id:d,name:W(m),status:m.status,streaming:m.streaming===!0,asks:a.get(d)??0,fault:h(d)}})}});return{generated_at:I(),rows:i}}l(ze,"buildLiveRoots");let C=null,L=null;function Je(){const t=l(()=>Promise.resolve().then(ze),"run");return C===null?(C=t().finally(()=>{C=null}),C):(L===null&&(L=C.then(t).finally(()=>{L=null})),L)}l(Je,"liveRootsCoalesced");async function Ke(t){if(!Ce(t.principal))throw new $(403,"permission_error","only the person reads the dashboard");const e=await Je(),r=t.query.get("profile");return{status:200,body:r===null?e:{...e,rows:e.rows.filter(n=>n.profile_id===r)}}}l(Ke,"handleLiveRoots");function We(t){const e=P().filter(s=>t.principal.class==="person"||T(t.principal,s.grantee??"app:terminal",s.node_id)).map(s=>({node_id:s.node_id,name:s.name,description:s.description,kind:s.kind,mode:s.mode,lifecycle:s.lifecycle,status:s.status,cwd:s.cwd,profile_id:s.profile_id,grantee:s.grantee??"app:terminal",parent:s.parent,created:s.created,frozen_at:s.frozen_at??null,terminal_reason:s.terminal_reason??null,final_report:s.final_report??null,telemetry_tokens_in:s.telemetry_tokens_in??null,telemetry_updated_at:s.telemetry_updated_at??null,fault:s.fault&&s.fault.link!=="broker\u2194crtrd"?{...s.fault,link:s.fault.link}:null,streaming:s.streaming??!1})),r=new Set(e.map(s=>s.node_id)),n=w().filter(s=>r.has(s.from_id)&&r.has(s.to_id));return{status:200,rawBody:V(JSON.stringify({nodes:e,edges:n}),{level:1}),headers:{"content-type":"application/gzip"}}}l(We,"handleBrowse");function Ue(t){const e=N(t);return{status:200,body:{generated_at:I(),nodes:X().filter(n=>e===null||e.has(n.node_id)).map(Re),edges:w().filter(n=>e===null||e.has(n.from_id)&&e.has(n.to_id)).map(n=>({from_id:n.from_id,to_id:n.to_id,active:n.active,created:n.created})),focused_node_ids:q().map(n=>n.node_id).filter(n=>e===null||e.has(n))}}}l(Ue,"handleGraph");function Qe(t){if(t==null)return{};if(typeof t!="object")throw _("prune body must be a JSON object");const e=t,r=l(i=>{const o=e[i];if(o!==void 0){if(typeof o!="number"||!Number.isFinite(o))throw _(`${i} must be a number`);return o}},"num"),n=l(i=>{const o=e[i];if(o!==void 0){if(typeof o!="boolean")throw _(`${i} must be a boolean`);return o}},"bool"),a={},s=r("limit");s!==void 0&&(a.limit=s);const c=r("ttl_days");c!==void 0&&(a.ttl_days=c);const p=n("include_stale");p!==void 0&&(a.include_stale=p);const f=n("empty");f!==void 0&&(a.empty=f);const h=n("dry_run");return h!==void 0&&(a.dry_run=h),a}l(Qe,"parsePruneBody");function Ye(t){const e=Qe(t.body),r=e.ttl_days??14,n=e.dry_run??!1,a=_e(me());let s;return e.limit!==void 0?s=ee({maxNodes:e.limit,held:a,dryRun:n}).pruned.map(f=>({node_id:f.node_id,status:f.status,created:f.created})):e.empty===!0?s=pe({dryRun:n}).map(f=>({node_id:f,status:"empty",created:""})):s=Z({ttlDays:r,held:a,dryRun:n,includeStale:e.include_stale??!1}).pruned.map(f=>({node_id:f.node_id,status:f.status,created:f.created})),{status:200,body:{pruned:s,dry_run:n,ttl_days:r}}}l(Ye,"handlePrune");const Nt=[{method:"GET",pattern:"/v1/canvas/attention",handler:Ie},{method:"POST",pattern:"/v1/canvas/attention/counts",handler:Me},{method:"POST",pattern:"/v1/canvas/history/search",handler:Pe},{method:"POST",pattern:"/v1/canvas/history/grep",handler:Ae},{method:"GET",pattern:"/v1/canvas/history/read",handler:Fe},{method:"POST",pattern:"/v1/canvas/history/stats",handler:Be},{method:"GET",pattern:"/v1/canvas/snapshot",handler:De},{method:"GET",pattern:"/v1/canvas/roster",handler:He},{method:"GET",pattern:"/v1/canvas/live-roots",handler:Ke},{method:"GET",pattern:"/v1/canvas/browse",handler:We},{method:"GET",pattern:"/v1/canvas/graph",handler:Ue},{method:"POST",pattern:"/v1/canvas/prune",ownerOnly:!0,handler:Ye}];export{Nt as canvasRoutes,We as handleBrowse};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var
|
|
1
|
+
var i=Object.defineProperty;var o=(e,t)=>i(e,"name",{value:t,configurable:!0});import{prepared as r}from"../../../core/sqlite-statements.js";import{openDb as s}from"../../../core/canvas/db.js";import{apiSocketPath as c}from"../../../core/canvas/paths.js";import{currentVersion as d}from"../../../core/self-update.js";import{API_VERSION as p}from"../../../api/index.js";import{DEFAULT_INTERVAL_MS as l}from"../../supervise-cadence.js";import{isPidPresent as _}from"../../../core/canvas/pid.js";import{boundDaemonControl as u}from"../../control.js";import{dueReport as m}from"../../due.js";import{runtimeReadiness as h}from"../../readiness.js";const f=l;function a(){try{return r(s(),"SELECT 1 FROM nodes LIMIT 1").get(),!0}catch{return!1}}o(a,"canvasAccessible");function E(){const e={},t=r(s(),`
|
|
2
2
|
SELECT status, COUNT(*) AS count
|
|
3
3
|
FROM node_rows
|
|
4
4
|
WHERE node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
5
5
|
GROUP BY status
|
|
6
|
-
`).all();for(const
|
|
6
|
+
`).all();for(const n of t)e[n.status]=n.count;return e}o(E,"nodeCounts");function T(){return r(s(),`
|
|
7
7
|
SELECT pi_pid
|
|
8
8
|
FROM node_rows
|
|
9
9
|
WHERE node_id NOT IN (SELECT node_id FROM warm_pool)
|
|
@@ -11,4 +11,4 @@ var c=Object.defineProperty;var o=(e,t)=>c(e,"name",{value:t,configurable:!0});i
|
|
|
11
11
|
AND pi_pid IS NOT NULL
|
|
12
12
|
AND turn_open_at IS NOT NULL
|
|
13
13
|
AND turn_closed_at IS NULL
|
|
14
|
-
`).all().filter(t=>_(t.pi_pid)).length}o(
|
|
14
|
+
`).all().filter(t=>_(t.pi_pid)).length}o(T,"busyNodeCount");function b(){const e=a(),t=u()?.startupBlock()??null,n={ok:e&&t===null,daemon_up:!0,store_accessible:e,brokers_reconciled:t===null,startup_phase:t?.phase??"ready",...t===null?{}:{startup_blocked:t.message}};return{status:n.ok?200:503,body:n}}o(b,"handleHealthz");function N(){const e=h();return{status:e.ready?200:503,body:e}}o(N,"handleReady");function L(e){if(!a())throw{status:503,code:"store_unavailable",message:"canvas store is inaccessible"};return{status:200,body:{daemon_pid:process.pid,tick_interval_ms:f,node_counts:E(),busy_node_count:T(),listeners:{socket_path:c(),tcp:e()},runtime_version:d(),api_version:p,startup_phase:u()?.startupBlock()?.phase??"ready"}}}o(L,"handleStatus");function R(){if(!a())throw{status:503,code:"store_unavailable",message:"canvas store is inaccessible"};return{status:200,body:m()}}o(R,"handleDue");function F(e){return[{method:"GET",pattern:"/healthz",handler:o(t=>b(),"handler")},{method:"GET",pattern:"/v1/ready",handler:o(t=>N(),"handler")},{method:"GET",pattern:"/v1/status",handler:o(t=>L(e),"handler")},{method:"GET",pattern:"/v1/due",handler:o(t=>R(),"handler")}]}o(F,"healthRoutes");export{F as healthRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var Oe=Object.defineProperty;var a=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{prepared as Z}from"../../../core/sqlite-statements.js";import{envProfileId as Ie}from"../../../shared/env.js";import{pausedCanvasProfiles as Ae}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as q,statSync as ee}from"node:fs";import{isAbsolute as F,resolve as T}from"node:path";import{appendSituationalContext as $e,formatSituationalProse as Ce}from"../../../core/runtime/situational-context.js";import{closeNode as Ne}from"../../../core/runtime/close.js";import{reviveNode as Te}from"../../../core/runtime/revive.js";import{nowIso as B}from"../../../core/fs-utils.js";import{appPaidLaunch as Ee,assertLaunchModelRegistered as K,forkNode as Pe,resolveForkSource as De,spawnChildPrepared as Le}from"../../../core/runtime/spawn.js";import{forkSourceNode as Me,newNodeId as ne}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as te,childrenOf as je,completeCreateRequest as oe,findCreateRequest as Ge,getNode as R,recordCreateRequestNode as Fe,reserveCreateRequest as re,reserveCreateRequestNode as Be,listNodes as ie,recordRespawnAttempt as Ke,subscribersOf as We,subscriptionsOf as de,setMessageWait as xe,updateNode as C}from"../../../core/canvas/canvas.js";import{subtreeIds as Ve}from"../../../core/canvas/nav-model.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 se,nodeAgentDir as x}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as en}from"../../cron/authority.js";import{cronBirthPlacement as nn}from"../../cron/armed-context.js";import{existsBeneath as tn,isAbsentOrRefused as on,isBeneathRefusal as rn,readdirBeneath as dn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as sn,readNodeSession as an,readNodeSnapshot as ln,transcriptMarkdown as cn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as fn}from"../../../core/substrate/subject.js";import{reviveAll as un}from"../../../core/runtime/revive-all.js";import{promoteAsync as pn,requestYieldAsync as mn,reshapeNodeAsync as V}from"../../../core/runtime/promote.js";import{recycleNode as hn}from"../../../core/runtime/recycle.js";import{relaunchRoot as wn}from"../../../core/runtime/reset.js";import{assertReopenGate as yn}from"../../../core/runtime/reopen.js";import{writeYieldMessage as _n,readGoal as gn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as bn,hasRoadmap as vn}from"../../../core/runtime/roadmap.js";import{renameWindow as kn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Sn,explicitModelIntent as Rn,normalizeModel as On,readMergedLaunchConfigAsync as ae}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as In}from"../../../core/model-routes.js";import{persistDormantModel as An,setModelLive as $n}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as le}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Cn}from"../../../core/runtime/broker-request.js";import{boundFleet as E}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Nn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Tn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ce}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as En}from"../../../core/human/action-binding.js";import{resolveHumanAction as Pn}from"../../../core/human-actions.js";import{parseDurationMs as Dn}from"../../../core/wake.js";import{claimWarmNode as Ln,refillWarmPool as fe,resumeWarmClaim as Mn,warmPoolEnabled as jn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as z,isLaunchKind as Gn,resolveLaunchTarget as Fn}from"../../../core/runtime/launch-target.js";import{fullName as Bn}from"../../../core/canvas/labels.js";import{reportsForNode as ue}from"./reports.js";import{requireUsableProfile as Kn}from"./profiles.js";import{assertProfileActive as Wn,loadExactProfileManifest as xn}from"../../../core/profiles/manifest.js";import{getCron as pe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Vn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as zn}from"../../control.js";import{notFound as P,usage as h}from"../../../core/errors.js";import{assertScope as Jn,validateScopes as me}from"../../../core/scopes.js";import{scopeAllowed as I}from"../../../shared/env.js";import{toCloseResultDTO as Un,toNodeDetailDTO as J,toNodeSummaryDTO as Yn,toReviveResultDTO as Hn}from"../map.js";import{ApiError as u}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{actsAsPerson as Qn,brokerMayReach as U,canReadNode as he,resolvedScopes as Xn}from"../router.js";import{forwardVerb as Zn,queryWithoutMachine as qn,relayError as et,unknownError as nt,withMachine as tt}from"../../peer/forward.js";import{fileRoot as ot}from"../../../core/spaces/file-root.js";import{activeGrant as rt,payerOfGrant as it,terminalGrant as dt}from"../../../core/grants/mirror.js";import{appRungForGrant as st}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as at}from"../../../core/model-routes.js";import{readConfig as lt}from"../../../core/config.js";import{hasConfiguredProviderCredential as ct,NO_PROVIDER_CREDENTIAL_MESSAGE as we}from"../../../core/runtime/provider-credential-gate.js";function w(e){const t=R(e);if(t===null)throw P(`unknown node: ${e}`,{received:e});return t}a(w,"requireMeta");function Y(e){return{subscribesTo:de(e),subscribers:We(e),children:je(e)}}a(Y,"edgesFor");function g(e){const t=w(e);return J(t,Y(e))}a(g,"detailOf");function ft(e){let t=ue(e).length;try{t+=dn(x(e),se(e)).length}catch(n){if(!on(n))throw n}return t}a(ft,"countFiles");function ut(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw h("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(t.scopes!==void 0&&me(t.scopes),t.isolated!==void 0&&typeof t.isolated!="boolean")throw new u(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(t.request_key!==void 0&&(typeof t.request_key!="string"||t.request_key.trim()===""||t.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return t}a(ut,"parseCreateBody");function pt(e){if(e===void 0)return;const t=Dn(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new u(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}a(pt,"parseDeadline");function mt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new u(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!En.test(e.action))throw new u(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>ce)throw new u(413,"payload_too_large",`serialized payload exceeds ${ce} bytes`)}return e}}a(mt,"parseOutcomeDelivery");function ht(e,t){const n=Pn(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new u(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new u(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}a(ht,"resolveOutcomeDelivery");function wt(e,t,n){const r={kind:e.kind,cwd:n,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),t!==void 0&&(r.parent=t),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=T(e.pin_cwd??e.cwd??n)),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}a(wt,"buildRecipe");function yt(e,t,n){return!jn()||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:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}a(yt,"warmRequestFor");import{resolveCreateKind as wr}from"../../../core/runtime/launch-target.js";function ye(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return In(e.model,t,e.modelExact===!0)}a(ye,"requestFromLaunch");function _t(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(r=>!I(t,r));if(n.length===0)return e;throw new u(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}a(_t,"withinCeiling");async function _e(e,t,n){const r=(await Sn(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await K(ye(r),{cwd:e.cwd,profileId:e.profile_id??null},n)}a(_e,"assertNodeModelChangeRegistered");function ge(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const r=ot({app:n.app,resolved:Xn(n),launched:n.scopes},t,"read");if("root"in r)return;const o="missing"in r?r.missing:null;throw new u(403,"scope_missing",o?`the child's directory ${t} needs missing scope ${o}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,o?{scope:o}:void 0)}a(ge,"assertCallerReaches");const H=new Map;async function gt(e,t={},n={}){const r=_t(ut(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(r.prefer_warm===!0&&c.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const i=w(r.parent);if(i.grantee!==c.app)throw new u(403,"other_app_run","cannot create a child under another app's node");if(!U(c,r.parent,i.grantee??"app:terminal"))throw P(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==c.node)throw new u(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let i=null;try{i=Me(De(r.fork_from))}catch{}if(i?.grantee!==c.app||!U(c,i.node_id,i.grantee))throw new u(403,"other_app_run","cannot fork another app's conversation")}r.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new u(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1;const i=en({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!i.allowed)throw new u(i.reason==="scope_missing"?403:401,i.reason==="scope_missing"?"scope_missing":"grant_revoked",i.message);if(r.scopes!==void 0){const l=r.scopes.find(p=>!I(i.effectiveScopes,p)||!I(c.scopes,p));if(l!==void 0)throw new u(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else c.scopes!==null&&(r.scopes=[...c.scopes]);r.node_id=ne(),c.isolated&&(r.isolated=!0,r.cwd=x(r.node_id,c.app))}r.creator!==void 0&&Jn(w(r.creator),"crtr:act");const o=r.request_key?.trim();if(o===void 0||r.node_id!==void 0&&qe(r.node_id)&&R(r.node_id)!==null&&Ge(o)?.nodeId!==r.node_id)return D(e,r,t,n);const s=H.get(o);if(s!==void 0)return s;const d=bt(e,r,o,t,n);H.set(o,d);try{return await d}finally{H.delete(o)}}a(gt,"handleCreate");async function bt(e,t,n,r,o){const s=re(n);if(s.nodeId!==null&&R(s.nodeId)!==null){if(s.state!=="warm_claimed"){const d=R(s.nodeId);if(e.principal.class!=="person"&&!he(e.principal,d.grantee??"app:terminal",s.nodeId))throw new u(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:g(s.nodeId)}}return D(e,t,r,o,s)}try{return await D(e,t,r,o,s)}catch(d){const c=re(n);throw(c.nodeId===null||R(c.nodeId)===null)&&te(n,c.nodeId),d}}a(bt,"handleKeyedCreateRequest");async function D(e,t,n,r,o=void 0){const s=r.deadlineAt??pt(t.deadline),d=mt(t.outcome_delivery),c=e.principal.class==="cron"?nn({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:pe(e.principal.cron)?.created_by??null},t.node_id):null;c!==null&&(t.root=c.root===!0);const i=c?.parent??t.parent??void 0;if(i==null&&t.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(t.output_schema!==void 0){try{l=JSON.parse(t.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 Tn(l)}const{profileId:p,kind:m,cwd:f,launch:b}=await Fn(t,{validateKind:Re});ge(e,f),t.worktree!==void 0&&ge(e,T(t.pin_cwd??t.cwd??f));const v={...t,kind:m},_=d===void 0?void 0:ht(d,f),Q=("grant"in e.principal?e.principal.grant:null)??(i==null?null:R(i)?.grant_id??null);if(await K(ye(Ee(b,Q,t.model)),{cwd:f,profileId:p},n.modelRegistry),it(Q)!=="app"&&!await ct(p))throw new u(412,"no_provider_credential",we,{error:"no_provider_credential",message:we,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let M=null;{const A=o===void 0||o.nodeId===null||o.state==="warm_claimed"?yt(v,f,p):null,j=l===null&&r.beforeBrokerLaunch===void 0?void 0:S=>{l!==null&&Nn(S,"terminal",l),r.beforeBrokerLaunch?.(S)};if(o?.state==="warm_claimed"&&o.nodeId!==null){const S=A===null?null:await Mn(A,o.nodeId,j);if(S===null)throw te(o.requestKey,o.nodeId),new u(503,"create_resume_failed",`could not resume warm claim ${o.nodeId}; retry the create`);return oe(o.requestKey,S),{status:201,body:g(S)}}if(A!==null){const S=await Ln(A,{...s===void 0?{}:{deadlineAt:s},..._===void 0?{}:{outcomeDelivery:_},...o===void 0?{}:{requestKey:o.requestKey}},j);if(S!==null)return o!==void 0&&oe(o.requestKey,S),fe(A),{status:201,body:g(S)};M=A}const G=o?.nodeId??t.node_id??(o===void 0?void 0:ne());o!==void 0&&o.nodeId===null&&Be(o.requestKey,G);const O=wt(G===void 0?v:{...v,node_id:G},i,f);c!==null&&(c.rootLifecycle!==void 0&&(O.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&v.scopes===void 0&&(O.scopes=c.scopes),c.run!==void 0&&(O.run=c.run),c.withinCreate!==void 0&&(O.withinCreate=c.withinCreate)),s!==void 0&&(O.deadlineAt=s),_!==void 0&&(O.outcomeDelivery=_),O.readiness=t.root===!0?"await":"launch";const X=await Le(O,j,()=>{M!==null&&fe(M)});return o!==void 0&&Fe(o.requestKey,X.node.node_id),{status:201,body:g(X.node.node_id)}}}a(D,"handleCreateRequest");function k(e,t){const n=e.query.getAll(t);if(n.length>1)throw h(`${t} must appear at most once`);return n[0]}a(k,"singleQueryValue");function be(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${t} must be true or false`)}}a(be,"optionalBoolean");function L(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw h(`${t} must be one of: ${n.join(", ")}`)}}a(L,"oneOf");function vt(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[b]of e.query)if(!t.has(b))throw h(`unknown nodes query parameter: ${b}`);const n=L(k(e,"status"),"status",["active","idle","done","dead","canceled"]),r=L(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),o=k(e,"kind"),s=L(k(e,"mode"),"mode",["base","orchestrator"]),d=k(e,"profile_id"),c=k(e,"profile_prefix"),i=k(e,"parent"),l=be(k(e,"top_level"),"top_level"),p=k(e,"under"),m=be(k(e,"hanging"),"hanging"),f=L(k(e,"include"),"include",["activity"]);if(i!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...r!==void 0?{lifecycle:r}:{},...o!==void 0?{kind:o}:{},...s!==void 0?{mode:s}:{},...d!==void 0?{profile_id:d}:{},...c!==void 0?{profile_prefix:c}:{},...i!==void 0?{parent:i}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{hanging:m}:{},...f!==void 0?{include:f}:{}}}a(vt,"parseListQuery");function kt(e){const t=vt(e);let n=t.status!==void 0?ie({status:t.status}):ie();if(e.principal.class!=="person"&&(n=n.filter(d=>he(e.principal,d.grantee??"app:terminal",d.node_id))),t.lifecycle!==void 0&&(n=n.filter(d=>d.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(d=>d.kind===t.kind)),t.mode!==void 0&&(n=n.filter(d=>d.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(d=>d.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(d=>d.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(d=>d.parent===t.parent)),t.top_level===!0&&(n=n.filter(d=>d.parent===null)),t.under!==void 0){const d=new Set(Ve(t.under));n=n.filter(c=>d.has(c.node_id))}t.hanging===!0&&(n=n.filter(d=>d.parent!==null&&R(d.parent)===null));const r=t.include==="activity"?Ze(n.map(d=>d.node_id)):null,o=n.length>0?Ae():new Set;return{status:200,body:n.map(d=>{const c=Yn(d,d.profile_id!==null&&o.has(d.profile_id));if(r!==null){const i=ue(d.node_id);c.activity={latest_report:i[0]??null,final_report:d.final_report===null?null:i.find(l=>l.name===d.final_report)??null,pending_human_count:r[d.node_id]??0}}return c})}}a(kt,"handleList");async function St(e){const t=e.params.id,n=await Zn(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:qn(e)});if(n.kind==="unknown")throw nt(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw et(n.status,n.body);return{status:n.status,body:tt(n.body,n.machine)}}return w(t),{status:200,body:g(t)}}a(St,"handleDetail");async function Rt(e){const t=e.params.id;w(t);const n=await ln(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.turnReplies===void 0?{}:{turnReplies:n.snapshot.turnReplies},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(o=>({name:o.name,description:o.description,source:o.source})),captured_at:B()}}}a(Rt,"handleSnapshot");async function Ot(e){const t=e.params.id,n=fn(t);if(n===null)throw P(`unknown node: ${t}`,{received:t});return{status:200,body:n}}a(Ot,"handleSubject");function It(e){for(const[s]of e.query)if(s!=="cursor"&&s!=="limit")throw h(`unknown messages query parameter: ${s}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw h("cursor must appear at most once");if(n.length>1)throw h("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const r=n[0],o=Number(r);if(!Number.isSafeInteger(o)||r==="")throw h("limit must be an integer from 1 through 500");return t.length===0?{limit:o}:{cursor:t[0],limit:o}}a(It,"parseMessagesQuery");async function At(e){const t=e.params.id,n=await sn(t,It(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:B()}}}a(At,"handleMessages");function $t(e){const t=e.params.id;w(t);const n=an(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:B()}}}a($t,"handleSession");async function Ct(e){const t=e.params.id;return w(t),{status:200,body:{node_id:t,markdown:await cn(t)}}}a(Ct,"handleTranscript");function Nt(e){const t=e.params.id;w(t);const n=a((o,s)=>({node_id:o,label:R(o)?.name??o,dir:se(o),self:s,files:ft(o)}),"root"),r=[n(t,!0),...de(t).map(o=>n(o.node_id,!1))].filter(o=>Tt(o.node_id,o.dir)||o.files>0);return{status:200,body:{node_id:t,roots:r}}}a(Nt,"handleContext");function Tt(e,t){try{return tn(x(e),t)}catch(n){if(rn(n))return!1;throw n}}a(Tt,"hasDir");async function Et(e){const t=w(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(s=>I(n,s)),...n.filter(s=>I(t.scopes,s))])],o=await Pe(t.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:g(o.node.node_id)}}a(Et,"handleFork");const Pt=1e4;async function Dt(e){const t=e.params.id;w(t);const n=e.body,r=n?.resume??!0,o=n?.reopen??!1;yn(t,o);const s=!r&&n?.cron_id!==void 0?pe(n.cron_id):null,d=await Te(t,{resume:r,capacity:"refuse",...s!==null?{wakeReason:Vn(s,"schedule_revive")}:{}});d.outcome!=="already-live"&&Ke(t,{failures:0,notBefore:null});const c=R(t)?.status??"active",i=(d.launch??E().get(t)?.handle)?.exited,l=d.outcome!=="frozen"&&await le(t,i,Pt);return{status:200,body:Hn(t,d,c,l)}}a(Dt,"handleRevive");async function Lt(e){const t=e.params.id;return{status:200,body:{newNodeId:(await wn(t))?.newNodeId??null}}}a(Lt,"handleRelaunchRoot");function Mt(e){const t=e.params.id;w(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=zn(),o=Ne(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Un(o)}}a(Mt,"handleClose");function jt(e){if(!Qn(e.principal))throw new u(403,"permission_error","only the person marks a conversation read");const t=e.params.id;return w(t),ze(t),{status:204}}a(jt,"handleMarkRead");async function Gt(e){const t=e.params.id;w(t);const n=await hn(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}a(Gt,"handleRecycle");async function Ft(e){const t=e.params.id;return w(t),await V(t,{lifecycle:"terminal"}),$(e,t,["lifecycle"]),{status:200,body:g(t)}}a(Ft,"handleDemote");async function Bt(e,t={}){const n=e.params.id,r=w(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await _e(r,{kind:o.kind??r.kind,mode:"orchestrator",lifecycle:o.resident===!0?"resident":r.lifecycle,model:o.model},t.modelRegistry);const s=await pn(n,{...o.kind!==void 0?{kind:o.kind}:{},...o.resident===!0?{resident:!0}:{},...o.model!==void 0?{model:o.model}:{}});$(e,n,["mode",...o.kind!==void 0?["kind"]:[],...o.resident===!0?["lifecycle"]:[],...o.model!==void 0?["model"]:[]]);const d=J(s.meta,Y(n));return d.roadmap_written=s.roadmapWritten,d.roadmap_ref=s.roadmapRef,d.goal_path=s.goalPath,{status:200,body:d}}a(Bt,"handlePromote");async function Kt(e,t={}){const n=e.params.id,r=w(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await _e(r,{kind:o.kind??r.kind,mode:o.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:o.model},t.modelRegistry);const s=o.note??"Refresh: continue against your roadmap or goal.";_n(n,s);const d=await mn(n,{...o.promote===!0?{promote:!0}:{},...o.kind!==void 0?{kind:o.kind}:{},...o.model!==void 0?{model:o.model}:{}});return{status:200,body:J(d.meta,Y(n))}}a(Kt,"handleYield");function Wt(e){const t=e.params.id;w(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw h("a wait requires a controller node id");const r=R(n.controller);if(r===null)throw P(`unknown controller: ${n.controller}`,{received:n.controller});if(r.status!=="active"&&r.status!=="idle")throw new u(422,"unprocessable",`controller ${n.controller} is ${r.status}`);return xe(t,n.controller),{status:200,body:g(t)}}a(Wt,"handleWait");async function xt(e){const t=e.principal,n=await un(t.class==="broker"?o=>o.grantee===t.app&&U(t,o.node_id,o.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}a(xt,"handleReviveAll");const Vt=new Set(["interrupt","steer","after-turn","next-turn"]);function zt(e){if(e===null)return null;const t=a(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 t("listen must be an object or null");const n=Object.entries(e);if(n.length===0)return t("listen must name at least one level");for(const[r,o]of n)/^(?:[1-9]|10)$/.test(r)||t(`listen level must be 1..10: ${r}`),(typeof o!="string"||!Vt.has(o))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(o)}`);return JSON.stringify(Object.fromEntries(n))}a(zt,"listenJson");function $(e,t,n,r){n.length===0&&r===void 0||W(o=>{if(r?.(o),n.length===0)return;const s=Je(o,t),d=He(o,e),c=d.class==="person"?d.person:d.class==="app"?d.app:d.node;Ue(o,c,s),Ye(o,{event:"configured",object:s,actor:c,attrs:{changed:n.join(",")}})})}a($,"recordConfigured");function ve(e){const t=E().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}a(ve,"restartLiveBroker");function ke(e,t){try{return q(e)===q(t)}catch{return!1}}a(ke,"sameDirectory");async function Jt(e,t={}){const n=e.params.id,r=e.body;let o;if(r===void 0)o={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))o=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(o.profile!==void 0){if(typeof o.profile!="string"||o.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:o.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(o).some(m=>m!=="profile"&&m!=="restart"&&o[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 i=w(n),l=Kn(e,o.profile);Wn(l.profileId);const p=xn(l.profileId).manifest.grantee??"app:terminal";if(p!==(i.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${n} to ${i.grantee}`,received:o.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(i.profile_id??null)!==l.profileId&&(Gn(i.kind)?(await z(i.kind,i.cwd,l.profileId),await V(n,{profileId:l.profileId})):C(n,{profile_id:l.profileId}),$(e,n,["profile"])),o.restart===!0&&ve(n),{status:200,body:g(n)}}if(Object.prototype.hasOwnProperty.call(o,"cwd")){const i=o.cwd;if(typeof i!="string"||i==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:i,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(o).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&o[f]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:o,field:"cwd",next:"Send cwd as the only config field."});const l=w(n),p=N(l.cwd);if(o.keep_session===!0||p&&F(i)&&N(i)&&ke(l.cwd,i)){if(!F(i))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const f=T(i);let b=!1;try{b=ee(f).isDirectory()}catch{}if(!b)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${f}`,received:i,field:"cwd",next:"Send an existing absolute directory."});if(p&&!ke(l.cwd,f))throw new y({error:"cwd_not_same_directory",message:`${f} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:i,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:`${n} owns an open managed worktree and cannot relocate its cwd`,received:i,field:"cwd",next:"Reconcile the managed worktree first."});const v=l.cwd;return v!==f&&(W(_=>{C(n,{cwd:f}),Z(_,"UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,v),Qe(n,v,f)}),$(e,n,["cwd"])),o.restart===!0&&ve(n),{status:200,body:g(n)}}if(E().has(n)){const f=`${n} cannot repair its cwd while its broker is live`;throw new u(409,"cwd_node_live",f,{error:"cwd_node_live",message:f,received:i,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:`${n} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:i,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:`${n} owns an open managed worktree and cannot repair its cwd`,received:i,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:`${n} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:i,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(i))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const m=T(i);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ee(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:i,field:"cwd",next:"Send an existing absolute directory."})}catch(f){throw f instanceof y?f:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return W(()=>{C(n,{cwd:m}),Xe(n)}),$(e,n,["cwd"]),{status:200,body:g(n)}}let s=w(n);const d=o.listen===void 0?void 0:zt(o.listen);if(o.scopes!==void 0){const i=me(o.scopes),l=s.grantee==="app:terminal"?dt():s.grant_id?rt(s.grant_id):null,p=s.grantee==="app:terminal"&&!lt("user").runtime?.issuer;if(!i.every(m=>I(s.scopes,m)&&(l?I(l.resolved,m):p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:i,field:"scopes",next:"Send only scopes the node currently holds."});if(i.includes("crtr:act")&&!I(i,"crtr:llm"))throw new u(400,"invalid_scope","crtr:act requires crtr:llm");s=C(n,{scopes:i})}if(o.situational_context!==void 0&&$e(n,Ce(o.situational_context)),o.model!==void 0){const i=(await ae(s.cwd,s.profile_id??null)).modelLadders,l=Rn(o.model,i),p=st(s.grant_id,o.model,l===void 0),m=p?{family:at,strength:p.strength}:l,f=p?p.model:On(o.model,i);await K({kind:"concrete",spec:f},{cwd:s.cwd,profileId:s.profile_id??null},t.modelRegistry);const b=E();let v=!1;if(b.isClaimed(n)&&await le(n,b.get(n)?.handle.exited)&&(v=await $n(n,f,m).then(()=>!0,_=>{if(_ instanceof Cn)return!1;throw _})),!v){if(b.isClaimed(n)){const _=`${n}'s broker did not accept the model switch; the model was not changed`;throw new u(409,"broker_not_ready",_,{error:"broker_not_ready",message:_,received:o.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!f.includes("/"))throw h(`model must resolve to a provider/id spec: ${o.model}`);An(n,f,m)}s=w(n)}if(o.kind!==void 0||o.mode!==void 0||o.lifecycle!==void 0){o.kind!==void 0&&await Re(o.kind);const i=o.kind??s.kind,l=o.mode??s.mode,p=o.lifecycle??s.lifecycle;let m;l==="orchestrator"&&!vn(n)&&(m=a(()=>{const f=gn(n);bn(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),s=await V(n,{...o.kind!==void 0?{kind:i}:{},...o.mode!==void 0?{mode:l}:{},...o.lifecycle!==void 0?{lifecycle:p}:{}},m)}o.name!==void 0&&(s=C(n,{name:o.name}),s.window&&kn(s.window,Bn(s)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(i=>o[i]!==void 0);return $(e,n,c,d===void 0?void 0:i=>{Z(i,"UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(d,n)}),{status:200,body:g(n)}}a(Jt,"handleConfig");async function Se(){return(await ae(process.cwd(),Ie()||null)).kinds}a(Se,"daemonKinds");async function Re(e){const t=Object.keys(await Se());if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}a(Re,"assertKindServer");async function Ut(){const e=await Se();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}a(Ut,"handleListKinds");const pr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:gt},{method:"GET",pattern:"/v1/nodes",handler:kt},{method:"GET",pattern:"/v1/kinds",handler:a(()=>Ut(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:xt},{method:"GET",pattern:"/v1/nodes/:id",handler:St},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Rt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Ot},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:At},{method:"GET",pattern:"/v1/nodes/:id/session",handler:$t},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Ct},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Nt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Et},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Dt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Lt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Mt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:jt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Gt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ft},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Kt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Wt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Jt}];export{Jt as handleConfig,gt as handleCreate,Et as handleFork,kt as handleList,Bt as handlePromote,Kt as handleYield,pr as nodeRoutes,wr as resolveCreateKind};
|
|
1
|
+
var Oe=Object.defineProperty;var a=(e,t)=>Oe(e,"name",{value:t,configurable:!0});import{prepared as Z}from"../../../core/sqlite-statements.js";import{envProfileId as Ie}from"../../../shared/env.js";import{pausedCanvasProfiles as Ae}from"../../../core/profiles/manifest.js";import{existsSync as N,realpathSync as q,statSync as ee}from"node:fs";import{isAbsolute as F,resolve as T}from"node:path";import{appendSituationalContext as $e,formatSituationalProse as Ce}from"../../../core/runtime/situational-context.js";import{closeNode as Ne}from"../../../core/runtime/close.js";import{reviveNode as Te}from"../../../core/runtime/revive.js";import{nowIso as B}from"../../../core/fs-utils.js";import{appPaidLaunch as Ee,assertLaunchModelRegistered as K,forkNode as Pe,resolveForkSource as De,spawnChildPrepared as Le}from"../../../core/runtime/spawn.js";import{forkSourceNode as Me,newNodeId as ne}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as te,childrenOf as je,completeCreateRequest as oe,findCreateRequest as Ge,getNode as R,recordCreateRequestNode as Fe,reserveCreateRequest as re,reserveCreateRequestNode as Be,listNodes as ie,recordRespawnAttempt as Ke,subscribersOf as We,subscriptionsOf as de,updateNode as C}from"../../../core/canvas/canvas.js";import{armControllerWait as xe}from"../../../core/canvas/waits.js";import{subtreeIds as Ve}from"../../../core/canvas/nav-model.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 se,nodeAgentDir as x}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as en}from"../../cron/authority.js";import{cronBirthPlacement as nn}from"../../cron/armed-context.js";import{existsBeneath as tn,isAbsentOrRefused as on,isBeneathRefusal as rn,readdirBeneath as dn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as sn,readNodeSession as an,readNodeSnapshot as ln,transcriptMarkdown as cn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as fn}from"../../../core/substrate/subject.js";import{reviveAll as un}from"../../../core/runtime/revive-all.js";import{promoteAsync as pn,requestYieldAsync as mn,reshapeNodeAsync as V}from"../../../core/runtime/promote.js";import{recycleNode as hn}from"../../../core/runtime/recycle.js";import{relaunchRoot as wn}from"../../../core/runtime/reset.js";import{assertReopenGate as yn}from"../../../core/runtime/reopen.js";import{writeYieldMessage as _n,readGoal as gn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as bn,hasRoadmap as vn}from"../../../core/runtime/roadmap.js";import{renameWindow as kn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Sn,explicitModelIntent as Rn,normalizeModel as On,readMergedLaunchConfigAsync as ae}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as In}from"../../../core/model-routes.js";import{persistDormantModel as An,setModelLive as $n}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as le}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Cn}from"../../../core/runtime/broker-request.js";import{boundFleet as E}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Nn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Tn}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as ce}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as En}from"../../../core/human/action-binding.js";import{resolveHumanAction as Pn}from"../../../core/human-actions.js";import{parseDurationMs as Dn}from"../../../core/wake.js";import{claimWarmNode as Ln,refillWarmPool as fe,resumeWarmClaim as Mn,warmPoolEnabled as jn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as z,isLaunchKind as Gn,resolveLaunchTarget as Fn}from"../../../core/runtime/launch-target.js";import{fullName as Bn}from"../../../core/canvas/labels.js";import{reportsForNode as ue}from"./reports.js";import{requireUsableProfile as Kn}from"./profiles.js";import{assertProfileActive as Wn,loadExactProfileManifest as xn}from"../../../core/profiles/manifest.js";import{getCron as pe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Vn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as zn}from"../../control.js";import{notFound as P,usage as h}from"../../../core/errors.js";import{assertScope as Jn,validateScopes as me}from"../../../core/scopes.js";import{scopeAllowed as I}from"../../../shared/env.js";import{toCloseResultDTO as Un,toNodeDetailDTO as J,toNodeSummaryDTO as Yn,toReviveResultDTO as Hn}from"../map.js";import{ApiError as u}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{actsAsPerson as Qn,brokerMayReach as U,canReadNode as he,resolvedScopes as Xn}from"../router.js";import{forwardVerb as Zn,queryWithoutMachine as qn,relayError as et,unknownError as nt,withMachine as tt}from"../../peer/forward.js";import{fileRoot as ot}from"../../../core/spaces/file-root.js";import{activeGrant as rt,payerOfGrant as it,terminalGrant as dt}from"../../../core/grants/mirror.js";import{appRungForGrant as st}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as at}from"../../../core/model-routes.js";import{readConfig as lt}from"../../../core/config.js";import{hasConfiguredProviderCredential as ct,NO_PROVIDER_CREDENTIAL_MESSAGE as we}from"../../../core/runtime/provider-credential-gate.js";function w(e){const t=R(e);if(t===null)throw P(`unknown node: ${e}`,{received:e});return t}a(w,"requireMeta");function Y(e){return{subscribesTo:de(e),subscribers:We(e),children:je(e)}}a(Y,"edgesFor");function g(e){const t=w(e);return J(t,Y(e))}a(g,"detailOf");function ft(e){let t=ue(e).length;try{t+=dn(x(e),se(e)).length}catch(n){if(!on(n))throw n}return t}a(ft,"countFiles");function ut(e){if(typeof e!="object"||e===null)throw h("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw h("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw h("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw h("creator must be a non-empty node id when provided");if(t.scopes!==void 0&&me(t.scopes),t.isolated!==void 0&&typeof t.isolated!="boolean")throw new u(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw h("root_lifecycle must be 'resident' or 'terminal'");if(t.request_key!==void 0&&(typeof t.request_key!="string"||t.request_key.trim()===""||t.request_key.length>128))throw h("request_key must be a non-empty string of at most 128 characters when provided");return t}a(ut,"parseCreateBody");function pt(e){if(e===void 0)return;const t=Dn(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new u(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}a(pt,"parseDeadline");function mt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new u(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!En.test(e.action))throw new u(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new u(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>ce)throw new u(413,"payload_too_large",`serialized payload exceeds ${ce} bytes`)}return e}}a(mt,"parseOutcomeDelivery");function ht(e,t){const n=Pn(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new u(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new u(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}a(ht,"resolveOutcomeDelivery");function wt(e,t,n){const r={kind:e.kind,cwd:n,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),t!==void 0&&(r.parent=t),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=T(e.pin_cwd??e.cwd??n)),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}a(wt,"buildRecipe");function yt(e,t,n){return!jn()||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:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}a(yt,"warmRequestFor");import{resolveCreateKind as yr}from"../../../core/runtime/launch-target.js";function ye(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return In(e.model,t,e.modelExact===!0)}a(ye,"requestFromLaunch");function _t(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(r=>!I(t,r));if(n.length===0)return e;throw new u(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}a(_t,"withinCeiling");async function _e(e,t,n){const r=(await Sn(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await K(ye(r),{cwd:e.cwd,profileId:e.profile_id??null},n)}a(_e,"assertNodeModelChangeRegistered");function ge(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const r=ot({app:n.app,resolved:Xn(n),launched:n.scopes},t,"read");if("root"in r)return;const o="missing"in r?r.missing:null;throw new u(403,"scope_missing",o?`the child's directory ${t} needs missing scope ${o}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,o?{scope:o}:void 0)}a(ge,"assertCallerReaches");const H=new Map;async function gt(e,t={},n={}){const r=_t(ut(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(r.prefer_warm===!0&&c.app!=="app:terminal"&&(r.prefer_warm=!1),r.parent!=null){const i=w(r.parent);if(i.grantee!==c.app)throw new u(403,"other_app_run","cannot create a child under another app's node");if(!U(c,r.parent,i.grantee??"app:terminal"))throw P(`unknown node: ${r.parent}`,{received:r.parent})}if(r.creator!==void 0&&r.creator!==c.node)throw new u(403,"other_app_run","cannot create for another node");if(r.fork_from!==void 0){let i=null;try{i=Me(De(r.fork_from))}catch{}if(i?.grantee!==c.app||!U(c,i.node_id,i.grantee))throw new u(403,"other_app_run","cannot fork another app's conversation")}r.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(r[l]!=null)throw new u(403,"permission_error",`a cron cannot set ${l} on a node it starts`);r.prefer_warm=!1;const i=en({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!i.allowed)throw new u(i.reason==="scope_missing"?403:401,i.reason==="scope_missing"?"scope_missing":"grant_revoked",i.message);if(r.scopes!==void 0){const l=r.scopes.find(p=>!I(i.effectiveScopes,p)||!I(c.scopes,p));if(l!==void 0)throw new u(403,"scope_missing",`scope ${l} is not held by this cron`,void 0,void 0,{scope:l})}else c.scopes!==null&&(r.scopes=[...c.scopes]);r.node_id=ne(),c.isolated&&(r.isolated=!0,r.cwd=x(r.node_id,c.app))}r.creator!==void 0&&Jn(w(r.creator),"crtr:act");const o=r.request_key?.trim();if(o===void 0||r.node_id!==void 0&&qe(r.node_id)&&R(r.node_id)!==null&&Ge(o)?.nodeId!==r.node_id)return D(e,r,t,n);const s=H.get(o);if(s!==void 0)return s;const d=bt(e,r,o,t,n);H.set(o,d);try{return await d}finally{H.delete(o)}}a(gt,"handleCreate");async function bt(e,t,n,r,o){const s=re(n);if(s.nodeId!==null&&R(s.nodeId)!==null){if(s.state!=="warm_claimed"){const d=R(s.nodeId);if(e.principal.class!=="person"&&!he(e.principal,d.grantee??"app:terminal",s.nodeId))throw new u(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:g(s.nodeId)}}return D(e,t,r,o,s)}try{return await D(e,t,r,o,s)}catch(d){const c=re(n);throw(c.nodeId===null||R(c.nodeId)===null)&&te(n,c.nodeId),d}}a(bt,"handleKeyedCreateRequest");async function D(e,t,n,r,o=void 0){const s=r.deadlineAt??pt(t.deadline),d=mt(t.outcome_delivery),c=e.principal.class==="cron"?nn({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:pe(e.principal.cron)?.created_by??null},t.node_id):null;c!==null&&(t.root=c.root===!0);const i=c?.parent??t.parent??void 0;if(i==null&&t.root!==!0)throw h("a node create requires a parent (or root: true for an independent root)");let l=null;if(t.output_schema!==void 0){try{l=JSON.parse(t.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 Tn(l)}const{profileId:p,kind:m,cwd:f,launch:b}=await Fn(t,{validateKind:Re});ge(e,f),t.worktree!==void 0&&ge(e,T(t.pin_cwd??t.cwd??f));const v={...t,kind:m},_=d===void 0?void 0:ht(d,f),Q=("grant"in e.principal?e.principal.grant:null)??(i==null?null:R(i)?.grant_id??null);if(await K(ye(Ee(b,Q,t.model)),{cwd:f,profileId:p},n.modelRegistry),it(Q)!=="app"&&!await ct(p))throw new u(412,"no_provider_credential",we,{error:"no_provider_credential",message:we,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let M=null;{const A=o===void 0||o.nodeId===null||o.state==="warm_claimed"?yt(v,f,p):null,j=l===null&&r.beforeBrokerLaunch===void 0?void 0:S=>{l!==null&&Nn(S,"terminal",l),r.beforeBrokerLaunch?.(S)};if(o?.state==="warm_claimed"&&o.nodeId!==null){const S=A===null?null:await Mn(A,o.nodeId,j);if(S===null)throw te(o.requestKey,o.nodeId),new u(503,"create_resume_failed",`could not resume warm claim ${o.nodeId}; retry the create`);return oe(o.requestKey,S),{status:201,body:g(S)}}if(A!==null){const S=await Ln(A,{...s===void 0?{}:{deadlineAt:s},..._===void 0?{}:{outcomeDelivery:_},...o===void 0?{}:{requestKey:o.requestKey}},j);if(S!==null)return o!==void 0&&oe(o.requestKey,S),fe(A),{status:201,body:g(S)};M=A}const G=o?.nodeId??t.node_id??(o===void 0?void 0:ne());o!==void 0&&o.nodeId===null&&Be(o.requestKey,G);const O=wt(G===void 0?v:{...v,node_id:G},i,f);c!==null&&(c.rootLifecycle!==void 0&&(O.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&v.scopes===void 0&&(O.scopes=c.scopes),c.run!==void 0&&(O.run=c.run),c.withinCreate!==void 0&&(O.withinCreate=c.withinCreate)),s!==void 0&&(O.deadlineAt=s),_!==void 0&&(O.outcomeDelivery=_),O.readiness=t.root===!0?"await":"launch";const X=await Le(O,j,()=>{M!==null&&fe(M)});return o!==void 0&&Fe(o.requestKey,X.node.node_id),{status:201,body:g(X.node.node_id)}}}a(D,"handleCreateRequest");function k(e,t){const n=e.query.getAll(t);if(n.length>1)throw h(`${t} must appear at most once`);return n[0]}a(k,"singleQueryValue");function be(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw h(`${t} must be true or false`)}}a(be,"optionalBoolean");function L(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw h(`${t} must be one of: ${n.join(", ")}`)}}a(L,"oneOf");function vt(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[b]of e.query)if(!t.has(b))throw h(`unknown nodes query parameter: ${b}`);const n=L(k(e,"status"),"status",["active","idle","done","dead","canceled"]),r=L(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),o=k(e,"kind"),s=L(k(e,"mode"),"mode",["base","orchestrator"]),d=k(e,"profile_id"),c=k(e,"profile_prefix"),i=k(e,"parent"),l=be(k(e,"top_level"),"top_level"),p=k(e,"under"),m=be(k(e,"hanging"),"hanging"),f=L(k(e,"include"),"include",["activity"]);if(i!==void 0&&l===!0)throw h("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...r!==void 0?{lifecycle:r}:{},...o!==void 0?{kind:o}:{},...s!==void 0?{mode:s}:{},...d!==void 0?{profile_id:d}:{},...c!==void 0?{profile_prefix:c}:{},...i!==void 0?{parent:i}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{hanging:m}:{},...f!==void 0?{include:f}:{}}}a(vt,"parseListQuery");function kt(e){const t=vt(e);let n=t.status!==void 0?ie({status:t.status}):ie();if(e.principal.class!=="person"&&(n=n.filter(d=>he(e.principal,d.grantee??"app:terminal",d.node_id))),t.lifecycle!==void 0&&(n=n.filter(d=>d.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(d=>d.kind===t.kind)),t.mode!==void 0&&(n=n.filter(d=>d.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(d=>d.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(d=>d.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(d=>d.parent===t.parent)),t.top_level===!0&&(n=n.filter(d=>d.parent===null)),t.under!==void 0){const d=new Set(Ve(t.under));n=n.filter(c=>d.has(c.node_id))}t.hanging===!0&&(n=n.filter(d=>d.parent!==null&&R(d.parent)===null));const r=t.include==="activity"?Ze(n.map(d=>d.node_id)):null,o=n.length>0?Ae():new Set;return{status:200,body:n.map(d=>{const c=Yn(d,d.profile_id!==null&&o.has(d.profile_id));if(r!==null){const i=ue(d.node_id);c.activity={latest_report:i[0]??null,final_report:d.final_report===null?null:i.find(l=>l.name===d.final_report)??null,pending_human_count:r[d.node_id]??0}}return c})}}a(kt,"handleList");async function St(e){const t=e.params.id,n=await Zn(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:qn(e)});if(n.kind==="unknown")throw nt(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw et(n.status,n.body);return{status:n.status,body:tt(n.body,n.machine)}}return w(t),{status:200,body:g(t)}}a(St,"handleDetail");async function Rt(e){const t=e.params.id;w(t);const n=await ln(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.turnReplies===void 0?{}:{turnReplies:n.snapshot.turnReplies},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(o=>({name:o.name,description:o.description,source:o.source})),captured_at:B()}}}a(Rt,"handleSnapshot");async function Ot(e){const t=e.params.id,n=fn(t);if(n===null)throw P(`unknown node: ${t}`,{received:t});return{status:200,body:n}}a(Ot,"handleSubject");function It(e){for(const[s]of e.query)if(s!=="cursor"&&s!=="limit")throw h(`unknown messages query parameter: ${s}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw h("cursor must appear at most once");if(n.length>1)throw h("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const r=n[0],o=Number(r);if(!Number.isSafeInteger(o)||r==="")throw h("limit must be an integer from 1 through 500");return t.length===0?{limit:o}:{cursor:t[0],limit:o}}a(It,"parseMessagesQuery");async function At(e){const t=e.params.id,n=await sn(t,It(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:B()}}}a(At,"handleMessages");function $t(e){const t=e.params.id;w(t);const n=an(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:B()}}}a($t,"handleSession");async function Ct(e){const t=e.params.id;return w(t),{status:200,body:{node_id:t,markdown:await cn(t)}}}a(Ct,"handleTranscript");function Nt(e){const t=e.params.id;w(t);const n=a((o,s)=>({node_id:o,label:R(o)?.name??o,dir:se(o),self:s,files:ft(o)}),"root"),r=[n(t,!0),...de(t).map(o=>n(o.node_id,!1))].filter(o=>Tt(o.node_id,o.dir)||o.files>0);return{status:200,body:{node_id:t,roots:r}}}a(Nt,"handleContext");function Tt(e,t){try{return tn(x(e),t)}catch(n){if(rn(n))return!1;throw n}}a(Tt,"hasDir");async function Et(e){const t=w(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,r=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(s=>I(n,s)),...n.filter(s=>I(t.scopes,s))])],o=await Pe(t.node_id,r,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:g(o.node.node_id)}}a(Et,"handleFork");const Pt=1e4;async function Dt(e){const t=e.params.id;w(t);const n=e.body,r=n?.resume??!0,o=n?.reopen??!1;yn(t,o);const s=!r&&n?.cron_id!==void 0?pe(n.cron_id):null,d=await Te(t,{resume:r,capacity:"refuse",...s!==null?{wakeReason:Vn(s,"schedule_revive")}:{}});d.outcome!=="already-live"&&Ke(t,{failures:0,notBefore:null});const c=R(t)?.status??"active",i=(d.launch??E().get(t)?.handle)?.exited,l=d.outcome!=="frozen"&&await le(t,i,Pt);return{status:200,body:Hn(t,d,c,l)}}a(Dt,"handleRevive");async function Lt(e){const t=e.params.id;return{status:200,body:{newNodeId:(await wn(t))?.newNodeId??null}}}a(Lt,"handleRelaunchRoot");function Mt(e){const t=e.params.id;w(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw h("caller_pid must be a positive integer when provided");const r=zn(),o=Ne(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...r===null?{}:{registerDetached:r.registerDetached}});return{status:200,body:Un(o)}}a(Mt,"handleClose");function jt(e){if(!Qn(e.principal))throw new u(403,"permission_error","only the person marks a conversation read");const t=e.params.id;return w(t),ze(t),{status:204}}a(jt,"handleMarkRead");async function Gt(e){const t=e.params.id;w(t);const n=await hn(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}a(Gt,"handleRecycle");async function Ft(e){const t=e.params.id;return w(t),await V(t,{lifecycle:"terminal"}),$(e,t,["lifecycle"]),{status:200,body:g(t)}}a(Ft,"handleDemote");async function Bt(e,t={}){const n=e.params.id,r=w(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await _e(r,{kind:o.kind??r.kind,mode:"orchestrator",lifecycle:o.resident===!0?"resident":r.lifecycle,model:o.model},t.modelRegistry);const s=await pn(n,{...o.kind!==void 0?{kind:o.kind}:{},...o.resident===!0?{resident:!0}:{},...o.model!==void 0?{model:o.model}:{}});$(e,n,["mode",...o.kind!==void 0?["kind"]:[],...o.resident===!0?["lifecycle"]:[],...o.model!==void 0?["model"]:[]]);const d=J(s.meta,Y(n));return d.roadmap_written=s.roadmapWritten,d.roadmap_ref=s.roadmapRef,d.goal_path=s.goalPath,{status:200,body:d}}a(Bt,"handlePromote");async function Kt(e,t={}){const n=e.params.id,r=w(n),o=e.body??{};o.kind!==void 0&&await z(o.kind,r.cwd,r.profile_id??null),o.model!==void 0&&await _e(r,{kind:o.kind??r.kind,mode:o.promote===!0?"orchestrator":r.mode,lifecycle:r.lifecycle,model:o.model},t.modelRegistry);const s=o.note??"Refresh: continue against your roadmap or goal.";_n(n,s);const d=await mn(n,{...o.promote===!0?{promote:!0}:{},...o.kind!==void 0?{kind:o.kind}:{},...o.model!==void 0?{model:o.model}:{}});return{status:200,body:J(d.meta,Y(n))}}a(Kt,"handleYield");function Wt(e){const t=e.params.id;w(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw h("a wait requires a controller node id");const r=R(n.controller);if(r===null)throw P(`unknown controller: ${n.controller}`,{received:n.controller});if(r.status!=="active"&&r.status!=="idle")throw new u(422,"unprocessable",`controller ${n.controller} is ${r.status}`);return xe(t,n.controller),{status:200,body:g(t)}}a(Wt,"handleWait");async function xt(e){const t=e.principal,n=await un(t.class==="broker"?o=>o.grantee===t.app&&U(t,o.node_id,o.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}a(xt,"handleReviveAll");const Vt=new Set(["interrupt","steer","after-turn","next-turn"]);function zt(e){if(e===null)return null;const t=a(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 t("listen must be an object or null");const n=Object.entries(e);if(n.length===0)return t("listen must name at least one level");for(const[r,o]of n)/^(?:[1-9]|10)$/.test(r)||t(`listen level must be 1..10: ${r}`),(typeof o!="string"||!Vt.has(o))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(o)}`);return JSON.stringify(Object.fromEntries(n))}a(zt,"listenJson");function $(e,t,n,r){n.length===0&&r===void 0||W(o=>{if(r?.(o),n.length===0)return;const s=Je(o,t),d=He(o,e),c=d.class==="person"?d.person:d.class==="app"?d.app:d.node;Ue(o,c,s),Ye(o,{event:"configured",object:s,actor:c,attrs:{changed:n.join(",")}})})}a($,"recordConfigured");function ve(e){const t=E().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}a(ve,"restartLiveBroker");function ke(e,t){try{return q(e)===q(t)}catch{return!1}}a(ke,"sameDirectory");async function Jt(e,t={}){const n=e.params.id,r=e.body;let o;if(r===void 0)o={};else if(typeof r=="object"&&r!==null&&!Array.isArray(r))o=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(o.profile!==void 0){if(typeof o.profile!="string"||o.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:o.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(o).some(m=>m!=="profile"&&m!=="restart"&&o[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 i=w(n),l=Kn(e,o.profile);Wn(l.profileId);const p=xn(l.profileId).manifest.grantee??"app:terminal";if(p!==(i.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${n} to ${i.grantee}`,received:o.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(i.profile_id??null)!==l.profileId&&(Gn(i.kind)?(await z(i.kind,i.cwd,l.profileId),await V(n,{profileId:l.profileId})):C(n,{profile_id:l.profileId}),$(e,n,["profile"])),o.restart===!0&&ve(n),{status:200,body:g(n)}}if(Object.prototype.hasOwnProperty.call(o,"cwd")){const i=o.cwd;if(typeof i!="string"||i==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:i,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(o).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&o[f]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:o,field:"cwd",next:"Send cwd as the only config field."});const l=w(n),p=N(l.cwd);if(o.keep_session===!0||p&&F(i)&&N(i)&&ke(l.cwd,i)){if(!F(i))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const f=T(i);let b=!1;try{b=ee(f).isDirectory()}catch{}if(!b)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${f}`,received:i,field:"cwd",next:"Send an existing absolute directory."});if(p&&!ke(l.cwd,f))throw new y({error:"cwd_not_same_directory",message:`${f} is not the same directory as the recorded ${l.cwd}; --keep-session only relocates an alias`,received:i,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:`${n} owns an open managed worktree and cannot relocate its cwd`,received:i,field:"cwd",next:"Reconcile the managed worktree first."});const v=l.cwd;return v!==f&&(W(_=>{C(n,{cwd:f}),Z(_,"UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,v),Qe(n,v,f)}),$(e,n,["cwd"])),o.restart===!0&&ve(n),{status:200,body:g(n)}}if(E().has(n)){const f=`${n} cannot repair its cwd while its broker is live`;throw new u(409,"cwd_node_live",f,{error:"cwd_node_live",message:f,received:i,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:`${n} is a fork and cannot repair its cwd; recorded cwd: ${l.cwd}`,received:i,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:`${n} owns an open managed worktree and cannot repair its cwd`,received:i,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:`${n} recorded cwd still exists: ${l.cwd}; cwd repair is not a relocation command`,received:i,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(i))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${i}`,received:i,field:"cwd",next:"Send an absolute path."});const m=T(i);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ee(m).isDirectory())throw new y({error:"cwd_not_a_directory",message:`cwd is not a directory: ${m}`,received:i,field:"cwd",next:"Send an existing absolute directory."})}catch(f){throw f instanceof y?f:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:i,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return W(()=>{C(n,{cwd:m}),Xe(n)}),$(e,n,["cwd"]),{status:200,body:g(n)}}let s=w(n);const d=o.listen===void 0?void 0:zt(o.listen);if(o.scopes!==void 0){const i=me(o.scopes),l=s.grantee==="app:terminal"?dt():s.grant_id?rt(s.grant_id):null,p=s.grantee==="app:terminal"&&!lt("user").runtime?.issuer;if(!i.every(m=>I(s.scopes,m)&&(l?I(l.resolved,m):p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:i,field:"scopes",next:"Send only scopes the node currently holds."});if(i.includes("crtr:act")&&!I(i,"crtr:llm"))throw new u(400,"invalid_scope","crtr:act requires crtr:llm");s=C(n,{scopes:i})}if(o.situational_context!==void 0&&$e(n,Ce(o.situational_context)),o.model!==void 0){const i=(await ae(s.cwd,s.profile_id??null)).modelLadders,l=Rn(o.model,i),p=st(s.grant_id,o.model,l===void 0),m=p?{family:at,strength:p.strength}:l,f=p?p.model:On(o.model,i);await K({kind:"concrete",spec:f},{cwd:s.cwd,profileId:s.profile_id??null},t.modelRegistry);const b=E();let v=!1;if(b.isClaimed(n)&&await le(n,b.get(n)?.handle.exited)&&(v=await $n(n,f,m).then(()=>!0,_=>{if(_ instanceof Cn)return!1;throw _})),!v){if(b.isClaimed(n)){const _=`${n}'s broker did not accept the model switch; the model was not changed`;throw new u(409,"broker_not_ready",_,{error:"broker_not_ready",message:_,received:o.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!f.includes("/"))throw h(`model must resolve to a provider/id spec: ${o.model}`);An(n,f,m)}s=w(n)}if(o.kind!==void 0||o.mode!==void 0||o.lifecycle!==void 0){o.kind!==void 0&&await Re(o.kind);const i=o.kind??s.kind,l=o.mode??s.mode,p=o.lifecycle??s.lifecycle;let m;l==="orchestrator"&&!vn(n)&&(m=a(()=>{const f=gn(n);bn(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),s=await V(n,{...o.kind!==void 0?{kind:i}:{},...o.mode!==void 0?{mode:l}:{},...o.lifecycle!==void 0?{lifecycle:p}:{}},m)}o.name!==void 0&&(s=C(n,{name:o.name}),s.window&&kn(s.window,Bn(s)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(i=>o[i]!==void 0);return $(e,n,c,d===void 0?void 0:i=>{Z(i,"UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(d,n)}),{status:200,body:g(n)}}a(Jt,"handleConfig");async function Se(){return(await ae(process.cwd(),Ie()||null)).kinds}a(Se,"daemonKinds");async function Re(e){const t=Object.keys(await Se());if(!t.includes(e))throw h(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}a(Re,"assertKindServer");async function Ut(){const e=await Se();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}a(Ut,"handleListKinds");const mr=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:gt},{method:"GET",pattern:"/v1/nodes",handler:kt},{method:"GET",pattern:"/v1/kinds",handler:a(()=>Ut(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:xt},{method:"GET",pattern:"/v1/nodes/:id",handler:St},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Rt},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:Ot},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:At},{method:"GET",pattern:"/v1/nodes/:id/session",handler:$t},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Ct},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Nt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Et},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Dt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Lt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Mt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:jt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Gt},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Ft},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Kt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Wt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Jt}];export{Jt as handleConfig,gt as handleCreate,Et as handleFork,kt as handleList,Bt as handlePromote,Kt as handleYield,mr as nodeRoutes,yr as resolveCreateKind};
|