@north-light/cli 0.3.534 → 0.3.535
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/dto/nodes.d.ts +2 -0
- package/dist/builtin-memory/crouter-sdk/release-notes.md +1 -1
- package/dist/clients/attach/viewer.js +2 -2
- package/dist/commands/api-client.d.ts +1 -0
- package/dist/commands/api-client.js +1 -1
- package/dist/commands/node/inspect.js +9 -9
- package/dist/core/bash-jobs.d.ts +4 -0
- package/dist/core/bash-jobs.js +8 -8
- package/dist/core/canvas/canvas.d.ts +16 -2
- package/dist/core/canvas/canvas.js +20 -20
- package/dist/core/canvas/recovery.js +1 -1
- package/dist/core/canvas/remote-canvas-source.d.ts +1 -0
- package/dist/core/canvas/remote-canvas-source.js +1 -1
- package/dist/core/canvas/source.d.ts +4 -0
- package/dist/core/canvas/source.js +1 -1
- package/dist/core/canvas/tree.d.ts +2 -0
- package/dist/core/canvas/tree.js +12 -5
- package/dist/core/graph/watches.d.ts +0 -2
- package/dist/core/graph/watches.js +7 -12
- package/dist/core/runtime/broker/fault-retry.d.ts +6 -0
- package/dist/core/runtime/broker/fault-retry.js +1 -1
- package/dist/core/runtime/launch.js +2 -2
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/dist/daemon/reconcilers/bash-deadline.d.ts +6 -0
- package/dist/daemon/reconcilers/bash-deadline.js +3 -2
- package/dist/daemon/runs/observer.d.ts +2 -0
- package/dist/daemon/runs/observer.js +2 -2
- package/docs/sdk/release-notes.md +1 -1
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +12 -12
- package/dist/core/canvas/nav-model.d.ts +0 -44
- package/dist/core/canvas/nav-model.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
var ae=Object.defineProperty;var h=(r,e)=>ae(r,"name",{value:e,configurable:!0});import{envModelIntent as N,envNodeCwd as G,envProfileId as U}from"../../../shared/env.js";import{isContextOverflow as Y}from"@earendil-works/pi-ai";import{classify as B}from"../../fault-classifier.js";import{isDaemonTransportApiError as de}from"../../../api/errors.js";import{isModelNotFoundError as le,isProviderUnconfiguredError as ce}from"../fault.js";import{brokerRecovery as ue,mutateBrokerFault as W,mutateBrokerProviderRetry as _}from"./daemon-ops.js";import{extractCoolingDeadline as pe}from"../managed-provider-cooling.js";import{extractProviderFailureDetails as fe}from"../../provider-failure.js";import{expandModelCandidates as q,modelRequestFromConfig as V,probeRouteAvailability as he}from"../../model-routes.js";import{operationIdContext as j}from"../../events/operation-id.js";import{emitEvent as w}from"../../events/emit.js";import{CONNECTION_FAULT_RECOVERY_BODY as me,PROVIDER_FAULT_RECOVERY_BODY as ge,RUN_CONNECTION_FAULT_RETRY_BODY as ye,formatCard as X,formatModelFallbackRecovery as ve}from"../../../shared/generated-context.js";import{markFatalOnExhaust as J,nextFaultRetry as z,policyFor as H}from"../fault-recovery.js";import{parseModelSpec as K}from"../model-selection.js";import{endedByAbort as Q}from"../session-cycles.js";import{resolveProviderCandidates as Fe}from"../../subscription-state.js";import{announceMessageOrigin as Z}from"../stamp/channel.js";import{LLM_REFUSAL_DIAGNOSTIC as we,refusalRetryAt as ke}from"./model-adapter.js";import{isSafetyRefusal as ee}from"../../llm/refusal.js";const be=2147483647,te=3e4;function _e(r,e,t){const n=Date.parse(r);return!Number.isFinite(n)||t+e-n>te}h(_e,"runTurnRetryExpired");class ne extends Error{static{h(this,"StaleOutcome")}}const Ee=1e3,Ie=3e4;function Re(r,e){return r!=="connection"?ge:e?ye:me}h(Re,"retryCardBody");function E(r){return{link:r.link,op:r.op,kind:r.kind,retry:r.retry,message:r.message,since:r.since,operation_id:r.operation_id,...r.anchor_entry_id===void 0?{}:{anchorEntryId:r.anchor_entry_id},...r.provider_error===void 0?{}:{providerError:r.provider_error}}}h(E,"policyFault");function x(r){return{link:r.link,op:r.op,kind:r.kind,retry:r.retry,message:r.message,...r.operation_id===void 0?{}:{operation_id:r.operation_id},...r.since===void 0?{}:{since:r.since},...r.anchorEntryId===void 0?{}:{anchor_entry_id:r.anchorEntryId},...r.providerError===void 0?{}:{provider_error:r.providerError}}}h(x,"faultInput");function ie(r,e){const t=h(n=>`${n.providerId}/${n.modelId}`===e.modelSpec,"onLiveModel");return(r.find(n=>t(n)&&n.thinkingLevel===e.thinkingLevel)??r.find(t))?.rank}h(ie,"liveRouteRank");function re(r){const e=B("pi\u2192provider",r),t=r.diagnostics?.some(n=>n.type===we)??!1;return{classified:e,disposition:t?"fatal":e.disposition}}h(re,"settledProviderFault");function He(r,e){if(r.stopReason!=="error"||Q(r)||ee(r)||Y(r,e))return!1;const{classified:t,disposition:n}=re(r);return n==="auto"&&(t.kind==="connection"||t.kind==="rate-limit"||t.kind==="overloaded")}h(He,"willDaemonRetry");const Se=/does not support assistant message prefill|conversation must end with a user message/i;function Ae(r,e){return e&&Se.test(r)}h(Ae,"isPrefillRejectionDuringEpisode");class Ke{static{h(this,"FaultRetry")}deps;timer=null;failedRetryRoutes=new Set;notFoundModels=new Set;providerFallbackInFlight=null;notFoundFallbackInFlight=null;stagedCapacityFailure=null;agentStarts=0;constructor(e){this.deps=e}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}reset(){this.clearTimer(),this.deps.turnEnds?.abandon(),this.providerFallbackInFlight=null,this.notFoundFallbackInFlight=null,this.stagedCapacityFailure=null}abandonTurnEnd(){this.deps.turnEnds?.abandon()}state(){return ue(this.deps.nodeId)}async recordFault(e){return(await W(this.deps.nodeId,{op:"record",input:e})).fault}async clearFault(e,t=!1){await W(this.deps.nodeId,{op:"clear",...e===void 0?{}:{link:e},...t?{preserve_episode:!0}:{}})}sessionId(e){const t=e.sessionManager.getSessionId?.();return typeof t=="string"&&t!==""?t:null}async clearEpisode(e){const t=this.sessionId(e);t!==null&&await _(this.deps.nodeId,{op:"clear",session_id:t})}onEvent(e){e.type==="agent_start"&&this.agentStarts++,this.maybeSwitchProviderForRetry(e),this.maybeFallbackOnUnusableModel(e)}isActiveAutoFault(e){return e===null||e.retry.disposition!=="auto"||e.retry.by!=="daemon"?!1:e.kind==="connection"||e.kind==="rate-limit"||e.kind==="overloaded"}async publishSettledProviderFault(e){const t={agentEnd:e.stagedProviderAgentEnd,watchdogAbort:e.stagedWatchdogAbort,refreshAbort:e.stagedRefreshAbort,overflowFailure:e.stagedOverflowFailure,capacityFailure:this.stagedCapacityFailure?.generation===e?this.stagedCapacityFailure:null};this.stagedCapacityFailure=null,e.stagedProviderAgentEnd=null,e.stagedWatchdogAbort=!1,e.stagedRefreshAbort=!1,e.stagedOverflowFailure=null;const n=this.agentStarts,i=h(()=>{if(this.deps.installedGeneration()!==e||this.agentStarts!==n)throw new ne},"assertCurrent");let a=Ee;try{for(;;){try{await this.recordStagedOutcome(e,t,i);return}catch(o){if(!de(o))throw o;w({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`settled turn fault write waiting for the daemon: ${o.message}`}})}await new Promise(o=>setTimeout(o,a)),a=Math.min(a*2,Ie),i()}}catch(o){if(!(o instanceof ne))throw o}}async recordStagedOutcome(e,t,n){const{agentEnd:i,watchdogAbort:a,refreshAbort:o,overflowFailure:d,capacityFailure:p}=t,s=e.session,l=h(async F=>{n(),await this.clearEpisode(F)},"clearEpisode"),y=h(async F=>{n(),await this.recordFault(F)},"recordFault"),u=h(async(F,oe)=>{n(),await this.recordPendingProviderFault(F,oe)},"recordPendingProviderFault"),v=await this.state(),m=v.fault,f=v.episode,I=this.sessionId(s),k=this.isActiveAutoFault(m)&&m.link==="pi\u2192provider"?m:f?.state==="admitted"&&f.session_id===I&&this.isActiveAutoFault(f.fault)?f.fault:null,g=k===null?null:{since:k.since,anchorEntryId:k.anchor_entry_id,attempt:k.retry.attempt},c=[...Array.isArray(i?.messages)?i.messages:[]].reverse().find(F=>typeof F=="object"&&F!==null&&F.role==="assistant");if(p!==null||d!==null){await l(s),await y({link:"pi\u2192provider",op:"context overflow recovery",kind:"context-overflow",retry:{disposition:"fatal"},message:p?.errorMessage??d.errorMessage,anchor_entry_id:s.sessionManager.getLeafId?.()??void 0});return}if(a&&c?.stopReason==="aborted"){await u(s,{link:"pi\u2192provider",op:"generation turn",kind:"connection",retry:{disposition:"auto",by:"daemon",...g?.attempt!==void 0?{attempt:g.attempt}:{}},message:typeof c.errorMessage=="string"?c.errorMessage:"engine error (no errorMessage recorded)",...g!==null?{since:g.since}:{},anchor_entry_id:g?.anchorEntryId??s.sessionManager.getLeafId?.()??void 0});return}if(c?.stopReason!=="error"){c!==void 0&&await l(s);return}if(o){await l(s);return}if(ee(c)){await l(s);return}const S=typeof c.errorMessage=="string"?c.errorMessage:"engine error (no errorMessage recorded)";if(Q({stopReason:"error",errorMessage:S})){await l(s);return}const b=Y(c,s.model?.contextWindow),A=re(c),T=g!==null&&A.disposition!=="auto"&&Ae(S,!0),se=T?{kind:"connection",disposition:"auto"}:A.classified,R=T?"auto":A.disposition,C=pe(c),O=ke(c),P=fe(c),$=typeof c.provider=="string"&&c.provider!==""?c.provider:s.model?.provider,L=typeof c.model=="string"&&c.model!==""?c.model:s.model?.id,D=P===void 0||$===void 0||L===void 0?void 0:{provider:$,model:L,...P};b&&await l(s);const M={link:"pi\u2192provider",op:"generation turn",kind:b?"context-overflow":se.kind,retry:b?{disposition:"fatal"}:R==="auto"?{disposition:"auto",by:"daemon",...C!==void 0?{nextAt:new Date(C).toISOString()}:{},...g?.attempt!==void 0?{attempt:g.attempt}:{}}:{disposition:R,...O!==void 0?{nextAt:new Date(O).toISOString()}:{}},message:S,...!b&&R==="auto"&&g!==null?{since:g.since}:{},anchor_entry_id:!b&&R==="auto"&&g?.anchorEntryId!==void 0?g.anchorEntryId:s.sessionManager.getLeafId?.()??void 0,...D===void 0?{}:{provider_error:D}};M.retry.disposition==="auto"?await u(s,M):(await l(s),await y(M))}async recoverOnStartup(){const e=this.deps.installedGeneration();if(e===void 0)return"none";const t=(await this.state()).episode,n=this.sessionId(e.session);if(this.deps.cfg.newCycle===!0)return t!==null&&n!==null&&t.session_id===n&&await _(this.deps.nodeId,{op:"invalidate",session_id:n}),"none";if(t===null||n===null||t.session_id!==n)return"none";if(t.state==="admitted")if(t.fault.anchor_entry_id!==void 0&&!this.hasProgressPastAnchor(e.session,t.fault.anchor_entry_id)){if(!(await _(this.deps.nodeId,{op:"reopen",session_id:n})).applied)return"none"}else return await this.clearEpisode(e.session),"none";else if(t.state!=="pending")return"none";return await this.recordFault(x(E(t.fault))),await this.schedule(),"retry-armed"}hasProgressPastAnchor(e,t){const n=e.sessionManager.getBranch(),i=n.findIndex(o=>o.id===t);return(i===-1?n:n.slice(i+1)).some(o=>{if(o.type!=="message")return!1;const{message:d}=o;return d.role==="toolResult"?!0:d.role==="assistant"&&Array.isArray(d.content)&&d.content.length>0})}async schedule(){const e=this.deps.installedGeneration(),t=this.deps.currentSession();if(t.isStreaming||this.timer!==null)return;if(e===void 0){this.abandonTurnEnd();return}const n=await this.state(),i=n.fault;if(!this.isActiveAutoFault(i)||this.sessionId(t)!==null&&!this.pendingEpisodeMatches(t,i,n)){this.clearTimer(),this.abandonTurnEnd();return}const a=Date.now(),o=this.faultRetryDelayMs(i,a);if(o!==null&&this.deps.turnEnds?.holding()===!0&&_e(i.since,o,a)){await this.endRunTurnOnFault(t,i,o);return}o!==null?this.clearAndArmFaultRetry(o,e):this.abandonTurnEnd()}async endRunTurnOnFault(e,t,n){this.clearTimer(),this.abandonTurnEnd(),w({level:"info",event:"broker.runtime.diagnostic",fields:{message:`run turn completed on provider fault: ${t.kind} retry in ${n}ms is past the ${te}ms turn window (since ${t.since}, attempt ${t.retry.attempt??0})`}}),await this.clearEpisode(e),await this.clearFault("pi\u2192provider")}async rearmIfStranded(){if(this.timer!==null||this.deps.installedGeneration()===void 0)return;const e=this.deps.currentSession();if(e.isStreaming)return;const t=await this.state();!this.isActiveAutoFault(t.fault)||!this.pendingEpisodeMatches(e,t.fault,t)||await this.schedule()}maybeSwitchProviderForRetry(e){if(e.type!=="auto_retry_start")return;const t=B("pi\u2192provider",e.errorMessage??"").kind;if(t!=="rate-limit"&&t!=="connection"||this.providerFallbackInFlight!==null||this.deps.cfg.modelExact===!0)return;const n=this.deps.installedGeneration();if(n===void 0)return;const i=this.deps.currentSession(),a=this.deps.currentServices(),o=this.deps.formatModelSpec(i.model,i.thinkingLevel);if(o===null)return;const d=V(this.deps.cfg.model,N(),!1);if(d===void 0)return;const p=q(d,G()??this.deps.cfg.cwd,U()),s=K(o),l=ie(p,s),y=l===void 0?{route:void 0,capacityExhausted:!1}:this.nextEligibleFallbackRoute(p.slice(l+1),this.deps.registryOf(a),i.getContextUsage()?.tokens,m=>!this.failedRetryRoutes.has(m.routeId));if(y.route===void 0){y.capacityExhausted&&(this.stageCapacityFailure(n,i),queueMicrotask(()=>{this.deps.installedGeneration()===n&&this.deps.currentSession()===i&&i.abortRetry()}));return}const u=y.route,v=(async()=>{const m=this.deps.registryOf(a).find(u.providerId,u.modelId);if(!m||(await i.setModel(m),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i))return;const f=`${u.providerId}/${u.modelId}`===s.modelSpec?s.thinkingLevel:u.thinkingLevel;i.setThinkingLevel(f??"off"),this.failedRetryRoutes.add(u.routeId),await this.deps.broadcastModelChanged(!1)})().catch(m=>{w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`provider route fallback failed: ${m instanceof Error?m.message:String(m)}`}})}).finally(()=>{this.deps.installedGeneration()===n&&(this.providerFallbackInFlight=null)});this.providerFallbackInFlight=v}maybeFallbackOnUnusableModel(e){if(e.type!=="message_end"||e.message.role!=="assistant"||e.message.stopReason!=="error")return;const t=ce(e.message.errorMessage??"");if(!t&&!le(e.message.errorMessage??"")||this.deps.cfg.modelExact===!0||this.notFoundFallbackInFlight!==null)return;const n=this.deps.installedGeneration();if(n===void 0)return;const i=this.deps.currentSession(),a=this.deps.currentServices(),o=this.deps.formatModelSpec(i.model,i.thinkingLevel);if(o===null)return;const d=K(o);this.notFoundModels.add(d.modelSpec);const p=V(this.deps.cfg.model,N(),!1),s=p?q(p,G()??this.deps.cfg.cwd,U()):[],l=ie(s,d),y=l===void 0?{route:void 0,capacityExhausted:!1}:this.nextEligibleFallbackRoute(s.slice(l+1),this.deps.registryOf(a),i.getContextUsage()?.tokens,f=>!this.notFoundModels.has(`${f.providerId}/${f.modelId}`));if(y.route===void 0){y.capacityExhausted&&this.stageCapacityFailure(n,i);return}const u=y.route,v=`${u.providerId}/${u.modelId}${u.thinkingLevel?`:${u.thinkingLevel}`:""}`,m=(async()=>{const f=this.deps.registryOf(a).find(u.providerId,u.modelId);if(f===void 0){w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback skipped: ${v} is not registered`}});return}if(await i.setModel(f),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i)return;i.setThinkingLevel(u.thinkingLevel??"off"),await this.deps.broadcastModelChanged();const I=this.deps.formatModelSpec(i.model,i.thinkingLevel)??v;if(w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback: ${o} unavailable \u2192 ${I}; re-driving turn`}}),await i.agent.waitForIdle(),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i)return;t&&await this.clearFault("pi\u2192provider");const k=X("recovery",{},ve(o,I,t?"credential":"not-found"));Z(k,{type:"runtime",kind:"recovery"}),await this.deps.turnAdmission.admit(g=>j.fresh(()=>i.prompt(k,{preflightResult:g})))})().catch(f=>{w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback failed: ${f instanceof Error?f.message:String(f)}`}})}).finally(()=>{this.deps.installedGeneration()===n&&(this.notFoundFallbackInFlight=null)});this.notFoundFallbackInFlight=m}nextEligibleFallbackRoute(e,t,n,i){let a=0,o=0;for(const d of e){if(!i(d)||Fe([{...d,...he(d,t),automaticFallback:!0}]).candidates.length===0)continue;const p=t.find(d.providerId,d.modelId);if(p!==void 0){if(a++,this.targetCannotFitContext(p.contextWindow,n)){o++;continue}return{route:d,capacityExhausted:!1}}}return{route:void 0,capacityExhausted:a>0&&a===o}}targetCannotFitContext(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e<t}stageCapacityFailure(e,t){const n=t.getContextUsage()?.tokens;this.stagedCapacityFailure={generation:e,errorMessage:Number.isFinite(n)?`All available fallback models have context windows smaller than the current conversation (${n} tokens).`:"All available fallback models have context windows smaller than the current conversation."}}async recordPendingProviderFault(e,t){const n=this.sessionId(e);if(n===null){await this.recordFault(t);return}await _(this.deps.nodeId,{op:"record-pending",session_id:n,input:t})}pendingEpisodeMatches(e,t,n){const i=this.sessionId(e),a=n.episode;return i!==null&&a!==null&&a.state==="pending"&&a.session_id===i&&a.fault.fault_id===t.fault_id}faultRetryDelayMs(e,t){if(e.retry.nextAt!==void 0){const n=Date.parse(e.retry.nextAt)-t;return Number.isFinite(n)?Math.max(0,n):null}return z(E(e),t)?.delayMs??null}clearAndArmFaultRetry(e,t){if(this.deps.installedGeneration()!==t)return;this.clearTimer();const n=Math.min(Math.max(0,e),be),i=Math.max(0,e-n);this.timer=setTimeout(()=>{if(this.timer=null,this.deps.installedGeneration()===t){if(i>0){this.clearAndArmFaultRetry(i,t);return}this.runFaultRetry().catch(a=>{this.abandonTurnEnd(),w({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry fire failed: ${a instanceof Error?a.message:String(a)}`}})})}},n),typeof this.timer.unref=="function"&&this.timer.unref()}async runFaultRetry(){await this.attemptFaultRetry()===void 0&&this.abandonTurnEnd()}async attemptFaultRetry(){const e=this.deps.installedGeneration();if(e===void 0)return;const t=e.session;if(t.isStreaming)return;const n=(await this.state()).fault;if(!this.isActiveAutoFault(n))return;let i=n;if(n.kind==="connection"&&this.deps.turnEnds===void 0){const s=await this.deps.retryProbe();if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming)return;const l=(await this.state()).fault;if(!this.isActiveAutoFault(l)||l.since!==n.since)return;if(!s)return this.clearAndArmFaultRetry(H(l.kind).baseDelayMs,e),"rearmed";i=l}const a=this.deps.turnEnds!==void 0,o=i.retry.attempt??0,d=H(i.kind);if(o>=d.max){await this.recordFault(x(J(E(i)))),await this.clearEpisode(t);return}const p=z(E(i),Date.now());if(p===null){await this.recordFault(x(J(E(i)))),await this.clearEpisode(t);return}if(i.anchor_entry_id!==void 0)try{if((t.sessionManager.getLeafId?.()??null)!==i.anchor_entry_id){const s=await t.navigateTree(i.anchor_entry_id);if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t)return;s.cancelled||this.deps.reWelcomeAll()}}catch(s){w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`fault retry rewind skipped: ${s instanceof Error?s.message:String(s)}`}})}if(!(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t))return this.deps.turnAdmission.admit(async s=>{const l=(await this.state()).fault;if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||!this.isActiveAutoFault(l)||l.since!==i.since){s();return}const y=this.sessionId(t);if(y===null){s();return}if(!(await _(this.deps.nodeId,{op:"admit",session_id:y,fault_id:l.fault_id,retry:p.fault.retry})).applied){s();return}const v=X("recovery",a?{attempt:p.attempt}:{attempt:p.attempt,max:p.max},Re(i.kind,a));Z(v,{type:"runtime",kind:"recovery"}),this.deps.turnEnds?.beginRecovery();try{await j.fresh(()=>t.prompt(v,{preflightResult:s}))}finally{this.deps.turnEnds?.recoveryReturned()}return"prompted"})}}export{Ke as FaultRetry,te as RUN_TURN_RETRY_WINDOW_MS,Ae as isPrefillRejectionDuringEpisode,Re as retryCardBody,_e as runTurnRetryExpired,re as settledProviderFault,He as willDaemonRetry};
|
|
1
|
+
var ae=Object.defineProperty;var m=(r,e)=>ae(r,"name",{value:e,configurable:!0});import{envModelIntent as N,envNodeCwd as G,envProfileId as U}from"../../../shared/env.js";import{isContextOverflow as Y}from"@earendil-works/pi-ai";import{classify as B}from"../../fault-classifier.js";import{isDaemonTransportApiError as de}from"../../../api/errors.js";import{isModelNotFoundError as le,isProviderUnconfiguredError as ce}from"../fault.js";import{brokerRecovery as ue,mutateBrokerFault as W,mutateBrokerProviderRetry as _}from"./daemon-ops.js";import{extractCoolingDeadline as pe}from"../managed-provider-cooling.js";import{extractProviderFailureDetails as fe}from"../../provider-failure.js";import{expandModelCandidates as q,modelRequestFromConfig as V,probeRouteAvailability as he}from"../../model-routes.js";import{operationIdContext as j}from"../../events/operation-id.js";import{emitEvent as w}from"../../events/emit.js";import{CONNECTION_FAULT_RECOVERY_BODY as me,PROVIDER_FAULT_RECOVERY_BODY as ge,RUN_CONNECTION_FAULT_RETRY_BODY as ye,formatCard as X,formatModelFallbackRecovery as ve}from"../../../shared/generated-context.js";import{markFatalOnExhaust as J,nextFaultRetry as z,policyFor as H}from"../fault-recovery.js";import{parseModelSpec as K}from"../model-selection.js";import{endedByAbort as Q}from"../session-cycles.js";import{resolveProviderCandidates as Fe}from"../../subscription-state.js";import{announceMessageOrigin as Z}from"../stamp/channel.js";import{LLM_REFUSAL_DIAGNOSTIC as we,refusalRetryAt as ke}from"./model-adapter.js";import{isSafetyRefusal as ee}from"../../llm/refusal.js";const be=2147483647,te=3e4;function _e(r,e,t){const n=Date.parse(r);return!Number.isFinite(n)||t+e-n>te}m(_e,"runTurnRetryExpired");class ne extends Error{static{m(this,"StaleOutcome")}}const Ee=1e3,Ie=3e4;function Re(r,e){return r!=="connection"?ge:e?ye:me}m(Re,"retryCardBody");function E(r){return{link:r.link,op:r.op,kind:r.kind,retry:r.retry,message:r.message,since:r.since,operation_id:r.operation_id,...r.anchor_entry_id===void 0?{}:{anchorEntryId:r.anchor_entry_id},...r.provider_error===void 0?{}:{providerError:r.provider_error}}}m(E,"policyFault");function x(r){return{link:r.link,op:r.op,kind:r.kind,retry:r.retry,message:r.message,...r.operation_id===void 0?{}:{operation_id:r.operation_id},...r.since===void 0?{}:{since:r.since},...r.anchorEntryId===void 0?{}:{anchor_entry_id:r.anchorEntryId},...r.providerError===void 0?{}:{provider_error:r.providerError}}}m(x,"faultInput");function ie(r,e){const t=m(n=>`${n.providerId}/${n.modelId}`===e.modelSpec,"onLiveModel");return(r.find(n=>t(n)&&n.thinkingLevel===e.thinkingLevel)??r.find(t))?.rank}m(ie,"liveRouteRank");function re(r){const e=B("pi\u2192provider",r),t=r.diagnostics?.some(n=>n.type===we)??!1;return{classified:e,disposition:t?"fatal":e.disposition}}m(re,"settledProviderFault");function He(r,e){if(r.stopReason!=="error"||Q(r)||ee(r)||Y(r,e))return!1;const{classified:t,disposition:n}=re(r);return n==="auto"&&(t.kind==="connection"||t.kind==="rate-limit"||t.kind==="overloaded")}m(He,"willDaemonRetry");const Se=/does not support assistant message prefill|conversation must end with a user message/i;function Ae(r,e){return e&&Se.test(r)}m(Ae,"isPrefillRejectionDuringEpisode");class Ke{static{m(this,"FaultRetry")}deps;timer=null;failedRetryRoutes=new Set;notFoundModels=new Set;providerFallbackInFlight=null;notFoundFallbackInFlight=null;stagedCapacityFailure=null;agentStarts=0;constructor(e){this.deps=e}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}reset(){this.clearTimer(),this.deps.turnEnds?.abandon(),this.providerFallbackInFlight=null,this.notFoundFallbackInFlight=null,this.stagedCapacityFailure=null}abandonTurnEnd(){this.deps.turnEnds?.abandon()}state(){return ue(this.deps.nodeId)}async recordFault(e){return(await W(this.deps.nodeId,{op:"record",input:e})).fault}async clearFault(e,t=!1){await W(this.deps.nodeId,{op:"clear",...e===void 0?{}:{link:e},...t?{preserve_episode:!0}:{}})}sessionId(e){const t=e.sessionManager.getSessionId?.();return typeof t=="string"&&t!==""?t:null}async clearEpisode(e){const t=this.sessionId(e);t!==null&&await _(this.deps.nodeId,{op:"clear",session_id:t})}onEvent(e){e.type==="agent_start"&&this.agentStarts++,this.maybeSwitchProviderForRetry(e),this.maybeFallbackOnUnusableModel(e)}isActiveAutoFault(e){return e===null||e.retry.disposition!=="auto"||e.retry.by!=="daemon"?!1:e.kind==="connection"||e.kind==="rate-limit"||e.kind==="overloaded"}async publishSettledProviderFault(e){const t={agentEnd:e.stagedProviderAgentEnd,watchdogAbort:e.stagedWatchdogAbort,refreshAbort:e.stagedRefreshAbort,overflowFailure:e.stagedOverflowFailure,capacityFailure:this.stagedCapacityFailure?.generation===e?this.stagedCapacityFailure:null};this.stagedCapacityFailure=null,e.stagedProviderAgentEnd=null,e.stagedWatchdogAbort=!1,e.stagedRefreshAbort=!1,e.stagedOverflowFailure=null;const n=this.agentStarts,i=m(()=>{if(this.deps.installedGeneration()!==e||this.agentStarts!==n)throw new ne},"assertCurrent");let a=Ee;try{for(;;){try{await this.recordStagedOutcome(e,t,i);return}catch(s){if(!de(s))throw s;w({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`settled turn fault write waiting for the daemon: ${s.message}`}})}await new Promise(s=>setTimeout(s,a)),a=Math.min(a*2,Ie),i()}}catch(s){if(!(s instanceof ne))throw s}}async recordStagedOutcome(e,t,n){const{agentEnd:i,watchdogAbort:a,refreshAbort:s,overflowFailure:d,capacityFailure:f}=t,o=e.session,l=m(async F=>{n(),await this.clearEpisode(F)},"clearEpisode"),g=m(async F=>{n(),await this.recordFault(F)},"recordFault"),p=m(async(F,oe)=>{n(),await this.recordPendingProviderFault(F,oe)},"recordPendingProviderFault"),v=await this.state(),h=v.fault,c=v.episode,I=this.sessionId(o),k=this.isActiveAutoFault(h)&&h.link==="pi\u2192provider"?h:c?.state==="admitted"&&c.session_id===I&&this.isActiveAutoFault(c.fault)?c.fault:null,y=k===null?null:{since:k.since,anchorEntryId:k.anchor_entry_id,attempt:k.retry.attempt},u=[...Array.isArray(i?.messages)?i.messages:[]].reverse().find(F=>typeof F=="object"&&F!==null&&F.role==="assistant");if(f!==null||d!==null){await l(o),await g({link:"pi\u2192provider",op:"context overflow recovery",kind:"context-overflow",retry:{disposition:"fatal"},message:f?.errorMessage??d.errorMessage,anchor_entry_id:o.sessionManager.getLeafId?.()??void 0});return}if(a&&u?.stopReason==="aborted"){await p(o,{link:"pi\u2192provider",op:"generation turn",kind:"connection",retry:{disposition:"auto",by:"daemon",...y?.attempt!==void 0?{attempt:y.attempt}:{}},message:typeof u.errorMessage=="string"?u.errorMessage:"engine error (no errorMessage recorded)",...y!==null?{since:y.since}:{},anchor_entry_id:this.retryAnchor(o,y?.anchorEntryId)});return}if(u?.stopReason!=="error"){u!==void 0&&await l(o);return}if(s){await l(o);return}if(ee(u)){await l(o);return}const S=typeof u.errorMessage=="string"?u.errorMessage:"engine error (no errorMessage recorded)";if(Q({stopReason:"error",errorMessage:S})){await l(o);return}const b=Y(u,o.model?.contextWindow),A=re(u),T=y!==null&&A.disposition!=="auto"&&Ae(S,!0),se=T?{kind:"connection",disposition:"auto"}:A.classified,R=T?"auto":A.disposition,C=pe(u),O=ke(u),P=fe(u),$=typeof u.provider=="string"&&u.provider!==""?u.provider:o.model?.provider,L=typeof u.model=="string"&&u.model!==""?u.model:o.model?.id,D=P===void 0||$===void 0||L===void 0?void 0:{provider:$,model:L,...P};b&&await l(o);const M={link:"pi\u2192provider",op:"generation turn",kind:b?"context-overflow":se.kind,retry:b?{disposition:"fatal"}:R==="auto"?{disposition:"auto",by:"daemon",...C!==void 0?{nextAt:new Date(C).toISOString()}:{},...y?.attempt!==void 0?{attempt:y.attempt}:{}}:{disposition:R,...O!==void 0?{nextAt:new Date(O).toISOString()}:{}},message:S,...!b&&R==="auto"&&y!==null?{since:y.since}:{},anchor_entry_id:!b&&R==="auto"?this.retryAnchor(o,y?.anchorEntryId):o.sessionManager.getLeafId?.()??void 0,...D===void 0?{}:{provider_error:D}};M.retry.disposition==="auto"?await p(o,M):(await l(o),await g(M))}retryAnchor(e,t){const n=e.sessionManager.getLeafId?.()??void 0;return t!==void 0&&!this.hasProgressPastAnchor(e,t)?t:n}async recoverOnStartup(){const e=this.deps.installedGeneration();if(e===void 0)return"none";const t=(await this.state()).episode,n=this.sessionId(e.session);if(this.deps.cfg.newCycle===!0)return t!==null&&n!==null&&t.session_id===n&&await _(this.deps.nodeId,{op:"invalidate",session_id:n}),"none";if(t===null||n===null||t.session_id!==n)return"none";if(t.state==="admitted")if(t.fault.anchor_entry_id!==void 0&&!this.hasProgressPastAnchor(e.session,t.fault.anchor_entry_id)){if(!(await _(this.deps.nodeId,{op:"reopen",session_id:n})).applied)return"none"}else return await this.clearEpisode(e.session),"none";else if(t.state!=="pending")return"none";return await this.recordFault(x(E(t.fault))),await this.schedule(),"retry-armed"}hasProgressPastAnchor(e,t){const n=e.sessionManager.getBranch(),i=n.findIndex(s=>s.id===t);return(i===-1?n:n.slice(i+1)).some(s=>{if(s.type!=="message")return!1;const{message:d}=s;return d.role==="toolResult"?!0:d.role==="assistant"&&Array.isArray(d.content)&&d.content.length>0})}async schedule(){const e=this.deps.installedGeneration(),t=this.deps.currentSession();if(t.isStreaming||this.timer!==null)return;if(e===void 0){this.abandonTurnEnd();return}const n=await this.state(),i=n.fault;if(!this.isActiveAutoFault(i)||this.sessionId(t)!==null&&!this.pendingEpisodeMatches(t,i,n)){this.clearTimer(),this.abandonTurnEnd();return}const a=Date.now(),s=this.faultRetryDelayMs(i,a);if(s!==null&&this.deps.turnEnds?.holding()===!0&&_e(i.since,s,a)){await this.endRunTurnOnFault(t,i,s);return}s!==null?this.clearAndArmFaultRetry(s,e):this.abandonTurnEnd()}async endRunTurnOnFault(e,t,n){this.clearTimer(),this.abandonTurnEnd(),w({level:"info",event:"broker.runtime.diagnostic",fields:{message:`run turn completed on provider fault: ${t.kind} retry in ${n}ms is past the ${te}ms turn window (since ${t.since}, attempt ${t.retry.attempt??0})`}}),await this.clearEpisode(e),await this.clearFault("pi\u2192provider")}async rearmIfStranded(){if(this.timer!==null||this.deps.installedGeneration()===void 0)return;const e=this.deps.currentSession();if(e.isStreaming)return;const t=await this.state();!this.isActiveAutoFault(t.fault)||!this.pendingEpisodeMatches(e,t.fault,t)||await this.schedule()}maybeSwitchProviderForRetry(e){if(e.type!=="auto_retry_start")return;const t=B("pi\u2192provider",e.errorMessage??"").kind;if(t!=="rate-limit"&&t!=="connection"||this.providerFallbackInFlight!==null||this.deps.cfg.modelExact===!0)return;const n=this.deps.installedGeneration();if(n===void 0)return;const i=this.deps.currentSession(),a=this.deps.currentServices(),s=this.deps.formatModelSpec(i.model,i.thinkingLevel);if(s===null)return;const d=V(this.deps.cfg.model,N(),!1);if(d===void 0)return;const f=q(d,G()??this.deps.cfg.cwd,U()),o=K(s),l=ie(f,o),g=l===void 0?{route:void 0,capacityExhausted:!1}:this.nextEligibleFallbackRoute(f.slice(l+1),this.deps.registryOf(a),i.getContextUsage()?.tokens,h=>!this.failedRetryRoutes.has(h.routeId));if(g.route===void 0){g.capacityExhausted&&(this.stageCapacityFailure(n,i),queueMicrotask(()=>{this.deps.installedGeneration()===n&&this.deps.currentSession()===i&&i.abortRetry()}));return}const p=g.route,v=(async()=>{const h=this.deps.registryOf(a).find(p.providerId,p.modelId);if(!h||(await i.setModel(h),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i))return;const c=`${p.providerId}/${p.modelId}`===o.modelSpec?o.thinkingLevel:p.thinkingLevel;i.setThinkingLevel(c??"off"),this.failedRetryRoutes.add(p.routeId),await this.deps.broadcastModelChanged(!1)})().catch(h=>{w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`provider route fallback failed: ${h instanceof Error?h.message:String(h)}`}})}).finally(()=>{this.deps.installedGeneration()===n&&(this.providerFallbackInFlight=null)});this.providerFallbackInFlight=v}maybeFallbackOnUnusableModel(e){if(e.type!=="message_end"||e.message.role!=="assistant"||e.message.stopReason!=="error")return;const t=ce(e.message.errorMessage??"");if(!t&&!le(e.message.errorMessage??"")||this.deps.cfg.modelExact===!0||this.notFoundFallbackInFlight!==null)return;const n=this.deps.installedGeneration();if(n===void 0)return;const i=this.deps.currentSession(),a=this.deps.currentServices(),s=this.deps.formatModelSpec(i.model,i.thinkingLevel);if(s===null)return;const d=K(s);this.notFoundModels.add(d.modelSpec);const f=V(this.deps.cfg.model,N(),!1),o=f?q(f,G()??this.deps.cfg.cwd,U()):[],l=ie(o,d),g=l===void 0?{route:void 0,capacityExhausted:!1}:this.nextEligibleFallbackRoute(o.slice(l+1),this.deps.registryOf(a),i.getContextUsage()?.tokens,c=>!this.notFoundModels.has(`${c.providerId}/${c.modelId}`));if(g.route===void 0){g.capacityExhausted&&this.stageCapacityFailure(n,i);return}const p=g.route,v=`${p.providerId}/${p.modelId}${p.thinkingLevel?`:${p.thinkingLevel}`:""}`,h=(async()=>{const c=this.deps.registryOf(a).find(p.providerId,p.modelId);if(c===void 0){w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback skipped: ${v} is not registered`}});return}if(await i.setModel(c),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i)return;i.setThinkingLevel(p.thinkingLevel??"off"),await this.deps.broadcastModelChanged();const I=this.deps.formatModelSpec(i.model,i.thinkingLevel)??v;if(w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback: ${s} unavailable \u2192 ${I}; re-driving turn`}}),await i.agent.waitForIdle(),this.deps.installedGeneration()!==n||this.deps.currentSession()!==i)return;t&&await this.clearFault("pi\u2192provider");const k=X("recovery",{},ve(s,I,t?"credential":"not-found"));Z(k,{type:"runtime",kind:"recovery"}),await this.deps.turnAdmission.admit(y=>j.fresh(()=>i.prompt(k,{preflightResult:y})))})().catch(c=>{w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`${t?"unconfigured-provider":"not_found"} fallback failed: ${c instanceof Error?c.message:String(c)}`}})}).finally(()=>{this.deps.installedGeneration()===n&&(this.notFoundFallbackInFlight=null)});this.notFoundFallbackInFlight=h}nextEligibleFallbackRoute(e,t,n,i){let a=0,s=0;for(const d of e){if(!i(d)||Fe([{...d,...he(d,t),automaticFallback:!0}]).candidates.length===0)continue;const f=t.find(d.providerId,d.modelId);if(f!==void 0){if(a++,this.targetCannotFitContext(f.contextWindow,n)){s++;continue}return{route:d,capacityExhausted:!1}}}return{route:void 0,capacityExhausted:a>0&&a===s}}targetCannotFitContext(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e<t}stageCapacityFailure(e,t){const n=t.getContextUsage()?.tokens;this.stagedCapacityFailure={generation:e,errorMessage:Number.isFinite(n)?`All available fallback models have context windows smaller than the current conversation (${n} tokens).`:"All available fallback models have context windows smaller than the current conversation."}}async recordPendingProviderFault(e,t){const n=this.sessionId(e);if(n===null){await this.recordFault(t);return}await _(this.deps.nodeId,{op:"record-pending",session_id:n,input:t})}pendingEpisodeMatches(e,t,n){const i=this.sessionId(e),a=n.episode;return i!==null&&a!==null&&a.state==="pending"&&a.session_id===i&&a.fault.fault_id===t.fault_id}faultRetryDelayMs(e,t){if(e.retry.nextAt!==void 0){const n=Date.parse(e.retry.nextAt)-t;return Number.isFinite(n)?Math.max(0,n):null}return z(E(e),t)?.delayMs??null}clearAndArmFaultRetry(e,t){if(this.deps.installedGeneration()!==t)return;this.clearTimer();const n=Math.min(Math.max(0,e),be),i=Math.max(0,e-n);this.timer=setTimeout(()=>{if(this.timer=null,this.deps.installedGeneration()===t){if(i>0){this.clearAndArmFaultRetry(i,t);return}this.runFaultRetry().catch(a=>{this.abandonTurnEnd(),w({level:"warn",event:"broker.runtime.diagnostic",fields:{message:`fault retry fire failed: ${a instanceof Error?a.message:String(a)}`}})})}},n),typeof this.timer.unref=="function"&&this.timer.unref()}async runFaultRetry(){await this.attemptFaultRetry()===void 0&&this.abandonTurnEnd()}async attemptFaultRetry(){const e=this.deps.installedGeneration();if(e===void 0)return;const t=e.session;if(t.isStreaming)return;const n=(await this.state()).fault;if(!this.isActiveAutoFault(n))return;let i=n;if(n.kind==="connection"&&this.deps.turnEnds===void 0){const o=await this.deps.retryProbe();if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming)return;const l=(await this.state()).fault;if(!this.isActiveAutoFault(l)||l.since!==n.since)return;if(!o)return this.clearAndArmFaultRetry(H(l.kind).baseDelayMs,e),"rearmed";i=l}const a=this.deps.turnEnds!==void 0,s=i.retry.attempt??0,d=H(i.kind);if(s>=d.max){await this.recordFault(x(J(E(i)))),await this.clearEpisode(t);return}const f=z(E(i),Date.now());if(f===null){await this.recordFault(x(J(E(i)))),await this.clearEpisode(t);return}if(!(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t))return this.deps.turnAdmission.admit(async o=>{const l=(await this.state()).fault;if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t||t.isStreaming||!this.isActiveAutoFault(l)||l.since!==i.since){o();return}const g=this.sessionId(t);if(g===null){o();return}if(!(await _(this.deps.nodeId,{op:"admit",session_id:g,fault_id:l.fault_id,retry:f.fault.retry})).applied){o();return}const v=i.anchor_entry_id;if(v!==void 0&&(t.sessionManager.getLeafId?.()??null)!==v&&!this.hasProgressPastAnchor(t,v))try{const c=await t.navigateTree(v);if(this.deps.installedGeneration()!==e||this.deps.currentSession()!==t){o();return}c.cancelled||this.deps.reWelcomeAll()}catch(c){w({level:"debug",event:"broker.runtime.diagnostic",fields:{message:`fault retry rewind skipped: ${c instanceof Error?c.message:String(c)}`}})}const h=X("recovery",a?{attempt:f.attempt}:{attempt:f.attempt,max:f.max},Re(i.kind,a));Z(h,{type:"runtime",kind:"recovery"}),this.deps.turnEnds?.beginRecovery();try{await j.fresh(()=>t.prompt(h,{preflightResult:o}))}finally{this.deps.turnEnds?.recoveryReturned()}return"prompted"})}}export{Ke as FaultRetry,te as RUN_TURN_RETRY_WINDOW_MS,Ae as isPrefillRejectionDuringEpisode,Re as retryCardBody,_e as runTurnRetryExpired,re as settledProviderFault,He as willDaemonRetry};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var V=Object.defineProperty;var s=(e,r)=>V(e,"name",{value:r,configurable:!0});import{envProfileId as T}from"../../shared/env.js";import{mkdirSync as M}from"node:fs";import{join as U}from"node:path";import{readMergedLaunchConfig as D}from"../config.js";import{fork as F}from"node:child_process";import{fileURLToPath as $}from"node:url";import{freshChildNodeExecPath as G,recheckChildNode as K}from"./branded-host.js";import{LAUNCH_SYSTEM_PROMPT as W}from"./launch-prompt.js";import{nodeEnv as X}from"./nodes.js";import{editorLabel as B}from"../canvas/index.js";import{CANVAS_EXTENSIONS as ye,CANVAS_STOPHOOK_PATH as ve,CANVAS_INBOX_WATCHER_PATH as Le,CANVAS_RECAP_PATH as Re,CANVAS_GOAL_CAPTURE_PATH as be,CANVAS_PASSIVE_CONTEXT_PATH as He,CANVAS_CONTEXT_INTRO_PATH as Ve,CANVAS_TOOL_GUIDE_PATH as Me,CANVAS_DOC_SUBSTRATE_PATH as Ue,CANVAS_STRUCTURED_OUTPUT_PATH as De,CANVAS_BASH_VALVE_PATH as Fe}from"./canvas-extensions.js";import{nodeRunDir as j}from"../canvas/paths.js";import{writeFileBeneath as z}from"../spaces/open-beneath.js";import{projectOutputSchema as Y}from"./structured-output.js";import{CANVAS_EXTENSIONS as Q,mergeCanvasExtensions as P,assertMandatoryCanvasExtensions as J}from"./canvas-extensions.js";import{modelLadders as a,defaultProvider as C,STRENGTH_ALIASES as p,MODEL_PROVIDER_KEYS as x,MODEL_STRENGTHS as A,THINKING_SUFFIXES as Z,stripThinkingSuffix as m}from"./model-selection.js";import{OPENAI_PROVIDER_ENV as Ge,configuredLadderProviders as Ke,inferPortableModelSelection as We}from"./model-selection.js";function k(e,r=a()){return r[e]}s(k,"ladderFor");const S={light:0,medium:1,strong:2,ultra:3};function q(e,r,n){const t=m(e);for(const o of[!0,!1]){const i=o?A:[...A].sort((c,u)=>S[c]-S[u]);for(const c of n)for(const u of i){const f=r[c][u];if(!(o?f!==e:m(f)!==t))return{provider:c,strength:u}}}return null}s(q,"findLadderCell");function N(e){const r=e.lastIndexOf("/"),n=r===-1?void 0:e.slice(0,r),t=r===-1?e:e.slice(r+1),o=p[t];return o!==void 0?o:n!==void 0&&n!=="anthropic"?null:t==="opus"?"strong":t==="sonnet"?"medium":t==="haiku"?"light":null}s(N,"modelTokenStrength");function w(e,r=a()){const n=N(e);return n!==null?n:q(_(e,r),r,x)?.strength??null}s(w,"resolvedModelStrength");function ee(e){return e==="review"||e.startsWith("review/")||e.includes("/reviewers/")}s(ee,"isReviewQualityKind");function ne(e,r,n,t=a()){if(r===void 0)return n;if(!ee(e)||n===void 0)return r;const o=w(r,t),i=w(n,t);return o===null||i===null?r:S[o]<S[i]?n:r}s(ne,"floorReviewModel");function I(e){if(e.includes("/")){const r=e.lastIndexOf("/"),n=e.slice(0,r),t=e.slice(r+1);return n!==""&&(p[t]!==void 0||n==="anthropic"&&(t==="opus"||t==="sonnet"||t==="haiku"))}return p[e]!==void 0||e==="opus"||e==="sonnet"||e==="haiku"}s(I,"isPortableModelToken");function O(e,r=a()){const n=N(e);if(n!==null)return e.includes("/")?{family:e.slice(0,e.lastIndexOf("/")),strength:n}:e==="opus"||e==="sonnet"||e==="haiku"?{family:"anthropic",strength:n}:{family:C(r),strength:n}}s(O,"logicalModelIntent");function Te(e,r=a()){return I(e)?O(e,r):void 0}s(Te,"explicitModelIntent");function _(e,r=a()){if(e.includes("/")){const t=e.indexOf("/"),o=e.slice(0,t),i=e.slice(t+1),c=p[i];if(c!==void 0&&(o==="anthropic"||o==="openai"))return k(o,r)[c];if(o==="anthropic"){if(i==="opus")return r.anthropic.strong;if(i==="sonnet")return r.anthropic.medium;if(i==="haiku")return r.anthropic.light}return e}const n=p[e];return n!==void 0?k(C(r),r)[n]:e==="opus"?r.anthropic.strong:e==="sonnet"?r.anthropic.medium:e==="haiku"?r.anthropic.light:e}s(_,"normalizeModel");function y(e){const r=e.lastIndexOf(":");if(r<=0)return;const n=e.slice(r+1);return Z.has(n)?n:void 0}s(y,"thinkingSuffixOf");function re(e=x){const r=e.length>0?e:x,n=a(),t=[];for(const o of A)for(const i of r)t.push(n[i][o]);return t}s(re,"interleavedLadderCycle");function Pe(e,r=1,n){const t=re(n),o=_(e),i=m(o),c=y(o);let u=t.findIndex(f=>m(f)===i&&y(f)===c);return u===-1&&(u=t.findIndex(f=>m(f)===i)),u===-1?t[0]:t[(u+r+t.length)%t.length]}s(Pe,"nextLadderModel");function v(e,r,n,t){const o=t.kinds[e],i=t.modelLadders,c=r==="orchestrator"?o?.orchestratorModel??o?.model:o?.model,u=n.modelExact===!0?n.model:ne(e,n.model,c,i),f=n.modelExact===!0||n.modelOverride===!0&&n.model!==void 0&&!I(n.model),l=n.modelExact===!0?u:u!==void 0?_(u,i):void 0,h=f?void 0:n.modelIntent??(u!==void 0?O(u,i):void 0);return{launch:{model:l,modelIntent:h,modelExact:f?!0:void 0,tools:o?.tools??[],extensions:P([...Q,...o?.extensions??[]]),systemPrompt:W,env:{...n.extraEnv??{},...h?{CRTR_MODEL_INTENT:`${h.family}/${h.strength}`}:{}}},lifecycle:n.lifecycle}}s(v,"buildLaunchSpecFromMerged");function Ce(e,r,n){return v(e,r,n,D(n.cwd??process.cwd(),n.profileId!==void 0?n.profileId:T()||null))}s(Ce,"buildLaunchSpec");async function ke(e,r,n){const t=n.cwd??process.cwd(),o=n.profileId!==void 0?n.profileId:T()||null,i=await oe(t,o);return v(e,r,n,i)}s(ke,"buildLaunchSpecAsync");const L=15e3;function te(e,r,n){const t=r!==null?`was killed by ${r}`:`exited with code ${e}`,o=n.trim().split(`
|
|
2
2
|
`).slice(-8).join(`
|
|
3
|
-
`).slice(-1500);return`launch config subprocess ${t}${o!==""?`: ${o}`:" (no stderr output)"}`}s(
|
|
3
|
+
`).slice(-1500);return`launch config subprocess ${t}${o!==""?`: ${o}`:" (no stderr output)"}`}s(te,"describeLaunchConfigExit");class R extends Error{static{s(this,"LaunchConfigWorkerCrash")}}async function oe(e,r,n={}){const t=n.execPath??await G(),o=n.workerPath??$(new URL("./launch-config-worker.js",import.meta.url));try{return await b(e,r,t,o)}catch(i){if(!(i instanceof R))throw i;const c=await K(t);if(c===t)throw i;return b(e,r,c,o)}}s(oe,"readMergedLaunchConfigAsync");function b(e,r,n,t){return new Promise((o,i)=>{const c=F(t,[],{execPath:n,stdio:["ignore","ignore","pipe","ipc"],serialization:"advanced"});let u="";c.stderr?.setEncoding("utf8").on("data",d=>{u=(u+d).slice(-8192)}),c.send({cwd:e,profileId:r});let f=!1;const l=s(d=>{f||(f=!0,clearTimeout(h),c.connected&&c.disconnect(),c.killed||c.kill("SIGKILL"),d())},"finish"),h=setTimeout(()=>l(()=>i(new Error(`timed out after ${L}ms reading launch config for ${e}`))),L);c.once("message",d=>{d.error!==void 0?l(()=>i(new Error(d.error))):d.config!==void 0?l(()=>o(d.config)):l(()=>i(new Error("launch config subprocess returned no result")))});let g=null;c.on("error",d=>{g??=d}),c.once("close",(d,H)=>{if(f)return;const E=te(d,H,u);l(()=>i(new R(g===null?E:`${E} (${g.message})`)))})})}s(b,"runLaunchConfigWorker");function ie(e,r){try{const n=j(e);M(n,{recursive:!0});const t=U(n,"system-prompt.md");return z(n,t,r,{atomic:!0}),t}catch{return null}}s(ie,"writeSystemPromptFile");function Ne(e,r={}){const n=e.launch,t=P(n?.extensions);J(t);const o=[];for(const i of t)o.push("-e",i);if(o.push("-n",B(e)),r.forkFrom!==void 0&&r.forkFrom!=="")o.push("--fork",r.forkFrom);else{const i=r.resumeSessionPath??r.resumeSessionId;i!==void 0&&o.push("--session",i),r.newCycle===!0&&o.push("--crtr-new-cycle")}if(n?.model!==void 0&&o.push("--model",n.model),n?.modelExact===!0&&o.push("--crtr-model-exact"),n?.tools!==void 0&&n.tools.length>0&&o.push("--tools",n.tools.join(",")),n?.systemPrompt!==void 0&&n.systemPrompt!==""){const i=ie(e.node_id,n.systemPrompt)??n.systemPrompt;o.push("--append-system-prompt",i)}return r.prompt!==void 0&&r.prompt!==""&&o.push(r.prompt),Y(e.node_id),{argv:o,env:X(e)}}s(Ne,"buildPiArgv");function we(e){for(const[t,o]of Object.entries(e.env))process.env[t]=o;const r={cwd:e.env.CRTR_NODE_CWD??process.cwd(),extensionPaths:[]},n=e.argv;for(let t=0;t<n.length;t++){const o=n[t];switch(o){case"-e":r.extensionPaths.push(n[++t]);break;case"-n":r.editorName=n[++t];break;case"--fork":r.forkFrom=n[++t];break;case"--session":{const i=n[++t];i.includes("/")||i.endsWith(".jsonl")?r.resumeSessionPath=i:r.resumeSessionId=i;break}case"--model":r.model=n[++t];break;case"--crtr-model-exact":r.modelExact=!0;break;case"--tools":r.tools=n[++t].split(",").filter(i=>i!=="");break;case"--append-system-prompt":r.appendSystemPromptPath=n[++t];break;case"--crtr-new-cycle":r.newCycle=!0;break;default:r.firstPrompt=o;break}}return r}s(we,"piInvocationToSdkConfig");export{Fe as CANVAS_BASH_VALVE_PATH,Ve as CANVAS_CONTEXT_INTRO_PATH,Ue as CANVAS_DOC_SUBSTRATE_PATH,ye as CANVAS_EXTENSIONS,be as CANVAS_GOAL_CAPTURE_PATH,Le as CANVAS_INBOX_WATCHER_PATH,He as CANVAS_PASSIVE_CONTEXT_PATH,Re as CANVAS_RECAP_PATH,ve as CANVAS_STOPHOOK_PATH,De as CANVAS_STRUCTURED_OUTPUT_PATH,Me as CANVAS_TOOL_GUIDE_PATH,Ge as OPENAI_PROVIDER_ENV,Ce as buildLaunchSpec,ke as buildLaunchSpecAsync,Ne as buildPiArgv,Ke as configuredLadderProviders,te as describeLaunchConfigExit,Te as explicitModelIntent,We as inferPortableModelSelection,re as interleavedLadderCycle,I as isPortableModelToken,O as logicalModelIntent,N as modelTokenStrength,Pe as nextLadderModel,_ as normalizeModel,we as piInvocationToSdkConfig,oe as readMergedLaunchConfigAsync};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ie=Object.defineProperty;var s=(e,t)=>Ie(e,"name",{value:t,configurable:!0});import{envProfileId as Ae}from"../../../shared/env.js";import{pausedCanvasProfiles as $e}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 Ce,formatSituationalProse as Ne}from"../../../core/runtime/situational-context.js";import{closeNode as Te}from"../../../core/runtime/close.js";import{reviveNode as Pe}from"../../../core/runtime/revive.js";import{nowIso as B}from"../../../core/fs-utils.js";import{appPaidLaunch as Ee,assertLaunchModelRegistered as K,forkNode as De,resolveForkSource as Le,spawnChildPrepared as Me}from"../../../core/runtime/spawn.js";import{forkSourceNode as je,newNodeId as ne}from"../../../core/runtime/nodes.js";import{abandonCreateRequest as te,childrenOf as Ge,completeCreateRequest as ie,findCreateRequest as Fe,getNode as R,recordCreateRequestNode as Be,reserveCreateRequest as oe,reserveCreateRequestNode as Ke,listNodes as re,recordRespawnAttempt as We,subscribersOf as Ve,subscriptionsOf as ae,updateNode as C}from"../../../core/canvas/canvas.js";import{armControllerWait as xe}from"../../../core/canvas/waits.js";import{subtreeIds as ze}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as W}from"../../../core/canvas/db.js";import{markNodeRead as Je}from"../../../core/canvas/recovery.js";import{nodeObject as Ue}from"../../../core/graph/objects.js";import{recordActedOn as Ye}from"../../../core/graph/edges.js";import{publish as He}from"../../../core/graph/events.js";import{readerFor as Qe}from"../reader.js";import{relocateSessionCwd as Xe,unbindSession as Ze}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as qe}from"../../../core/canvas/attention.js";import{isSafeNodeId as en}from"../../../core/canvas/paths.js";import{contextDir as de,nodeAgentDir as V}from"../../../core/canvas/node-agent-paths.js";import{checkCronBirth as nn}from"../../cron/authority.js";import{cronBirthPlacement as tn}from"../../cron/armed-context.js";import{existsBeneath as on,isAbsentOrRefused as rn,isBeneathRefusal as an,readdirBeneath as dn}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as sn,readNodeSession as ln,readNodeSnapshot as cn,transcriptMarkdown as fn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as un}from"../../../core/substrate/subject.js";import{reviveAll as pn}from"../../../core/runtime/revive-all.js";import{promoteAsync as mn,requestYieldAsync as wn,reshapeNodeAsync as x}from"../../../core/runtime/promote.js";import{recycleNode as hn}from"../../../core/runtime/recycle.js";import{relaunchRoot as yn}from"../../../core/runtime/reset.js";import{assertReopenGate as _n}from"../../../core/runtime/reopen.js";import{writeYieldMessage as gn,readGoal as bn}from"../../../core/runtime/kickoff.js";import{ensureRoadmap as vn,hasRoadmap as kn}from"../../../core/runtime/roadmap.js";import{renameWindow as Sn}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Rn,explicitModelIntent as On,normalizeModel as In,readMergedLaunchConfigAsync as se}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as An}from"../../../core/model-routes.js";import{persistDormantModel as $n,setModelLive as Cn}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as le}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Nn}from"../../../core/runtime/broker-request.js";import{boundFleet as P}from"../../../core/runtime/fleet.js";import{admitLegacyStructuredOutput as Tn}from"../../structured-requests/sidecar.js";import{assertOutputSchemaAccepted as Pn}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 Dn}from"../../../core/human-actions.js";import{parseDurationMs as Ln}from"../../../core/wake.js";import{claimWarmNode as Mn,refillWarmPool as fe,resumeWarmClaim as jn,warmPoolEnabled as Gn}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as z,isLaunchKind as Fn,resolveLaunchTarget as Bn}from"../../../core/runtime/launch-target.js";import{fullName as Kn}from"../../../core/canvas/labels.js";import{reportsForNode as ue}from"./reports.js";import{requireUsableProfile as Wn}from"./profiles.js";import{assertProfileActive as Vn,loadExactProfileManifest as xn}from"../../../core/profiles/manifest.js";import{getCron as pe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as zn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as Jn}from"../../control.js";import{notFound as E,usage as w}from"../../../core/errors.js";import{assertScope as Un,validateScopes as me}from"../../../core/scopes.js";import{scopeAllowed as I}from"../../../shared/env.js";import{toCloseResultDTO as Yn,toNodeDetailDTO as J,toNodeSummaryDTO as Hn,toReviveResultDTO as Qn}from"../map.js";import{ApiError as u}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{actsAsPerson as Xn,brokerMayReach as U,canReadNode as we,resolvedScopes as Zn}from"../router.js";import{forwardVerb as qn,queryWithoutMachine as et,relayError as nt,unknownError as tt,withMachine as it}from"../../peer/forward.js";import{fileRoot as ot}from"../../../core/spaces/file-root.js";import{activeGrant as rt,payerOfGrant as at,terminalGrant as dt}from"../../../core/grants/mirror.js";import{appRungForGrant as st}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as lt}from"../../../core/model-routes.js";import{readConfig as ct}from"../../../core/config.js";import{hasConfiguredProviderCredential as ft,NO_PROVIDER_CREDENTIAL_MESSAGE as he}from"../../../core/runtime/provider-credential-gate.js";import{filterAsync as Y,mapAsync as ye}from"../../../core/async-array.js";async function h(e){const t=await R(e);if(t===null)throw E(`unknown node: ${e}`,{received:e});return t}s(h,"requireMeta");async function H(e){return{subscribesTo:await ae(e),subscribers:await Ve(e),children:await Ge(e)}}s(H,"edgesFor");async function g(e){const t=await h(e);return await J(t,await H(e))}s(g,"detailOf");async function ut(e){let t=(await ue(e)).length;try{t+=dn(await V(e),await de(e)).length}catch(n){if(!rn(n))throw n}return t}s(ut,"countFiles");function pt(e){if(typeof e!="object"||e===null)throw w("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw w("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw w("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw w("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 w("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 w("request_key must be a non-empty string of at most 128 characters when provided");return t}s(pt,"parseCreateBody");function mt(e){if(e===void 0)return;const t=Ln(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()}s(mt,"parseDeadline");function wt(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}}s(wt,"parseOutcomeDelivery");function ht(e,t){const n=Dn(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})}s(ht,"resolveOutcomeDelivery");function yt(e,t,n){const o={kind:e.kind,cwd:n,prompt:e.prompt??""};return e.mode!==void 0&&(o.mode=e.mode),e.name!==void 0&&(o.name=e.name),e.description!==void 0&&(o.description=e.description),t!==void 0&&(o.parent=t),e.creator!==void 0&&(o.creator=e.creator),e.scopes!==void 0&&(o.scopes=e.scopes),e.isolated!==void 0&&(o.isolated=e.isolated),e.root===!0&&(o.root=!0),e.root_lifecycle!==void 0&&(o.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(o.worktree=!0),typeof e.worktree=="string"&&(o.worktreeBase=e.worktree),e.worktree!==void 0&&(o.worktreeCwd=T(e.pin_cwd??e.cwd??n)),e.fork_from!==void 0&&(o.forkFrom=e.fork_from),e.model!==void 0&&(o.model=e.model),e.profile!==void 0&&(o.profile=e.profile),e.situational_context!==void 0&&(o.situationalContext=e.situational_context),e.node_id!==void 0&&(o.nodeId=e.node_id),o}s(yt,"buildRecipe");function _t(e,t,n){return!Gn()||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}}s(_t,"warmRequestFor");import{resolveCreateKind as _o}from"../../../core/runtime/launch-target.js";function _e(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return An(e.model,t,e.modelExact===!0)}s(_e,"requestFromLaunch");function gt(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(o=>!I(t,o));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})}s(gt,"withinCeiling");async function ge(e,t,n){const o=(await Rn(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(_e(o),{cwd:e.cwd,profileId:e.profile_id??null},n)}s(ge,"assertNodeModelChangeRegistered");async function be(e,t){const n=e.principal;if(n.class!=="broker"&&n.class!=="cron")return;const o=ot({app:n.app,resolved:await Zn(n),launched:n.scopes},t,"read");if("root"in o)return;const i="missing"in o?o.missing:null;throw new u(403,"scope_missing",i?`the child's directory ${t} needs missing scope ${i}`:`no permission of this run names the child's directory ${t}`,void 0,void 0,i?{scope:i}:void 0)}s(be,"assertCallerReaches");const Q=new Map;async function bt(e,t={},n={}){const o=gt(pt(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(o.prefer_warm===!0&&c.app!=="app:terminal"&&(o.prefer_warm=!1),o.parent!=null){const r=await h(o.parent);if(r.grantee!==c.app)throw new u(403,"other_app_run","cannot create a child under another app's node");if(!await U(c,o.parent,r.grantee??"app:terminal"))throw E(`unknown node: ${o.parent}`,{received:o.parent})}if(o.creator!==void 0&&o.creator!==c.node)throw new u(403,"other_app_run","cannot create for another node");if(o.fork_from!==void 0){let r=null;try{r=await je(await Le(o.fork_from))}catch{}if(r?.grantee!==c.app||!await U(c,r.node_id,r.grantee))throw new u(403,"other_app_run","cannot fork another app's conversation")}o.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const l of["parent","creator","fork_from","node_id"])if(o[l]!=null)throw new u(403,"permission_error",`a cron cannot set ${l} on a node it starts`);o.prefer_warm=!1;const r=await nn({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!r.allowed)throw new u(r.reason==="scope_missing"?403:401,r.reason==="scope_missing"?"scope_missing":"grant_revoked",r.message);if(o.scopes!==void 0){const l=o.scopes.find(p=>!I(r.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&&(o.scopes=[...c.scopes]);o.node_id=await ne(),c.isolated&&(o.isolated=!0,o.cwd=await V(o.node_id,c.app))}o.creator!==void 0&&Un(await h(o.creator),"crtr:act");const i=o.request_key?.trim();if(i===void 0||o.node_id!==void 0&&en(o.node_id)&&await R(o.node_id)!==null&&(await Fe(i))?.nodeId!==o.node_id)return D(e,o,t,n);const d=Q.get(i);if(d!==void 0)return d;const a=vt(e,o,i,t,n);Q.set(i,a);try{return await a}finally{Q.delete(i)}}s(bt,"handleCreate");async function vt(e,t,n,o,i){const d=await oe(n);if(d.nodeId!==null&&await R(d.nodeId)!==null){if(d.state!=="warm_claimed"){const a=await R(d.nodeId);if(e.principal.class!=="person"&&!await we(e.principal,a.grantee??"app:terminal",d.nodeId))throw new u(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await g(d.nodeId)}}return D(e,t,o,i,d)}try{return await D(e,t,o,i,d)}catch(a){const c=await oe(n);throw(c.nodeId===null||await R(c.nodeId)===null)&&await te(n,c.nodeId),a}}s(vt,"handleKeyedCreateRequest");async function D(e,t,n,o,i=void 0){const d=o.deadlineAt??mt(t.deadline),a=wt(t.outcome_delivery),c=e.principal.class==="cron"?await tn({grantee:e.principal.app,sub:e.principal.sub,grant_id:e.principal.grant,scopes:e.principal.scopes,cron_id:e.principal.cron,origin_run_id:e.principal.origin_run,isolated:e.principal.isolated,creator:(await pe(e.principal.cron))?.created_by??null},t.node_id):null;c!==null&&(t.root=c.root===!0);const r=c?.parent??t.parent??void 0;if(r==null&&t.root!==!0)throw w("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 w("output_schema must be a JSON schema string")}if(l===null||typeof l!="object"||Array.isArray(l))throw w("output_schema must be a JSON schema object");await Pn(l)}const{profileId:p,kind:m,cwd:f,launch:b}=await Bn(t,{validateKind:Oe});await be(e,f),t.worktree!==void 0&&await be(e,T(t.pin_cwd??t.cwd??f));const v={...t,kind:m},_=a===void 0?void 0:ht(a,f),X=("grant"in e.principal?e.principal.grant:null)??(r==null?null:(await R(r))?.grant_id??null);if(await K(_e(await Ee(b,X,t.model)),{cwd:f,profileId:p},n.modelRegistry),await at(X)!=="app"&&!await ft(p))throw new u(412,"no_provider_credential",he,{error:"no_provider_credential",message:he,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=i===void 0||i.nodeId===null||i.state==="warm_claimed"?_t(v,f,p):null,j=l===null&&o.beforeBrokerLaunch===void 0?void 0:async S=>{l!==null&&await Tn(S,"terminal",l),o.beforeBrokerLaunch?.(S)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const S=A===null?null:await jn(A,i.nodeId,j);if(S===null)throw await te(i.requestKey,i.nodeId),new u(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await ie(i.requestKey,S),{status:201,body:await g(S)}}if(A!==null){const S=await Mn(A,{...d===void 0?{}:{deadlineAt:d},..._===void 0?{}:{outcomeDelivery:_},...i===void 0?{}:{requestKey:i.requestKey}},j);if(S!==null)return i!==void 0&&await ie(i.requestKey,S),fe(A),{status:201,body:await g(S)};M=A}const G=i?.nodeId??t.node_id??(i===void 0?void 0:await ne());i!==void 0&&i.nodeId===null&&await Ke(i.requestKey,G);const O=yt(G===void 0?v:{...v,node_id:G},r,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)),d!==void 0&&(O.deadlineAt=d),_!==void 0&&(O.outcomeDelivery=_),O.readiness=t.root===!0?"await":"launch";const Z=await Me(O,j,()=>{M!==null&&fe(M)});return i!==void 0&&await Be(i.requestKey,Z.node.node_id),{status:201,body:await g(Z.node.node_id)}}}s(D,"handleCreateRequest");function k(e,t){const n=e.query.getAll(t);if(n.length>1)throw w(`${t} must appear at most once`);return n[0]}s(k,"singleQueryValue");function ve(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw w(`${t} must be true or false`)}}s(ve,"optionalBoolean");function L(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw w(`${t} must be one of: ${n.join(", ")}`)}}s(L,"oneOf");function kt(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 w(`unknown nodes query parameter: ${b}`);const n=L(k(e,"status"),"status",["active","idle","done","dead","canceled"]),o=L(k(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=k(e,"kind"),d=L(k(e,"mode"),"mode",["base","orchestrator"]),a=k(e,"profile_id"),c=k(e,"profile_prefix"),r=k(e,"parent"),l=ve(k(e,"top_level"),"top_level"),p=k(e,"under"),m=ve(k(e,"hanging"),"hanging"),f=L(k(e,"include"),"include",["activity"]);if(r!==void 0&&l===!0)throw w("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...o!==void 0?{lifecycle:o}:{},...i!==void 0?{kind:i}:{},...d!==void 0?{mode:d}:{},...a!==void 0?{profile_id:a}:{},...c!==void 0?{profile_prefix:c}:{},...r!==void 0?{parent:r}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...m!==void 0?{hanging:m}:{},...f!==void 0?{include:f}:{}}}s(kt,"parseListQuery");async function St(e){const t=kt(e);let n=t.status!==void 0?await re({status:t.status}):await re();if(e.principal.class!=="person"&&(n=await Y(n,async a=>await we(e.principal,a.grantee??"app:terminal",a.node_id))),t.lifecycle!==void 0&&(n=n.filter(a=>a.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(a=>a.kind===t.kind)),t.mode!==void 0&&(n=n.filter(a=>a.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(a=>a.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(a=>a.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(a=>a.parent===t.parent)),t.top_level===!0&&(n=n.filter(a=>a.parent===null)),t.under!==void 0){const a=new Set(await ze(t.under));n=n.filter(c=>a.has(c.node_id))}t.hanging===!0&&(n=await Y(n,async a=>a.parent!==null&&await R(a.parent)===null));const o=t.include==="activity"?await qe(n.map(a=>a.node_id)):null,i=n.length>0?$e():new Set;return{status:200,body:await ye(n,async a=>{const c=await Hn(a,a.profile_id!==null&&i.has(a.profile_id));if(o!==null){const r=await ue(a.node_id);c.activity={latest_report:r[0]??null,final_report:a.final_report===null?null:r.find(l=>l.name===a.final_report)??null,pending_human_count:o[a.node_id]??0}}return c})}}s(St,"handleList");async function Rt(e){const t=e.params.id,n=await qn(e,t,{method:"GET",path:`/v1/nodes/${encodeURIComponent(t)}`,query:et(e)});if(n.kind==="unknown")throw tt(t,n.unreachable);if(n.kind==="remote"){if(n.status>=400)throw nt(n.status,n.body);return{status:n.status,body:it(n.body,n.machine)}}return await h(t),{status:200,body:await g(t)}}s(Rt,"handleDetail");async function Ot(e){const t=e.params.id;await h(t);const n=await cn(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(i=>({name:i.name,description:i.description,source:i.source})),captured_at:B()}}}s(Ot,"handleSnapshot");async function It(e){const t=e.params.id,n=await un(t);if(n===null)throw E(`unknown node: ${t}`,{received:t});return{status:200,body:n}}s(It,"handleSubject");function At(e){for(const[d]of e.query)if(d!=="cursor"&&d!=="limit")throw w(`unknown messages query parameter: ${d}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw w("cursor must appear at most once");if(n.length>1)throw w("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const o=n[0],i=Number(o);if(!Number.isSafeInteger(i)||o==="")throw w("limit must be an integer from 1 through 500");return t.length===0?{limit:i}:{cursor:t[0],limit:i}}s(At,"parseMessagesQuery");async function $t(e){const t=e.params.id,n=await sn(t,At(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()}}}s($t,"handleMessages");async function Ct(e){const t=e.params.id;await h(t);const n=await ln(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:B()}}}s(Ct,"handleSession");async function Nt(e){const t=e.params.id;return await h(t),{status:200,body:{node_id:t,markdown:await fn(t)}}}s(Nt,"handleTranscript");async function Tt(e){const t=e.params.id;await h(t);const n=s(async(i,d)=>({node_id:i,label:(await R(i))?.name??i,dir:await de(i),self:d,files:await ut(i)}),"root"),o=await Y([await n(t,!0),...await ye(await ae(t),async i=>await n(i.node_id,!1))],async i=>await Pt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:t,roots:o}}}s(Tt,"handleContext");async function Pt(e,t){try{return on(await V(e),t)}catch(n){if(an(n))return!1;throw n}}s(Pt,"hasDir");async function Et(e){const t=await h(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,o=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(d=>I(n,d)),...n.filter(d=>I(t.scopes,d))])],i=await De(t.node_id,o,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await g(i.node.node_id)}}s(Et,"handleFork");const Dt=1e4;async function Lt(e){const t=e.params.id;await h(t);const n=e.body,o=n?.resume??!0,i=n?.reopen??!1;await _n(t,i,e.principal.class==="broker"?e.principal.node:null);const d=!o&&n?.cron_id!==void 0?await pe(n.cron_id):null,a=await Pe(t,{resume:o,capacity:"refuse",...d!==null?{wakeReason:await zn(d,"schedule_revive")}:{}});a.outcome!=="already-live"&&await We(t,{failures:0,notBefore:null});const c=(await R(t))?.status??"active",r=(a.launch??P().get(t)?.handle)?.exited,l=a.outcome!=="frozen"&&await le(t,r,Dt);return{status:200,body:Qn(t,a,c,l)}}s(Lt,"handleRevive");async function Mt(e){const t=e.params.id;return{status:200,body:{newNodeId:(await yn(t))?.newNodeId??null}}}s(Mt,"handleRelaunchRoot");async function jt(e){const t=e.params.id;await h(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw w("caller_pid must be a positive integer when provided");const o=Jn(),i=new Promise(a=>{e.res.once("close",()=>a())}),d=await Te(t,{teardownAfter:i,rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...o===null?{}:{registerDetached:o.registerDetached}});return{status:200,body:Yn(d)}}s(jt,"handleClose");async function Gt(e){if(!Xn(e.principal))throw new u(403,"permission_error","only the person marks a conversation read");const t=e.params.id;return await h(t),await Je(t),{status:204}}s(Gt,"handleMarkRead");async function Ft(e){const t=e.params.id;await h(t);const n=await hn(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}s(Ft,"handleRecycle");async function Bt(e){const t=e.params.id;return await h(t),await x(t,{lifecycle:"terminal"}),await $(e,t,["lifecycle"]),{status:200,body:await g(t)}}s(Bt,"handleDemote");async function Kt(e,t={}){const n=e.params.id,o=await h(n),i=e.body??{};i.kind!==void 0&&await z(i.kind,o.cwd,o.profile_id??null),i.model!==void 0&&await ge(o,{kind:i.kind??o.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":o.lifecycle,model:i.model},t.modelRegistry);const d=await mn(n,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await $(e,n,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const a=await J(d.meta,await H(n));return a.roadmap_written=d.roadmapWritten,a.roadmap_ref=d.roadmapRef,a.goal_path=d.goalPath,{status:200,body:a}}s(Kt,"handlePromote");async function Wt(e,t={}){const n=e.params.id,o=await h(n),i=e.body??{};i.kind!==void 0&&await z(i.kind,o.cwd,o.profile_id??null),i.model!==void 0&&await ge(o,{kind:i.kind??o.kind,mode:i.promote===!0?"orchestrator":o.mode,lifecycle:o.lifecycle,model:i.model},t.modelRegistry);const d=i.note??"Refresh: continue against your roadmap or goal.";await gn(n,d);const a=await wn(n,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await J(a.meta,await H(n))}}s(Wt,"handleYield");async function Vt(e){const t=e.params.id;await h(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw w("a wait requires a controller node id");const o=await R(n.controller);if(o===null)throw E(`unknown controller: ${n.controller}`,{received:n.controller});if(o.status!=="active"&&o.status!=="idle")throw new u(422,"unprocessable",`controller ${n.controller} is ${o.status}`);return await xe(t,n.controller),{status:200,body:await g(t)}}s(Vt,"handleWait");async function xt(e){const t=e.principal,n=await pn(t.class==="broker"?async i=>i.grantee===t.app&&await U(t,i.node_id,i.grantee):void 0);return{status:200,body:{revived:[...n.revived],failed:[...n.failed],frozen:[...n.frozen]}}}s(xt,"handleReviveAll");const zt=new Set(["interrupt","steer","after-turn","next-turn"]);function Jt(e){if(e===null)return null;const t=s(o=>{throw new y({error:"invalid_listen",message:o,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[o,i]of n)/^(?:[1-9]|10)$/.test(o)||t(`listen level must be 1..10: ${o}`),(typeof i!="string"||!zt.has(i))&&t(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(n))}s(Jt,"listenJson");async function $(e,t,n,o){n.length===0&&o===void 0||await W(async i=>{if(o?.(i),n.length===0)return;const d=await Ue(i,t),a=await Qe(i,e),c=a.class==="person"?a.person:a.class==="app"?a.app:a.node;await Ye(i,c,d),await He(i,{event:"configured",object:d,actor:c,attrs:{changed:n.join(",")}})})}s($,"recordConfigured");function ke(e){const t=P().get(e);if(t===void 0)return!1;try{return process.kill(t.pid,"SIGTERM"),!0}catch{return!1}}s(ke,"restartLiveBroker");function Se(e,t){try{return q(e)===q(t)}catch{return!1}}s(Se,"sameDirectory");async function Ut(e,t={}){const n=e.params.id,o=e.body;let i;if(o===void 0)i={};else if(typeof o=="object"&&o!==null&&!Array.isArray(o))i=o;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:o,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(m=>m!=="profile"&&m!=="restart"&&i[m]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const r=await h(n),l=await Wn(e,i.profile);Vn(l.profileId);const p=xn(l.profileId).manifest.grantee??"app:terminal";if(p!==(r.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${l.profileId} belongs to ${p}, node ${n} to ${r.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(r.profile_id??null)!==l.profileId&&(Fn(r.kind)?(await z(r.kind,r.cwd,l.profileId),await x(n,{profileId:l.profileId})):await C(n,{profile_id:l.profileId}),await $(e,n,["profile"])),i.restart===!0&&ke(n),{status:200,body:await g(n)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const r=i.cwd;if(typeof r!="string"||r==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:r,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(f=>f!=="cwd"&&f!=="keep_session"&&f!=="restart"&&i[f]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const l=await h(n),p=N(l.cwd);if(i.keep_session===!0||p&&F(r)&&N(r)&&Se(l.cwd,r)){if(!F(r))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${r}`,received:r,field:"cwd",next:"Send an absolute path."});const f=T(r);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:r,field:"cwd",next:"Send an existing absolute directory."});if(p&&!Se(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:r,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:r,field:"cwd",next:"Reconcile the managed worktree first."});const v=l.cwd;return v!==f&&(await W(async _=>{await C(n,{cwd:f}),await _.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(f,n,v),await Xe(n,v,f)}),await $(e,n,["cwd"])),i.restart===!0&&ke(n),{status:200,body:await g(n)}}if(P().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:r,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:r,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:r,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:r,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(r))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${r}`,received:r,field:"cwd",next:"Send an absolute path."});const m=T(r);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:r,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:r,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:r,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await W(async()=>{await C(n,{cwd:m}),await Ze(n)}),await $(e,n,["cwd"]),{status:200,body:await g(n)}}let d=await h(n);const a=i.listen===void 0?void 0:Jt(i.listen);if(i.scopes!==void 0){const r=me(i.scopes),l=d.grantee==="app:terminal"?await dt():d.grant_id?await rt(d.grant_id):null,p=d.grantee==="app:terminal"&&!ct("user").runtime?.issuer;if(!r.every(m=>I(d.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:r,field:"scopes",next:"Send only scopes the node currently holds."});if(r.includes("crtr:act")&&!I(r,"crtr:llm"))throw new u(400,"invalid_scope","crtr:act requires crtr:llm");d=await C(n,{scopes:r})}if(i.situational_context!==void 0&&Ce(n,Ne(i.situational_context)),i.model!==void 0){const r=(await se(d.cwd,d.profile_id??null)).modelLadders,l=On(i.model,r),p=await st(d.grant_id,i.model,l===void 0),m=p?{family:lt,strength:p.strength}:l,f=p?p.model:In(i.model,r);await K({kind:"concrete",spec:f},{cwd:d.cwd,profileId:d.profile_id??null},t.modelRegistry);const b=P();let v=!1;if(b.isClaimed(n)&&await le(n,b.get(n)?.handle.exited)&&(v=await Cn(n,f,m).then(()=>!0,_=>{if(_ instanceof Nn)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:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!f.includes("/"))throw w(`model must resolve to a provider/id spec: ${i.model}`);await $n(n,f,m)}d=await h(n)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Oe(i.kind);const r=i.kind??d.kind,l=i.mode??d.mode,p=i.lifecycle??d.lifecycle;let m;l==="orchestrator"&&!await kn(n)&&(m=s(async()=>{const f=await bn(n);await vn(n,f!==null&&f.trim()!==""?{goal:f.trim()}:{})},"beforePersist")),d=await x(n,{...i.kind!==void 0?{kind:r}:{},...i.mode!==void 0?{mode:l}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},m)}i.name!==void 0&&(d=await C(n,{name:i.name}),d.window&&Sn(d.window,Kn(d)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(r=>i[r]!==void 0);return await $(e,n,c,a===void 0?void 0:async r=>{await r.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(a,n)}),{status:200,body:await g(n)}}s(Ut,"handleConfig");async function Re(){return(await se(process.cwd(),Ae()||null)).kinds}s(Re,"daemonKinds");async function Oe(e){const t=Object.keys(await Re());if(!t.includes(e))throw w(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}s(Oe,"assertKindServer");async function Yt(){const e=await Re();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}))}}}s(Yt,"handleListKinds");const wo=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:bt},{method:"GET",pattern:"/v1/nodes",handler:St},{method:"GET",pattern:"/v1/kinds",handler:s(()=>Yt(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:xt},{method:"GET",pattern:"/v1/nodes/:id",handler:Rt},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Ot},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:It},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:$t},{method:"GET",pattern:"/v1/nodes/:id/session",handler:Ct},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Nt},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Tt},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:Et},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Lt},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Mt},{method:"POST",pattern:"/v1/nodes/:id/close",handler:jt},{method:"POST",pattern:"/v1/nodes/:id/read",handler:Gt},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Ft},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Bt},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Kt},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Wt},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Vt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Ut}];export{Ut as handleConfig,bt as handleCreate,Et as handleFork,St as handleList,Kt as handlePromote,Wt as handleYield,wo as nodeRoutes,_o as resolveCreateKind};
|
|
1
|
+
var Ie=Object.defineProperty;var d=(e,n)=>Ie(e,"name",{value:n,configurable:!0});import{envProfileId as Oe}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 Pe,assertLaunchModelRegistered as K,forkNode as Ee,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 ie,findCreateRequest as Ge,getNode as R,recordCreateRequestNode as Fe,reserveCreateRequest as oe,reserveCreateRequestNode as Be,listNodes as Ke,recordRespawnAttempt as Ve,subscribersOf as We,subscriptionsOf as re,updateNode as C}from"../../../core/canvas/canvas.js";import{armControllerWait as xe}from"../../../core/canvas/waits.js";import{withCanvasWrite as V}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 ae,nodeAgentDir as W}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 an}from"../../../core/spaces/open-beneath.js";import{readNodeMessagesPage as dn,readNodeSession as sn,readNodeSnapshot as ln,transcriptMarkdown as cn}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as un}from"../../../core/substrate/subject.js";import{reviveAll as fn}from"../../../core/runtime/revive-all.js";import{promoteAsync as pn,requestYieldAsync as mn,reshapeNodeAsync as x}from"../../../core/runtime/promote.js";import{recycleNode as wn}from"../../../core/runtime/recycle.js";import{relaunchRoot as hn}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 In,readMergedLaunchConfigAsync as de}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as On}from"../../../core/model-routes.js";import{persistDormantModel as An,setModelLive as $n}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as se}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Cn}from"../../../core/runtime/broker-request.js";import{boundFleet as P}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 le}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Pn}from"../../../core/human/action-binding.js";import{resolveHumanAction as En}from"../../../core/human-actions.js";import{parseDurationMs as Dn}from"../../../core/wake.js";import{claimWarmNode as Ln,refillWarmPool as ce,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 Vn,loadExactProfileManifest as Wn}from"../../../core/profiles/manifest.js";import{getCron as fe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as xn}from"../../../core/runtime/bearings.js";import{boundDaemonControl as zn}from"../../control.js";import{notFound as E,usage as w}from"../../../core/errors.js";import{assertScope as Jn,validateScopes as pe}from"../../../core/scopes.js";import{scopeAllowed as O}from"../../../shared/env.js";import{toCloseResultDTO as Un,toNodeDetailDTO as J,toNodeSummaryDTO as Yn,toReviveResultDTO as Hn}from"../map.js";import{ApiError as f}from"../../../api/index.js";import{InputError as y}from"../../../core/io.js";import{actsAsPerson as Qn,brokerMayReach as U,canReadNode as me,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 it}from"../../../core/spaces/file-root.js";import{activeGrant as ot,payerOfGrant as rt,terminalGrant as at}from"../../../core/grants/mirror.js";import{appRungForGrant as dt}from"../../../core/llm/app-rungs.js";import{APP_FAMILY as st}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";import{filterAsync as he,mapAsync as ye}from"../../../core/async-array.js";async function h(e){const n=await R(e);if(n===null)throw E(`unknown node: ${e}`,{received:e});return n}d(h,"requireMeta");async function Y(e){return{subscribesTo:await re(e),subscribers:await We(e),children:await je(e)}}d(Y,"edgesFor");async function b(e){const n=await h(e);return await J(n,await Y(e))}d(b,"detailOf");async function ut(e){let n=(await ue(e)).length;try{n+=an(await W(e),await ae(e)).length}catch(t){if(!on(t))throw t}return n}d(ut,"countFiles");function ft(e){if(typeof e!="object"||e===null)throw w("a node create requires a JSON body");const n=e;if(n.kind!==void 0&&(typeof n.kind!="string"||n.kind.trim()===""))throw w("kind must be a non-empty string when provided");if(n.description!==void 0&&(typeof n.description!="string"||n.description.trim()===""))throw w("description must be a non-empty string when provided");if(n.creator!==void 0&&(typeof n.creator!="string"||n.creator.trim()===""))throw w("creator must be a non-empty node id when provided");if(n.scopes!==void 0&&pe(n.scopes),n.isolated!==void 0&&typeof n.isolated!="boolean")throw new f(400,"invalid_request","isolated must be a boolean",{param:"isolated"});const t=n.root_lifecycle;if(t!==void 0&&t!=="resident"&&t!=="terminal")throw w("root_lifecycle must be 'resident' or 'terminal'");if(n.request_key!==void 0&&(typeof n.request_key!="string"||n.request_key.trim()===""||n.request_key.length>128))throw w("request_key must be a non-empty string of at most 128 characters when provided");return n}d(ft,"parseCreateBody");function pt(e){if(e===void 0)return;const n=Dn(e),t=n===null?null:new Date(Date.now()+n);if(n===null||!Number.isFinite(n)||n<=0||t===null||!Number.isFinite(t.getTime()))throw new f(422,"invalid_deadline","`deadline` must be a positive representable duration");return t.toISOString()}d(pt,"parseDeadline");function mt(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new f(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Pn.test(e.action))throw new f(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let n;try{n=JSON.stringify(e.payload)}catch{throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(n===void 0)throw new f(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(n,"utf8")>le)throw new f(413,"payload_too_large",`serialized payload exceeds ${le} bytes`)}return e}}d(mt,"parseOutcomeDelivery");function wt(e,n){const t=En(e.action,n);if(!("kind"in t))return{actionName:e.action,argv:t.argv,cwd:t.cwd,configOrigin:t.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw t.kind==="unknown_action"?new f(422,"unknown_action",`no action named ${e.action} is declared from ${n}`):new f(422,"invalid_action",`${e.action} is declared in ${t.configOrigin} but unusable: ${t.reason}`,{reason:t.reason,configOrigin:t.configOrigin})}d(wt,"resolveOutcomeDelivery");function ht(e,n,t){const o={kind:e.kind,cwd:t,prompt:e.prompt??""};return e.mode!==void 0&&(o.mode=e.mode),e.name!==void 0&&(o.name=e.name),e.description!==void 0&&(o.description=e.description),n!==void 0&&(o.parent=n),e.creator!==void 0&&(o.creator=e.creator),e.scopes!==void 0&&(o.scopes=e.scopes),e.isolated!==void 0&&(o.isolated=e.isolated),e.root===!0&&(o.root=!0),e.root_lifecycle!==void 0&&(o.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(o.worktree=!0),typeof e.worktree=="string"&&(o.worktreeBase=e.worktree),e.worktree!==void 0&&(o.worktreeCwd=T(e.pin_cwd??e.cwd??t)),e.fork_from!==void 0&&(o.forkFrom=e.fork_from),e.model!==void 0&&(o.model=e.model),e.profile!==void 0&&(o.profile=e.profile),e.situational_context!==void 0&&(o.situationalContext=e.situational_context),e.node_id!==void 0&&(o.nodeId=e.node_id),o}d(ht,"buildRecipe");function yt(e,n,t){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:n,profileId:t,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(yt,"warmRequestFor");import{resolveCreateKind as ho}from"../../../core/runtime/launch-target.js";function _e(e){const n=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return On(e.model,n,e.modelExact===!0)}d(_e,"requestFromLaunch");function _t(e,n){if(n===null)return e;if(e.scopes===void 0)return{...e,scopes:[...n]};const t=e.scopes.filter(o=>!O(n,o));if(t.length===0)return e;throw new f(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${t.join(", ")}`,{scopes:t,ceiling:n})}d(_t,"withinCeiling");async function ge(e,n,t){const o=(await Sn(n.kind,n.mode,{lifecycle:n.lifecycle,hasManager:e.parent!==null,model:n.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await K(_e(o),{cwd:e.cwd,profileId:e.profile_id??null},t)}d(ge,"assertNodeModelChangeRegistered");async function be(e,n){const t=e.principal;if(t.class!=="broker"&&t.class!=="cron")return;const o=it({app:t.app,resolved:await Xn(t),launched:t.scopes},n,"read");if("root"in o)return;const i="missing"in o?o.missing:null;throw new f(403,"scope_missing",i?`the child's directory ${n} needs missing scope ${i}`:`no permission of this run names the child's directory ${n}`,void 0,void 0,i?{scope:i}:void 0)}d(be,"assertCallerReaches");const H=new Map;async function gt(e,n={},t={}){const o=_t(ft(e.body),e.ceiling);if(e.principal.class==="broker"){const c=e.principal;if(o.prefer_warm===!0&&c.app!=="app:terminal"&&(o.prefer_warm=!1),o.parent!=null){const r=await h(o.parent);if(r.grantee!==c.app)throw new f(403,"other_app_run","cannot create a child under another app's node");if(!await U(c,o.parent,r.grantee??"app:terminal"))throw E(`unknown node: ${o.parent}`,{received:o.parent})}if(o.creator!==void 0&&o.creator!==c.node)throw new f(403,"other_app_run","cannot create for another node");if(o.fork_from!==void 0){let r=null;try{r=await Me(await De(o.fork_from))}catch{}if(r?.grantee!==c.app||!await U(c,r.node_id,r.grantee))throw new f(403,"other_app_run","cannot fork another app's conversation")}o.creator=c.node}if(e.principal.class==="cron"){const c=e.principal;for(const s of["parent","creator","fork_from","node_id"])if(o[s]!=null)throw new f(403,"permission_error",`a cron cannot set ${s} on a node it starts`);o.prefer_warm=!1;const r=await en({grantee:c.app,sub:c.sub,grant_id:c.grant,scopes:c.scopes});if(!r.allowed)throw new f(r.reason==="scope_missing"?403:401,r.reason==="scope_missing"?"scope_missing":"grant_revoked",r.message);if(o.scopes!==void 0){const s=o.scopes.find(p=>!O(r.effectiveScopes,p)||!O(c.scopes,p));if(s!==void 0)throw new f(403,"scope_missing",`scope ${s} is not held by this cron`,void 0,void 0,{scope:s})}else c.scopes!==null&&(o.scopes=[...c.scopes]);o.node_id=await ne(),c.isolated&&(o.isolated=!0,o.cwd=await W(o.node_id,c.app))}o.creator!==void 0&&Jn(await h(o.creator),"crtr:act");const i=o.request_key?.trim();if(i===void 0||o.node_id!==void 0&&qe(o.node_id)&&await R(o.node_id)!==null&&(await Ge(i))?.nodeId!==o.node_id)return D(e,o,n,t);const a=H.get(i);if(a!==void 0)return a;const l=bt(e,o,i,n,t);H.set(i,l);try{return await l}finally{H.delete(i)}}d(gt,"handleCreate");async function bt(e,n,t,o,i){const a=await oe(t);if(a.nodeId!==null&&await R(a.nodeId)!==null){if(a.state!=="warm_claimed"){const l=await R(a.nodeId);if(e.principal.class!=="person"&&!await me(e.principal,l.grantee??"app:terminal",a.nodeId))throw new f(409,"create_request_conflict","request_key belongs to another caller");return{status:201,body:await b(a.nodeId)}}return D(e,n,o,i,a)}try{return await D(e,n,o,i,a)}catch(l){const c=await oe(t);throw(c.nodeId===null||await R(c.nodeId)===null)&&await te(t,c.nodeId),l}}d(bt,"handleKeyedCreateRequest");async function D(e,n,t,o,i=void 0){const a=o.deadlineAt??pt(n.deadline),l=mt(n.outcome_delivery),c=e.principal.class==="cron"?await 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:(await fe(e.principal.cron))?.created_by??null},n.node_id):null;c!==null&&(n.root=c.root===!0);const r=c?.parent??n.parent??void 0;if(r==null&&n.root!==!0)throw w("a node create requires a parent (or root: true for an independent root)");let s=null;if(n.output_schema!==void 0){try{s=JSON.parse(n.output_schema)}catch{throw w("output_schema must be a JSON schema string")}if(s===null||typeof s!="object"||Array.isArray(s))throw w("output_schema must be a JSON schema object");await Tn(s)}const{profileId:p,kind:m,cwd:u,launch:k}=await Fn(n,{validateKind:Re});await be(e,u),n.worktree!==void 0&&await be(e,T(n.pin_cwd??n.cwd??u));const _={...n,kind:m},g=l===void 0?void 0:wt(l,u),X=("grant"in e.principal?e.principal.grant:null)??(r==null?null:(await R(r))?.grant_id??null);if(await K(_e(await Pe(k,X,n.model)),{cwd:u,profileId:p},t.modelRegistry),await rt(X)!=="app"&&!await ct(p))throw new f(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=i===void 0||i.nodeId===null||i.state==="warm_claimed"?yt(_,u,p):null,j=s===null&&o.beforeBrokerLaunch===void 0?void 0:async S=>{s!==null&&await Nn(S,"terminal",s),o.beforeBrokerLaunch?.(S)};if(i?.state==="warm_claimed"&&i.nodeId!==null){const S=A===null?null:await Mn(A,i.nodeId,j);if(S===null)throw await te(i.requestKey,i.nodeId),new f(503,"create_resume_failed",`could not resume warm claim ${i.nodeId}; retry the create`);return await ie(i.requestKey,S),{status:201,body:await b(S)}}if(A!==null){const S=await Ln(A,{...a===void 0?{}:{deadlineAt:a},...g===void 0?{}:{outcomeDelivery:g},...i===void 0?{}:{requestKey:i.requestKey}},j);if(S!==null)return i!==void 0&&await ie(i.requestKey,S),ce(A),{status:201,body:await b(S)};M=A}const G=i?.nodeId??n.node_id??(i===void 0?void 0:await ne());i!==void 0&&i.nodeId===null&&await Be(i.requestKey,G);const I=ht(G===void 0?_:{..._,node_id:G},r,u);c!==null&&(c.rootLifecycle!==void 0&&(I.rootLifecycle=c.rootLifecycle),c.scopes!==void 0&&_.scopes===void 0&&(I.scopes=c.scopes),c.run!==void 0&&(I.run=c.run),c.withinCreate!==void 0&&(I.withinCreate=c.withinCreate)),a!==void 0&&(I.deadlineAt=a),g!==void 0&&(I.outcomeDelivery=g),I.readiness=n.root===!0?"await":"launch";const Z=await Le(I,j,()=>{M!==null&&ce(M)});return i!==void 0&&await Fe(i.requestKey,Z.node.node_id),{status:201,body:await b(Z.node.node_id)}}}d(D,"handleCreateRequest");function v(e,n){const t=e.query.getAll(n);if(t.length>1)throw w(`${n} must appear at most once`);return t[0]}d(v,"singleQueryValue");function Q(e,n){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw w(`${n} must be true or false`)}}d(Q,"optionalBoolean");function L(e,n,t){if(e!==void 0){if(t.includes(e))return e;throw w(`${n} must be one of: ${t.join(", ")}`)}}d(L,"oneOf");function vt(e){const n=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","under_inclusive","hanging","include"]);for(const[_]of e.query)if(!n.has(_))throw w(`unknown nodes query parameter: ${_}`);const t=L(v(e,"status"),"status",["active","idle","done","dead","canceled"]),o=L(v(e,"lifecycle"),"lifecycle",["terminal","resident"]),i=v(e,"kind"),a=L(v(e,"mode"),"mode",["base","orchestrator"]),l=v(e,"profile_id"),c=v(e,"profile_prefix"),r=v(e,"parent"),s=Q(v(e,"top_level"),"top_level"),p=v(e,"under"),m=Q(v(e,"under_inclusive"),"under_inclusive"),u=Q(v(e,"hanging"),"hanging"),k=L(v(e,"include"),"include",["activity"]);if(r!==void 0&&s===!0)throw w("parent and top_level=true cannot be combined");return{...t!==void 0?{status:t}:{},...o!==void 0?{lifecycle:o}:{},...i!==void 0?{kind:i}:{},...a!==void 0?{mode:a}:{},...l!==void 0?{profile_id:l}:{},...c!==void 0?{profile_prefix:c}:{},...r!==void 0?{parent:r}:{},...s!==void 0?{top_level:s}:{},...p!==void 0?{under:p}:{},...m!==void 0?{under_inclusive:m}:{},...u!==void 0?{hanging:u}:{},...k!==void 0?{include:k}:{}}}d(vt,"parseListQuery");async function kt(e){const n=vt(e);let t=await Ke({...n.status!==void 0?{status:n.status}:{},...n.lifecycle!==void 0?{lifecycle:n.lifecycle}:{},...n.kind!==void 0?{kind:n.kind}:{},...n.mode!==void 0?{mode:n.mode}:{},...n.profile_id!==void 0?{profileId:n.profile_id}:{},...n.profile_prefix!==void 0?{profilePrefix:n.profile_prefix}:{},...n.parent!==void 0?{parent:n.parent}:{},...n.top_level===!0?{topLevel:!0}:{},...n.under!==void 0?{under:n.under}:{},...n.under_inclusive===!0?{underInclusive:!0}:{},...n.hanging===!0?{hanging:!0}:{}});e.principal.class!=="person"&&(t=await he(t,async l=>await me(e.principal,l.grantee??"app:terminal",l.node_id)));const o=n.include==="activity"?await Ze(t.map(l=>l.node_id)):null,i=t.length>0?Ae():new Set;return{status:200,body:await ye(t,async l=>{const c=await Yn(l,l.profile_id!==null&&i.has(l.profile_id));if(o!==null){const r=await ue(l.node_id);c.activity={latest_report:r[0]??null,final_report:l.final_report===null?null:r.find(s=>s.name===l.final_report)??null,pending_human_count:o[l.node_id]??0}}return c})}}d(kt,"handleList");async function St(e){const n=e.params.id,t=await Zn(e,n,{method:"GET",path:`/v1/nodes/${encodeURIComponent(n)}`,query:qn(e)});if(t.kind==="unknown")throw nt(n,t.unreachable);if(t.kind==="remote"){if(t.status>=400)throw et(t.status,t.body);return{status:t.status,body:tt(t.body,t.machine)}}return await h(n),{status:200,body:await b(n)}}d(St,"handleDetail");async function Rt(e){const n=e.params.id;await h(n);const t=await ln(n);return{status:200,body:{node_id:n,snapshot:{messages:t.snapshot.messages,...t.snapshot.messageIds===void 0?{}:{messageIds:t.snapshot.messageIds},messageVisibility:t.snapshot.messageVisibility,turnVisibility:t.snapshot.turnVisibility,stats:t.snapshot.stats,state:t.snapshot.state,display:t.snapshot.display,...t.snapshot.queued===void 0?{}:{queued:t.snapshot.queued},...t.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:t.snapshot.toolGroupSummaries},...t.snapshot.turnReplies===void 0?{}:{turnReplies:t.snapshot.turnReplies},...t.snapshot.workingActivity===void 0?{}:{workingActivity:t.snapshot.workingActivity}},commands:t.commands.map(i=>({name:i.name,description:i.description,source:i.source})),captured_at:B()}}}d(Rt,"handleSnapshot");async function It(e){const n=e.params.id,t=await un(n);if(t===null)throw E(`unknown node: ${n}`,{received:n});return{status:200,body:t}}d(It,"handleSubject");function Ot(e){for(const[a]of e.query)if(a!=="cursor"&&a!=="limit")throw w(`unknown messages query parameter: ${a}`);const n=e.query.getAll("cursor"),t=e.query.getAll("limit");if(n.length>1)throw w("cursor must appear at most once");if(t.length>1)throw w("limit must appear at most once");if(t.length===0)return n.length===0?{}:{cursor:n[0]};const o=t[0],i=Number(o);if(!Number.isSafeInteger(i)||o==="")throw w("limit must be an integer from 1 through 500");return n.length===0?{limit:i}:{cursor:n[0],limit:i}}d(Ot,"parseMessagesQuery");async function At(e){const n=e.params.id,t=await dn(n,Ot(e));return{status:200,body:{node_id:n,messages:t.messages,...t.messageIds===void 0?{}:{message_ids:t.messageIds},message_visibility:t.messageVisibility,next_cursor:t.nextCursor,captured_at:B()}}}d(At,"handleMessages");async function $t(e){const n=e.params.id;await h(n);const t=await sn(n);return{status:200,body:{node_id:n,session_file:t.sessionFile,session_jsonl:t.sessionJsonl,system_prompt:t.systemPrompt,captured_at:B()}}}d($t,"handleSession");async function Ct(e){const n=e.params.id;return await h(n),{status:200,body:{node_id:n,markdown:await cn(n)}}}d(Ct,"handleTranscript");async function Nt(e){const n=e.params.id;await h(n);const t=d(async(i,a)=>({node_id:i,label:(await R(i))?.name??i,dir:await ae(i),self:a,files:await ut(i)}),"root"),o=await he([await t(n,!0),...await ye(await re(n),async i=>await t(i.node_id,!1))],async i=>await Tt(i.node_id,i.dir)||i.files>0);return{status:200,body:{node_id:n,roots:o}}}d(Nt,"handleContext");async function Tt(e,n){try{return tn(await W(e),n)}catch(t){if(rn(t))return!1;throw t}}d(Tt,"hasDir");async function Pt(e){const n=await h(e.params.id),t=e.principal.class==="broker"?e.principal.scopes:e.ceiling,o=t===null?void 0:n.scopes==null?[...t]:[...new Set([...n.scopes.filter(a=>O(t,a)),...t.filter(a=>O(n.scopes,a))])],i=await Ee(n.node_id,o,e.principal.class==="broker"?e.principal.node:void 0);return{status:201,body:await b(i.node.node_id)}}d(Pt,"handleFork");const Et=1e4;async function Dt(e){const n=e.params.id;await h(n);const t=e.body,o=t?.resume??!0,i=t?.reopen??!1;await yn(n,i,e.principal.class==="broker"?e.principal.node:null);const a=!o&&t?.cron_id!==void 0?await fe(t.cron_id):null,l=await Te(n,{resume:o,capacity:"refuse",...a!==null?{wakeReason:await xn(a,"schedule_revive")}:{}});l.outcome!=="already-live"&&await Ve(n,{failures:0,notBefore:null});const c=(await R(n))?.status??"active",r=(l.launch??P().get(n)?.handle)?.exited,s=l.outcome!=="frozen"&&await se(n,r,Et);return{status:200,body:Hn(n,l,c,s)}}d(Dt,"handleRevive");async function Lt(e){const n=e.params.id;return{status:200,body:{newNodeId:(await hn(n))?.newNodeId??null}}}d(Lt,"handleRelaunchRoot");async function Mt(e){const n=e.params.id;await h(n);const t=e.body;if(t?.caller_pid!==void 0&&(!Number.isInteger(t.caller_pid)||t.caller_pid<=0))throw w("caller_pid must be a positive integer when provided");const o=zn(),i=new Promise(l=>{e.res.once("close",()=>l())}),a=await Ne(n,{teardownAfter:i,rootEvent:t?.finish===!0?"finish":"cancel",callerPid:t?.caller_pid,...e.principal.class==="broker"?{closer:e.principal.node}:{},...o===null?{}:{registerDetached:o.registerDetached}});return{status:200,body:Un(a)}}d(Mt,"handleClose");async function jt(e){if(!Qn(e.principal))throw new f(403,"permission_error","only the person marks a conversation read");const n=e.params.id;return await h(n),await ze(n),{status:204}}d(jt,"handleMarkRead");async function Gt(e){const n=e.params.id;await h(n);const t=await wn(n);return{status:200,body:{recycled:t.recycled,finalized:t.finalized,new_root:t.newRoot,delivered:t.delivered}}}d(Gt,"handleRecycle");async function Ft(e){const n=e.params.id;return await h(n),await x(n,{lifecycle:"terminal"}),await $(e,n,["lifecycle"]),{status:200,body:await b(n)}}d(Ft,"handleDemote");async function Bt(e,n={}){const t=e.params.id,o=await h(t),i=e.body??{};i.kind!==void 0&&await z(i.kind,o.cwd,o.profile_id??null),i.model!==void 0&&await ge(o,{kind:i.kind??o.kind,mode:"orchestrator",lifecycle:i.resident===!0?"resident":o.lifecycle,model:i.model},n.modelRegistry);const a=await pn(t,{...i.kind!==void 0?{kind:i.kind}:{},...i.resident===!0?{resident:!0}:{},...i.model!==void 0?{model:i.model}:{}});await $(e,t,["mode",...i.kind!==void 0?["kind"]:[],...i.resident===!0?["lifecycle"]:[],...i.model!==void 0?["model"]:[]]);const l=await J(a.meta,await Y(t));return l.roadmap_written=a.roadmapWritten,l.roadmap_ref=a.roadmapRef,l.goal_path=a.goalPath,{status:200,body:l}}d(Bt,"handlePromote");async function Kt(e,n={}){const t=e.params.id,o=await h(t),i=e.body??{};i.kind!==void 0&&await z(i.kind,o.cwd,o.profile_id??null),i.model!==void 0&&await ge(o,{kind:i.kind??o.kind,mode:i.promote===!0?"orchestrator":o.mode,lifecycle:o.lifecycle,model:i.model},n.modelRegistry);const a=i.note??"Refresh: continue against your roadmap or goal.";await _n(t,a);const l=await mn(t,{...i.promote===!0?{promote:!0}:{},...i.kind!==void 0?{kind:i.kind}:{},...i.model!==void 0?{model:i.model}:{}});return{status:200,body:await J(l.meta,await Y(t))}}d(Kt,"handleYield");async function Vt(e){const n=e.params.id;await h(n);const t=e.body;if(t===void 0||typeof t.controller!="string"||t.controller.trim()==="")throw w("a wait requires a controller node id");const o=await R(t.controller);if(o===null)throw E(`unknown controller: ${t.controller}`,{received:t.controller});if(o.status!=="active"&&o.status!=="idle")throw new f(422,"unprocessable",`controller ${t.controller} is ${o.status}`);return await xe(n,t.controller),{status:200,body:await b(n)}}d(Vt,"handleWait");async function Wt(e){const n=e.principal,t=await fn(n.class==="broker"?async i=>i.grantee===n.app&&await U(n,i.node_id,i.grantee):void 0);return{status:200,body:{revived:[...t.revived],failed:[...t.failed],frozen:[...t.frozen]}}}d(Wt,"handleReviveAll");const xt=new Set(["interrupt","steer","after-turn","next-turn"]);function zt(e){if(e===null)return null;const n=d(o=>{throw new y({error:"invalid_listen",message:o,received:e,field:"listen",next:'Send an object mapping levels "1".."10" to interrupt|steer|after-turn|next-turn (e.g. {"3":"next-turn"}), or null to reset to the global default.'})},"bad");if(typeof e!="object"||Array.isArray(e))return n("listen must be an object or null");const t=Object.entries(e);if(t.length===0)return n("listen must name at least one level");for(const[o,i]of t)/^(?:[1-9]|10)$/.test(o)||n(`listen level must be 1..10: ${o}`),(typeof i!="string"||!xt.has(i))&&n(`listen delivery must be interrupt|steer|after-turn|next-turn: ${String(i)}`);return JSON.stringify(Object.fromEntries(t))}d(zt,"listenJson");async function $(e,n,t,o){t.length===0&&o===void 0||await V(async i=>{if(o?.(i),t.length===0)return;const a=await Je(i,n),l=await He(i,e),c=l.class==="person"?l.person:l.class==="app"?l.app:l.node;await Ue(i,c,a),await Ye(i,{event:"configured",object:a,actor:c,attrs:{changed:t.join(",")}})})}d($,"recordConfigured");function ve(e){const n=P().get(e);if(n===void 0)return!1;try{return process.kill(n.pid,"SIGTERM"),!0}catch{return!1}}d(ve,"restartLiveBroker");function ke(e,n){try{return q(e)===q(n)}catch{return!1}}d(ke,"sameDirectory");async function Jt(e,n={}){const t=e.params.id,o=e.body;let i;if(o===void 0)i={};else if(typeof o=="object"&&o!==null&&!Array.isArray(o))i=o;else throw new y({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:o,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(i.profile!==void 0){if(typeof i.profile!="string"||i.profile==="")throw new y({error:"profile_invalid",message:"profile must be a non-empty profile id or name",received:i.profile,field:"profile",next:"Send a profile id or exact name."});if(Object.keys(i).some(m=>m!=="profile"&&m!=="restart"&&i[m]!==void 0))throw new y({error:"profile_not_exclusive",message:"profile can only be combined with restart",field:"profile",next:"Send profile (and optionally restart) alone."});const r=await h(t),s=await Kn(e,i.profile);Vn(s.profileId);const p=Wn(s.profileId).manifest.grantee??"app:terminal";if(p!==(r.grantee??"app:terminal"))throw new y({error:"profile_grantee_mismatch",message:`profile ${s.profileId} belongs to ${p}, node ${t} to ${r.grantee}`,received:i.profile,field:"profile",next:"Pick a profile owned by the same app as the node."});return(r.profile_id??null)!==s.profileId&&(Gn(r.kind)?(await z(r.kind,r.cwd,s.profileId),await x(t,{profileId:s.profileId})):await C(t,{profile_id:s.profileId}),await $(e,t,["profile"])),i.restart===!0&&ve(t),{status:200,body:await b(t)}}if(Object.prototype.hasOwnProperty.call(i,"cwd")){const r=i.cwd;if(typeof r!="string"||r==="")throw new y({error:"cwd_invalid",message:"cwd must be a non-empty string",received:r,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(i).some(u=>u!=="cwd"&&u!=="keep_session"&&u!=="restart"&&i[u]!==void 0))throw new y({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:i,field:"cwd",next:"Send cwd as the only config field."});const s=await h(t),p=N(s.cwd);if(i.keep_session===!0||p&&F(r)&&N(r)&&ke(s.cwd,r)){if(!F(r))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${r}`,received:r,field:"cwd",next:"Send an absolute path."});const u=T(r);let k=!1;try{k=ee(u).isDirectory()}catch{}if(!k)throw new y({error:"cwd_missing",message:`cwd is not an existing directory: ${u}`,received:r,field:"cwd",next:"Send an existing absolute directory."});if(p&&!ke(s.cwd,u))throw new y({error:"cwd_not_same_directory",message:`${u} is not the same directory as the recorded ${s.cwd}; --keep-session only relocates an alias`,received:r,field:"cwd",next:"Drop --keep-session to repair a gone cwd, or pass the real path of the recorded directory."});if(s.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot relocate its cwd`,received:r,field:"cwd",next:"Reconcile the managed worktree first."});const _=s.cwd;return _!==u&&(await V(async g=>{await C(t,{cwd:u}),await g.prepare("UPDATE crons SET cwd = ? WHERE anchor_node = ? AND cwd = ?").run(u,t,_),await Qe(t,_,u)}),await $(e,t,["cwd"])),i.restart===!0&&ve(t),{status:200,body:await b(t)}}if(P().has(t)){const u=`${t} cannot repair its cwd while its broker is live`;throw new f(409,"cwd_node_live",u,{error:"cwd_node_live",message:u,received:r,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(s.fork_from!=null)throw new y({error:"cwd_node_forked",message:`${t} is a fork and cannot repair its cwd; recorded cwd: ${s.cwd}`,received:r,field:"cwd",next:`Restore ${s.cwd}, then revive the fork normally.`});if(s.managed_worktree?.state==="open")throw new y({error:"cwd_node_managed_worktree_open",message:`${t} owns an open managed worktree and cannot repair its cwd`,received:r,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(N(s.cwd))throw new y({error:"cwd_still_present",message:`${t} recorded cwd still exists: ${s.cwd}; cwd repair is not a relocation command`,received:r,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!F(r))throw new y({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${r}`,received:r,field:"cwd",next:"Send an absolute path."});const m=T(r);if(!N(m))throw new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:r,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:r,field:"cwd",next:"Send an existing absolute directory."})}catch(u){throw u instanceof y?u:new y({error:"cwd_missing",message:`cwd does not exist: ${m}`,received:r,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return await V(async()=>{await C(t,{cwd:m}),await Xe(t)}),await $(e,t,["cwd"]),{status:200,body:await b(t)}}let a=await h(t);const l=i.listen===void 0?void 0:zt(i.listen);if(i.scopes!==void 0){const r=pe(i.scopes),s=a.grantee==="app:terminal"?await at():a.grant_id?await ot(a.grant_id):null,p=a.grantee==="app:terminal"&&!lt("user").runtime?.issuer;if(!r.every(m=>O(a.scopes,m)&&(s?O(s.resolved,m):p)))throw new y({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:r,field:"scopes",next:"Send only scopes the node currently holds."});if(r.includes("crtr:act")&&!O(r,"crtr:llm"))throw new f(400,"invalid_scope","crtr:act requires crtr:llm");a=await C(t,{scopes:r})}if(i.situational_context!==void 0&&$e(t,Ce(i.situational_context)),i.model!==void 0){const r=(await de(a.cwd,a.profile_id??null)).modelLadders,s=Rn(i.model,r),p=await dt(a.grant_id,i.model,s===void 0),m=p?{family:st,strength:p.strength}:s,u=p?p.model:In(i.model,r);await K({kind:"concrete",spec:u},{cwd:a.cwd,profileId:a.profile_id??null},n.modelRegistry);const k=P();let _=!1;if(k.isClaimed(t)&&await se(t,k.get(t)?.handle.exited)&&(_=await $n(t,u,m).then(()=>!0,g=>{if(g instanceof Cn)return!1;throw g})),!_){if(k.isClaimed(t)){const g=`${t}'s broker did not accept the model switch; the model was not changed`;throw new f(409,"broker_not_ready",g,{error:"broker_not_ready",message:g,received:i.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!u.includes("/"))throw w(`model must resolve to a provider/id spec: ${i.model}`);await An(t,u,m)}a=await h(t)}if(i.kind!==void 0||i.mode!==void 0||i.lifecycle!==void 0){i.kind!==void 0&&await Re(i.kind);const r=i.kind??a.kind,s=i.mode??a.mode,p=i.lifecycle??a.lifecycle;let m;s==="orchestrator"&&!await vn(t)&&(m=d(async()=>{const u=await gn(t);await bn(t,u!==null&&u.trim()!==""?{goal:u.trim()}:{})},"beforePersist")),a=await x(t,{...i.kind!==void 0?{kind:r}:{},...i.mode!==void 0?{mode:s}:{},...i.lifecycle!==void 0?{lifecycle:p}:{}},m)}i.name!==void 0&&(a=await C(t,{name:i.name}),a.window&&kn(a.window,Bn(a)));const c=["scopes","situational_context","model","kind","mode","lifecycle","name","listen"].filter(r=>i[r]!==void 0);return await $(e,t,c,l===void 0?void 0:async r=>{await r.prepare("UPDATE objects SET listen_json = ? WHERE id = ? AND type = 'node'").run(l,t)}),{status:200,body:await b(t)}}d(Jt,"handleConfig");async function Se(){return(await de(process.cwd(),Oe()||null)).kinds}d(Se,"daemonKinds");async function Re(e){const n=Object.keys(await Se());if(!n.includes(e))throw w(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${n.sort().join(", ")}.`})}d(Re,"assertKindServer");async function Ut(){const e=await Se();return{status:200,body:{kinds:Object.keys(e).sort().map(t=>({kind:t,when_to_use:e[t]?.whenToUse??null,available_to:e[t]?.availableTo??null}))}}}d(Ut,"handleListKinds");const po=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:gt},{method:"GET",pattern:"/v1/nodes",handler:kt},{method:"GET",pattern:"/v1/kinds",handler:d(()=>Ut(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:Wt},{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:It},{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:Pt},{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:Vt},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Jt}];export{Jt as handleConfig,gt as handleCreate,Pt as handleFork,kt as handleList,Bt as handlePromote,Kt as handleYield,po as nodeRoutes,ho as resolveCreateKind};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var Ne=Object.defineProperty;var l=(e,t)=>Ne(e,"name",{value:t,configurable:!0});import{ApiError as
|
|
2
|
-
content unavailable: ${r.unavailable}`,data:{...f,content:"markdown"in r?"live":"unavailable"}}})}l(et,"read");function Y(e,t,a,n){if(e!=null){if(!a.includes(e)){n.push({field:t,problem:`must be one of ${a.join(", ")}`,received:e});return}return e}}l(Y,"oneOf");async function ge(e,t,a){if(t!=null){if(typeof t!="string"||!await Ce(e,t)){a.push({field:"type",problem:`must be a kind: one of ${(await De(e)).join(", ")}`,received:t});return}return t}}l(ge,"kindName");function je(e,t,a,n){if(e==null)return n;const i=Number(e);return!Number.isInteger(i)||i<1||i>100?(a.push({field:t,problem:"must be an integer from 1 to 100",received:e}),n):i}l(je,"limitOf");async function _e(e){const t=e.query,a=[],n=await ge(await I(),t.get("type"),a),i=Y(t.get("privacy"),"privacy",$e,a),o=je(t.get("limit"),"limit",a,50),r=t.get("cursor");r!==null&&!/^\d+$/.test(r)&&a.push({field:"cursor",problem:"is not a cursor from a previous page",received:r});const s=t.get("deleted");return s!==null&&!["0","1","true","false"].includes(s)&&a.push({field:"deleted",problem:"must be true or false",received:s}),a.length>0&&C("object list request",a),await _(async c=>{const u=await v(c,e),f={...n?{type:n}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...s==="1"||s==="true"?{deleted:!0}:{}},h=t.get("owner");if(h!==null){const w=await he(c,u,h);if(w===null)return{items:[],next_cursor:null};f.owner=w}const b=t.get("name"),j=[];let m=r===null?0:Number(r),p=!0;for(;j.length<o&&p;){const w=await Me(c,u,f,{limit:100,after_seq:m});p=w.length===100;for(const q of w)if(m=q.seq,(b===null||q.name.startsWith(b))&&j.push(q),j.length===o)break}const d=j.at(-1);return{items:await we(j,async w=>await me(c,w)),next_cursor:j.length===o&&d?String(d.seq):null}})}l(_e,"listLocal");const tt={ms:3e4},nt="self",X=l((e,t)=>e.map(a=>({...a,machine:t})),"labelItems");async function ke(e,t,a,n){const i=W.current;try{const o=await i.call(t.id,{method:"GET",path:"/v1/objects",query:a},await i.envelope(e.principal),n);if(Ye(o))return{state:"unreachable",items:[],next:null};if(o.status===426)return{state:"too_old",items:[],next:null};const r=o.body;return o.status!==200||!Array.isArray(r?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:X(r.items,t),next:r.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}l(ke,"remotePage");async function at(e){const t=new Promise(a=>e.addEventListener("abort",()=>a(null),{once:!0}));return Promise.race([W.current.machines().catch(()=>null),t])}l(at,"machinesWithin");async function it(e){const t=e.query.get("machine");if(!fe(e.principal)||!W.current.joined()||t===nt)return await _e(ve(e));const n=W.current.self(),i=t!==null&&A(t)!==n,o=i?null:await _e(ve(e)),r=new AbortController,s=setTimeout(()=>r.abort(),tt.ms);s.unref?.();try{const c=await at(r.signal);if(c===null){if(i)throw new y(503,"runtime_unreachable",`The directory did not answer, so ${A(t)} cannot be listed.`,{machine:A(t)});return o}const u=l(d=>({id:d,name:c.find(w=>w.machine_id===d)?.name??d}),"labelOf"),f=u(n),h=c.filter(d=>d.machine_id!==n&&d.kind!=="device"),b=D(e);if(t!==null){if(!i)return{items:X(o.items,f),next_cursor:o.next_cursor,machines:[{machine_id:n,name:f.name,state:"ok",more:o.next_cursor!==null}]};const d=A(t);if(!h.some(q=>q.machine_id===d))throw new y(404,"not_found",`no machine ${d} on your account`,{machine:d});const w=await ke(e,u(d),b,r.signal);return{items:w.items,next_cursor:w.next,machines:[{machine_id:d,name:u(d).name,state:w.state,more:w.next!==null}]}}const{cursor:j,...m}=b,p=await Promise.all(h.map(d=>ke(e,u(d.machine_id),m,r.signal)));return{items:[...X(o.items,f),...p.flatMap(d=>d.items)],next_cursor:o.next_cursor,machines:[{machine_id:n,name:f.name,state:"ok",more:o.next_cursor!==null},...h.map((d,w)=>({machine_id:d.machine_id,name:d.name,state:p[w].state,more:p[w].next!==null}))]}}finally{clearTimeout(s)}}l(it,"list");function ve(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}l(ve,"withoutMachine");async function rt(e){const t=[],a=N(e.body)?e.body:{};N(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const n=a.text;(typeof n!="string"||n.trim()==="")&&t.push({field:"text",problem:"is required",received:n});const i=a.grep;if(i!==void 0)if(typeof i!="string")t.push({field:"grep",problem:"must be a regular expression string",received:i});else try{new RegExp(i)}catch(s){t.push({field:"grep",problem:`is not a valid regular expression: ${s.message}`,received:i})}a.body!==void 0&&typeof a.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:a.body});const o=await ge(await I(),a.type,t);a.kind!==void 0&&typeof a.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:a.kind}),a.owner!==void 0&&typeof a.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:a.owner});const r=je(a.limit,"limit",t,50);return t.length>0&&C("object search request",t),await _(async s=>{const c=await v(s,e),u=typeof a.owner=="string"?await he(s,c,a.owner):null;if(typeof a.owner=="string"&&u===null)return{items:[]};const f=await se(s,c,{text:n,body:a.body===!0||typeof i=="string"}),h=new Set(f.map(m=>m.object.id)),j=(typeof i=="string"?(await se(s,c,{text:i,grep:!0})).filter(m=>h.has(m.object.id)):f).filter(m=>(!o||m.object.type===o)&&(a.kind===void 0||m.object.kind===a.kind)&&(!u||m.object.owner===u.id));return{items:await we(j.slice(0,r),async m=>({object:await me(s,m.object),...m.line!==void 0?{matches:[{line:m.line,text:m.text??""}]}:{}}))}})}l(rt,"search");const Oe=["interrupt","steer","after-turn","next-turn"],ot=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function st(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(a=>typeof a!="string"||!ot.test(a)||a.includes(">")&&!a.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}l(st,"patternsOf");function ut(e,t){if(e===void 0)return;if(!N(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const a=[];for(const[n,i]of Object.entries(e)){const o=Number(n);!Number.isInteger(o)||o<1||o>10?t.push({field:`config.${n}`,problem:"level must be an integer from 1 to 10"}):Oe.includes(i)?a.push({threshold:o,delivery:i}):t.push({field:`config.${n}`,problem:`delivery must be one of ${Oe.join(", ")}`,received:i})}return a.sort((n,i)=>i.threshold-n.threshold)}l(ut,"configOf");async function qe(e){const t=await ye(e);if(t!==null)throw new y(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}l(qe,"refuseStubWatch");async function x(e,t){const a=await E(e,t)??await(async()=>{const n=await Fe(e,await Ae(e,{class:"person"},async()=>[]),t);return"object"in n?n.object:null})();return a===null||a.deleted_at!==null||!(a.type.includes(".")||a.type==="node")?null:a}l(x,"findWatcher");const O=l(()=>{throw new y(404,"not_found","watcher not found")},"watcherNotFound");async function Ee(e,t,a){if(typeof t!="string"||a===void 0||a===null)return null;if(typeof a!="string")throw new y(400,"invalid_request","invalid watcher_machine");if(await x(e,t)!==null)return null;const n=W.current;let i;try{i=await n.machines()}catch{throw new y(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const o=A(a);return(o===n.self()||!i.some(r=>A(r.machine_id)===o))&&O(),o}l(Ee,"remoteWatcherMachine");async function Te(e,t,a,n){if(t.publishToken||t.principal.class==="anonymous")return O();const i=await v(e,t);if(i.class==="person")return O();let o;try{o=await T(e,i,n)}catch{return O()}const r=o.owner===null?null:await E(e,o.owner);return r===null||!await ie(e,i,r)||!await Le(e,i,"link",a)?O():(await z(e,t,a),{actor:i.app,object:o})}l(Te,"linkWatcher");async function Re(e,t,a){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!a.type.includes("."))return!1;const n=await v(e,t),i=a.owner===null?null:await E(e,a.owner);return i!==null&&await ie(e,n,i)&&await We(e,n,a)}l(Re,"ownsWatcher");async function ct(e){const t=k(e),a=N(e.body)?e.body:{};if(typeof a.watcher=="string"&&await qe(t),typeof a.watcher!="string"){const i=await Q(e,t,{method:"POST",path:`${G(t)}/watch`,body:e.body});if(i.kind==="unknown")throw de(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw M(i.status,i.body);const o=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",o),Z(i.body,i.machine)}}const n=await Ee(await I(),a.watcher,a.watcher_machine);return await lt(e,n)}l(ct,"watch");async function lt(e,t=null){const a=[],n=e.body===void 0?{}:N(e.body)?e.body:(a.push({field:"body",problem:"must be an object"}),{}),i=st(n.patterns,a),o=ut(n.config,a);return n.filter!==void 0&&!N(n.filter)&&a.push({field:"filter",problem:"must be an object",received:n.filter}),n.watcher!==void 0&&typeof n.watcher!="string"&&a.push({field:"watcher",problem:"must be a custom-object ref",received:n.watcher}),n.watcher_machine!==void 0&&typeof n.watcher_machine!="string"&&a.push({field:"watcher_machine",problem:"must be a machine id",received:n.watcher_machine}),a.length>0&&C("watch request",a),await _(async r=>{const s=typeof n.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!s)throw new y(404,"not_found","watcher not found");const c=i??[">"],u={patterns:c,...o?{config:o}:{},...n.filter!==void 0?{filter:n.filter}:{}};if(s){const j=n.watcher,m=t===null?null:await ft(r,e,j,t),p=m??(e.publishToken?await re(r,j):await x(r,j));if(p===null)return O();if(m===null&&await Re(r,e,p)){const q=await oe(r,e,p);await z(r,e,p);const ee=await U(r,p),R=await T(r,ee,k(e));if(!await ae(r,ee,R))throw new y(404,"not_found","object not found");return await L(r,p,R,"act",u),await P(r,p,R),await H(r,{event:"watched",object:R,actor:q,attrs:{}},await F(r)),{object:await $(r,R,await g(r,R)),patterns:c}}const{actor:d,object:w}=await Te(r,e,p,k(e));return await L(r,p,w,"act",{...u,linkApp:d}),await P(r,p,w),await H(r,{event:"watched",object:w,actor:d,attrs:{}},await F(r)),{object:await $(r,w,await g(r,w)),patterns:c}}const f=await v(r,e),h=await K(r,e)??te(f),b=await T(r,f,k(e));return await L(r,h,b,"ask",u),await P(r,h,b),await H(r,{event:"watched",object:b,actor:h,attrs:{}},await F(r)),{object:await $(r,b,await g(r,b)),patterns:c}})}l(lt,"watchLocal");async function ft(e,t,a,n){return t.publishToken||t.principal.class==="anonymous"?O():await Je(e,a,n)}l(ft,"ensureNodeStubFor");async function Ie(e,t,a,n){const i=l(async()=>(await e.prepare(`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.watch_id = s.watch
|
|
3
|
-
WHERE w.watcher = ? AND w.object = ?`).get(t.id,a.id)).n,"count"),o=await i();await Ue(e,t,a,n??void 0);const r=await i();return r===0&&await Ve(e,t,a),{object:await
|
|
1
|
+
var Ne=Object.defineProperty;var l=(e,t)=>Ne(e,"name",{value:t,configurable:!0});import{ApiError as p}from"../../../api/errors.js";import{PRIVACY_LEVELS_DTO as $e}from"../../../api/dto/objects.js";import{openDb as E,withCanvasWrite as j}from"../../../core/canvas/db.js";import{actorOf as te}from"../../../core/graph/documents.js";import{readerForObject as U,readerFor as Ae}from"../../../core/graph/reader.js";import{resolveName as Fe,stubsNamed as Se,unwrapRef as ne}from"../../../core/graph/names.js";import{canRead as ae,customReachable as We,holdsObjectsScope as Le,mayActAs as ie}from"../../../core/graph/access.js";import{customObjectRef as re,authorizeCustom as oe,fenceArgv as z}from"./custom-objects.js";import{edgesOf as Pe}from"../../../core/graph/edges.js";import{publish as H}from"../../../core/graph/events.js";import{objectDTO as b}from"../../../core/graph/kinds/dto.js";import{isKind as Ce,kindNames as De,kindOf as V}from"../../../core/graph/kinds/registry.js";import{listObjects as Me,searchObjects as se}from"../../../core/graph/objects.js";import{checkoutsForCwd as Ge}from"../../../core/graph/repo-sync/repos.js";import{recordWatch as L,unwatch as Ue,watchersOf as ze,watchesOf as He}from"../../../core/graph/watches.js";import{armObjectWaitForWatch as P,settleObjectWaitForUnwatch as Ve}from"../../../core/graph/object-waits.js";import{readerFor as v,resolveRef as B}from"../reader.js";import{readDelegationFor as ue,runReadLeaf as Be}from"../../plugin-objects/read-leaf.js";import{invalidRequest as C,isRecord as N}from"./validate.js";import{callerNode as ce,callerStub as K,forwardNamed as Ke,forwardVerb as le,originates as fe,queryWithoutMachine as D,relayError as M,remoteStub as Ze,unknownError as de,forwarding as W,withMachine as Z}from"../../peer/forward.js";import{getById as T}from"../../../core/graph/objects.js";import{ensureNodeStub as Je,isStub as J,stubOf as Qe,withKindDecl as $}from"../../../core/peer/stubs.js";import{isUnreachable as Ye}from"../../../core/peer/client.js";import{normalizeMachineId as A}from"../../../core/peer/directory.js";import{mapAsync as we}from"../../../core/async-array.js";const F=l(async e=>async t=>await Ge(e,t),"reposFnFor");async function me(e,t){return{...await b(e,t),...await(await V(e,t.type)).listItem?.(e,t)}}l(me,"listItem");function Xe(e){return`no object named ${e} on this runtime; it may be on another runtime, or the name may be misspelled`}l(Xe,"remoteMessage");async function he(e,t,a){try{return await R(e,t,a)}catch(n){if(n instanceof p&&n.code==="not_found"&&!n.details?.deleted)return null;throw n}}l(he,"ownerFilter");async function R(e,t,a){const n=await B(e,t,a);if("remote"in n)throw new p(404,"not_found",Xe(n.remote),{next:"Check the name with `crtr canvas search`."});if("deleted"in n)throw new p(404,"not_found",`${n.deleted.name} is deleted`,{id:n.deleted.id,deleted:!0});return n}l(R,"liveRef");const _=l(e=>decodeURIComponent(e.params.ref),"refParam"),pe=l(e=>{const t=ne(e),a=t.indexOf("/");return a>0?t.slice(0,a):t},"idOf");async function ye(e){const t=await T(await E(),pe(e));return t!==null&&await J(await E(),t)?t.id:null}l(ye,"stubIdOf");async function xe(e,t){const a=await ye(e);return a!==null?{stub:a,hit:!0}:await j(async n=>{try{const i=await v(n,t),o=l(async()=>{const s=await Se(n,i,e);if(s.length>1)throw new p(409,"ambiguous_name",`'${e}' names more than one remote object`,{candidates:s.map(c=>c.id),next:"Read one by its object id."});return{stub:s[0]?.id??null,hit:!1}},"named");let r;try{r=await B(n,i,e)}catch(s){if(s instanceof p&&s.code==="not_found")return await o();throw s}if("remote"in r)return await o();if("deleted"in r){const s=await o();return s.stub===null?{stub:null,hit:!0}:s}return{stub:await J(n,r)?r.id:null,hit:!0}}catch(i){if(i instanceof p&&i.code==="ambiguous_name")throw i;return{stub:null,hit:!1}}})}l(xe,"resolvedLocally");async function Q(e,t,a){const n=await xe(t,e);if(n.stub!==null)return le(e,n.stub,a);if(n.hit||!fe(e.principal))return{kind:"local"};const i=await le(e,pe(t),a);return i.kind==="local"&&ne(t).includes("/")?Ke(e,a,{method:"GET",path:G(t),query:D(e)}):i}l(Q,"forwardRef");const G=l(e=>`/v1/objects/${encodeURIComponent(e)}`,"objectPath");async function be(e,t,a,n,i){const o=t?.object;!o?.id||!o.type||await j(async r=>{const s=await ce(r,e);if(s===null)return;const c=await Ze(r,o.id,o.type,a,{kind:o.kind??null,name:o.name??o.id,...o.preview===void 0?{}:{preview:o.preview},owner:o.owner??null,...o.kind_decl===void 0?{}:{kind_decl:o.kind_decl},...o.privacy===void 0?{}:{privacy:o.privacy}});await L(r,s,c,n,i===void 0?{}:{patterns:i}),n==="ask"&&await P(r,s,c)})}l(be,"watchRemote");async function et(e){const t=_(e),a=["1","true"].includes(e.query.get("fields")??""),n=await Q(e,t,{method:"GET",path:G(t),query:D(e)});if(n.kind==="unknown")return{state:"unknown",ref:t,unreachable:n.unreachable};if(n.kind==="remote"){if(n.status>=400)throw M(n.status,n.body);return await be(e,n.body,n.machine.id,"read"),Z(n.body,n.machine)}const i=l(async s=>{const c=await K(s,e);return c===null?await v(s,e):await U(s,c,await F(s))},"readerOf"),o=await j(async s=>{const c=await i(s),u=await B(s,c,t);if("remote"in u)return{state:"remote",remote:u.remote};if("deleted"in u)return{state:"deleted",deleted:await b(s,u.deleted)};const w=await ue(s,u);if(w!==null)return{delegate:w,hitId:u.id};const{data:h,text:y}=await(await V(s,u.type)).read(s,c,u,{fields:a,reposFn:await F(s)});return{state:"object",type:u.type,object:await $(s,u,await b(s,u)),text:y,data:h}});if(!("delegate"in o))return o;const r=await Be(o.delegate,e.principal);return await j(async s=>{const c=await i(s),u=await T(s,o.hitId);if(u===null)throw new p(404,"not_found","object not found");if(u.deleted_at!==null)return{state:"deleted",deleted:await b(s,u)};if(!await ae(s,c,u))throw new p(404,"not_found","object not found");const{data:w,text:h}=await(await V(s,u.type)).read(s,c,u,{fields:a,reposFn:await F(s)});return await ue(s,u)===null?{state:"object",type:u.type,object:await $(s,u,await b(s,u)),text:h,data:w}:{state:"object",type:u.type,object:await $(s,u,await b(s,u)),text:"markdown"in r?r.markdown:`${h}
|
|
2
|
+
content unavailable: ${r.unavailable}`,data:{...w,content:"markdown"in r?"live":"unavailable"}}})}l(et,"read");function Y(e,t,a,n){if(e!=null){if(!a.includes(e)){n.push({field:t,problem:`must be one of ${a.join(", ")}`,received:e});return}return e}}l(Y,"oneOf");async function ge(e,t,a){if(t!=null){if(typeof t!="string"||!await Ce(e,t)){a.push({field:"type",problem:`must be a kind: one of ${(await De(e)).join(", ")}`,received:t});return}return t}}l(ge,"kindName");function je(e,t,a,n){if(e==null)return n;const i=Number(e);return!Number.isInteger(i)||i<1||i>100?(a.push({field:t,problem:"must be an integer from 1 to 100",received:e}),n):i}l(je,"limitOf");async function _e(e){const t=e.query,a=[],n=await ge(await E(),t.get("type"),a),i=Y(t.get("privacy"),"privacy",$e,a),o=je(t.get("limit"),"limit",a,50),r=t.get("cursor");r!==null&&!/^\d+$/.test(r)&&a.push({field:"cursor",problem:"is not a cursor from a previous page",received:r});const s=t.get("deleted");return s!==null&&!["0","1","true","false"].includes(s)&&a.push({field:"deleted",problem:"must be true or false",received:s}),a.length>0&&C("object list request",a),await j(async c=>{const u=await v(c,e),w={...n?{type:n}:{},...i?{privacy:i}:{},...t.get("kind")!==null?{kind:t.get("kind")}:{},...s==="1"||s==="true"?{deleted:!0}:{}},h=t.get("owner");if(h!==null){const m=await he(c,u,h);if(m===null)return{items:[],next_cursor:null};w.owner=m}const y=t.get("name"),g=[];let k=r===null?0:Number(r),f=!0;for(;g.length<o&&f;){const m=await Me(c,u,w,{limit:100,after_seq:k});f=m.length===100;for(const q of m)if(k=q.seq,(y===null||q.name.startsWith(y))&&g.push(q),g.length===o)break}const d=g.at(-1);return{items:await we(g,async m=>await me(c,m)),next_cursor:g.length===o&&d?String(d.seq):null}})}l(_e,"listLocal");const tt={ms:3e4},nt="self",X=l((e,t)=>e.map(a=>({...a,machine:t})),"labelItems");async function ke(e,t,a,n){const i=W.current;try{const o=await i.call(t.id,{method:"GET",path:"/v1/objects",query:a},await i.envelope(e.principal),n);if(Ye(o))return{state:"unreachable",items:[],next:null};if(o.status===426)return{state:"too_old",items:[],next:null};const r=o.body;return o.status!==200||!Array.isArray(r?.items)?{state:"unreachable",items:[],next:null}:{state:"ok",items:X(r.items,t),next:r.next_cursor??null}}catch{return{state:"unreachable",items:[],next:null}}}l(ke,"remotePage");async function at(e){const t=new Promise(a=>e.addEventListener("abort",()=>a(null),{once:!0}));return Promise.race([W.current.machines().catch(()=>null),t])}l(at,"machinesWithin");async function it(e){const t=e.query.get("machine");if(!fe(e.principal)||!W.current.joined()||t===nt)return await _e(ve(e));const n=W.current.self(),i=t!==null&&A(t)!==n,o=i?null:await _e(ve(e)),r=new AbortController,s=setTimeout(()=>r.abort(),tt.ms);s.unref?.();try{const c=await at(r.signal);if(c===null){if(i)throw new p(503,"runtime_unreachable",`The directory did not answer, so ${A(t)} cannot be listed.`,{machine:A(t)});return o}const u=l(d=>({id:d,name:c.find(m=>m.machine_id===d)?.name??d}),"labelOf"),w=u(n),h=c.filter(d=>d.machine_id!==n&&d.kind!=="device"),y=D(e);if(t!==null){if(!i)return{items:X(o.items,w),next_cursor:o.next_cursor,machines:[{machine_id:n,name:w.name,state:"ok",more:o.next_cursor!==null}]};const d=A(t);if(!h.some(q=>q.machine_id===d))throw new p(404,"not_found",`no machine ${d} on your account`,{machine:d});const m=await ke(e,u(d),y,r.signal);return{items:m.items,next_cursor:m.next,machines:[{machine_id:d,name:u(d).name,state:m.state,more:m.next!==null}]}}const{cursor:g,...k}=y,f=await Promise.all(h.map(d=>ke(e,u(d.machine_id),k,r.signal)));return{items:[...X(o.items,w),...f.flatMap(d=>d.items)],next_cursor:o.next_cursor,machines:[{machine_id:n,name:w.name,state:"ok",more:o.next_cursor!==null},...h.map((d,m)=>({machine_id:d.machine_id,name:d.name,state:f[m].state,more:f[m].next!==null}))]}}finally{clearTimeout(s)}}l(it,"list");function ve(e){const t=new URLSearchParams(e.query);return t.delete("machine"),{...e,query:t}}l(ve,"withoutMachine");async function rt(e){const t=[],a=N(e.body)?e.body:{};N(e.body)||t.push({field:"body",problem:"must be an object",received:e.body});const n=a.text;(typeof n!="string"||n.trim()==="")&&t.push({field:"text",problem:"is required",received:n});const i=a.grep;if(i!==void 0)if(typeof i!="string")t.push({field:"grep",problem:"must be a regular expression string",received:i});else try{new RegExp(i)}catch(f){t.push({field:"grep",problem:`is not a valid regular expression: ${f.message}`,received:i})}a.body!==void 0&&typeof a.body!="boolean"&&t.push({field:"body",problem:"must be a boolean",received:a.body});const o=await ge(await E(),a.type,t);a.kind!==void 0&&typeof a.kind!="string"&&t.push({field:"kind",problem:"must be a string",received:a.kind}),a.owner!==void 0&&typeof a.owner!="string"&&t.push({field:"owner",problem:"must be a string",received:a.owner});const r=je(a.limit,"limit",t,50);t.length>0&&C("object search request",t);const s=await j(async f=>{const d=await v(f,e),m=typeof a.owner=="string"?await he(f,d,a.owner):null;return{reader:d,owner:m}}),{reader:c,owner:u}=s;if(typeof a.owner=="string"&&u===null)return{items:[]};const w=await E(),h=await se(w,c,{text:n,body:a.body===!0||typeof i=="string"}),y=new Set(h.map(f=>f.object.id)),k=(typeof i=="string"?(await se(w,c,{text:i,grep:!0})).filter(f=>y.has(f.object.id)):h).filter(f=>(!o||f.object.type===o)&&(a.kind===void 0||f.object.kind===a.kind)&&(!u||f.object.owner===u.id));return{items:await we(k.slice(0,r),async f=>({object:await me(w,f.object),...f.line!==void 0?{matches:[{line:f.line,text:f.text??""}]}:{}}))}}l(rt,"search");const Oe=["interrupt","steer","after-turn","next-turn"],ot=/^(\*|>|[A-Za-z0-9_-]+)(\.(\*|>|[A-Za-z0-9_-]+))*$/;function st(e,t){if(e!==void 0){if(!Array.isArray(e)||e.length===0||e.some(a=>typeof a!="string"||!ot.test(a)||a.includes(">")&&!a.endsWith(">"))){t.push({field:"patterns",problem:"must be a non-empty list of event patterns (dot-separated words, `*` for one word, a final `>` for the rest)",received:e});return}return e}}l(st,"patternsOf");function ut(e,t){if(e===void 0)return;if(!N(e)||Object.keys(e).length===0){t.push({field:"config",problem:"must map levels 1-10 to a delivery",received:e});return}const a=[];for(const[n,i]of Object.entries(e)){const o=Number(n);!Number.isInteger(o)||o<1||o>10?t.push({field:`config.${n}`,problem:"level must be an integer from 1 to 10"}):Oe.includes(i)?a.push({threshold:o,delivery:i}):t.push({field:`config.${n}`,problem:`delivery must be one of ${Oe.join(", ")}`,received:i})}return a.sort((n,i)=>i.threshold-n.threshold)}l(ut,"configOf");async function qe(e){const t=await ye(e);if(t!==null)throw new p(400,"invalid_request",`${t} lives on another machine; an explicit watcher cannot watch it from here`,{id:t})}l(qe,"refuseStubWatch");async function x(e,t){const a=await T(e,t)??await(async()=>{const n=await Fe(e,await Ae(e,{class:"person"},async()=>[]),t);return"object"in n?n.object:null})();return a===null||a.deleted_at!==null||!(a.type.includes(".")||a.type==="node")?null:a}l(x,"findWatcher");const O=l(()=>{throw new p(404,"not_found","watcher not found")},"watcherNotFound");async function Ee(e,t,a){if(typeof t!="string"||a===void 0||a===null)return null;if(typeof a!="string")throw new p(400,"invalid_request","invalid watcher_machine");if(await x(e,t)!==null)return null;const n=W.current;let i;try{i=await n.machines()}catch{throw new p(503,"runtime_unreachable","The directory did not answer, so the watcher machine cannot be checked.")}const o=A(a);return(o===n.self()||!i.some(r=>A(r.machine_id)===o))&&O(),o}l(Ee,"remoteWatcherMachine");async function Te(e,t,a,n){if(t.publishToken||t.principal.class==="anonymous")return O();const i=await v(e,t);if(i.class==="person")return O();let o;try{o=await R(e,i,n)}catch{return O()}const r=o.owner===null?null:await T(e,o.owner);return r===null||!await ie(e,i,r)||!await Le(e,i,"link",a)?O():(await z(e,t,a),{actor:i.app,object:o})}l(Te,"linkWatcher");async function Re(e,t,a){if(t.publishToken)return!0;if(t.principal.class==="anonymous"||!a.type.includes("."))return!1;const n=await v(e,t),i=a.owner===null?null:await T(e,a.owner);return i!==null&&await ie(e,n,i)&&await We(e,n,a)}l(Re,"ownsWatcher");async function ct(e){const t=_(e),a=N(e.body)?e.body:{};if(typeof a.watcher=="string"&&await qe(t),typeof a.watcher!="string"){const i=await Q(e,t,{method:"POST",path:`${G(t)}/watch`,body:e.body});if(i.kind==="unknown")throw de(t,i.unreachable);if(i.kind==="remote"){if(i.status>=400)throw M(i.status,i.body);const o=i.body.patterns;return await be(e,i.body,i.machine.id,"ask",o),Z(i.body,i.machine)}}const n=await Ee(await E(),a.watcher,a.watcher_machine);return await lt(e,n)}l(ct,"watch");async function lt(e,t=null){const a=[],n=e.body===void 0?{}:N(e.body)?e.body:(a.push({field:"body",problem:"must be an object"}),{}),i=st(n.patterns,a),o=ut(n.config,a);return n.filter!==void 0&&!N(n.filter)&&a.push({field:"filter",problem:"must be an object",received:n.filter}),n.watcher!==void 0&&typeof n.watcher!="string"&&a.push({field:"watcher",problem:"must be a custom-object ref",received:n.watcher}),n.watcher_machine!==void 0&&typeof n.watcher_machine!="string"&&a.push({field:"watcher_machine",problem:"must be a machine id",received:n.watcher_machine}),a.length>0&&C("watch request",a),await j(async r=>{const s=typeof n.watcher=="string";if((e.publishToken||e.principal.class==="anonymous")&&!s)throw new p(404,"not_found","watcher not found");const c=i??[">"],u={patterns:c,...o?{config:o}:{},...n.filter!==void 0?{filter:n.filter}:{}};if(s){const g=n.watcher,k=t===null?null:await ft(r,e,g,t),f=k??(e.publishToken?await re(r,g):await x(r,g));if(f===null)return O();if(k===null&&await Re(r,e,f)){const q=await oe(r,e,f);await z(r,e,f);const ee=await U(r,f),I=await R(r,ee,_(e));if(!await ae(r,ee,I))throw new p(404,"not_found","object not found");return await L(r,f,I,"act",u),await P(r,f,I),await H(r,{event:"watched",object:I,actor:q,attrs:{}},await F(r)),{object:await $(r,I,await b(r,I)),patterns:c}}const{actor:d,object:m}=await Te(r,e,f,_(e));return await L(r,f,m,"act",{...u,linkApp:d}),await P(r,f,m),await H(r,{event:"watched",object:m,actor:d,attrs:{}},await F(r)),{object:await $(r,m,await b(r,m)),patterns:c}}const w=await v(r,e),h=await K(r,e)??te(w),y=await R(r,w,_(e));return await L(r,h,y,"ask",u),await P(r,h,y),await H(r,{event:"watched",object:y,actor:h,attrs:{}},await F(r)),{object:await $(r,y,await b(r,y)),patterns:c}})}l(lt,"watchLocal");async function ft(e,t,a,n){return t.publishToken||t.principal.class==="anonymous"?O():await Je(e,a,n)}l(ft,"ensureNodeStubFor");async function Ie(e,t,a,n){const i=l(async()=>(await e.prepare(`SELECT count(*) AS n FROM watch_subscriptions s JOIN watches w ON w.watch_id = s.watch
|
|
3
|
+
WHERE w.watcher = ? AND w.object = ?`).get(t.id,a.id)).n,"count"),o=await i();await Ue(e,t,a,n??void 0);const r=await i();return r===0&&await Ve(e,t,a),{object:await b(e,a),removed:o-r}}l(Ie,"dropWatch");async function dt(e){const t=_(e);if(e.query.get("watcher")&&await qe(t),!e.query.get("watcher")){const n=await Q(e,t,{method:"DELETE",path:`${G(t)}/watch`,query:D(e)});if(n.kind==="unknown")throw de(t,n.unreachable);if(n.kind==="remote"){const i=n.status===404?n.body.error?.details:void 0,o=i?.deleted===!0?i.id:void 0;if(n.status>=400&&o===void 0)throw M(n.status,n.body);const r=o??n.body.object?.id,s=await j(async c=>{const u=await ce(c,e),w=r===void 0?null:await T(c,r);return u===null||w===null||!await J(c,w)?null:await Ie(c,u,w,e.query.get("pattern"))});if(o!==void 0){if(s===null)throw M(n.status,n.body);return{...s,machine:n.machine}}return Z(n.body,n.machine)}}const a=await Ee(await E(),e.query.get("watcher")??void 0,e.query.get("watcher_machine")??void 0);return await wt(e,a)}l(dt,"unwatchRoute");async function wt(e,t=null){const a=e.query.get("pattern"),n=e.query.get("watcher");return await j(async i=>{if((e.publishToken||e.principal.class==="anonymous")&&!n)throw new p(404,"not_found","watcher not found");const o=l(async(c,u)=>await Ie(i,c,u,a),"drop");if(n){const c=t===null?null:await(async()=>{const w=await T(i,n);return w!==null&&await Qe(i,w)!==null?w:null})();if(t!==null&&c===null)return O();const u=c??(e.publishToken?await re(i,n):await x(i,n));return u===null?O():c===null&&await Re(i,e,u)?(await oe(i,e,u),await z(i,e,u),await o(u,await R(i,await U(i,u),_(e)))):await o(u,(await Te(i,e,u,_(e))).object)}const r=await v(i,e),s=await K(i,e)??te(r);return await o(s,await R(i,r,_(e)))})}l(wt,"unwatchLocal");async function mt(e){const t=[],a=Y(e.query.get("type"),"type",["acted-on","links-to","watches"],t),n=Y(e.query.get("direction"),"direction",["out","in"],t);return t.length>0&&C("edges request",t),await j(async i=>{const o=await v(i,e),r=await R(i,o,_(e)),s=[];if(a!=="watches")for(const c of await Pe(i,o,r,{...a?{type:a}:{},direction:n??"both"}))s.push({type:c.type,src:await b(i,c.src),dst:await b(i,c.dst),...c.written_as?{written_as:c.written_as}:{}});if(a===void 0||a==="watches"){const c=[...n!=="in"?await He(i,o,r):[],...n!=="out"?await ze(i,o,r):[]];for(const u of c)s.push({type:"watches",src:await b(i,u.watcher),dst:await b(i,u.object)})}return{items:s}})}l(mt,"edges");const S=l(e=>async t=>({status:200,body:await e(t)}),"ok"),Gt=[{method:"POST",pattern:"/v1/objects/search",handler:S(rt)},{method:"GET",pattern:"/v1/objects/:ref/edges",handler:S(mt)},{method:"POST",pattern:"/v1/objects/:ref/watch",handler:S(ct)},{method:"DELETE",pattern:"/v1/objects/:ref/watch",handler:S(dt)},{method:"GET",pattern:"/v1/objects/:ref",handler:S(et)},{method:"GET",pattern:"/v1/objects",handler:S(it)}];export{tt as listBudget,Gt as objectRoutes};
|
|
@@ -23,5 +23,11 @@ export declare class BashDeadlineReconciler {
|
|
|
23
23
|
/** Give every backgrounded job dir (job.bg) that has no job object one; the next tick's
|
|
24
24
|
* `publishExits` then ends it like any other job. */
|
|
25
25
|
private adoptUnrecorded;
|
|
26
|
+
/** A running job whose process is confirmed gone without job.exit (killed outright, so its
|
|
27
|
+
* supervisor never wrote one) is ended once as killed, with a null exit code, through
|
|
28
|
+
* `finishJob`. job.exit is then written so the file-based listing and stop guard stop counting
|
|
29
|
+
* the job. A job.exit that appears by the re-check is a real exit: `publishExits` reports it.
|
|
30
|
+
* A job being stopped (job.stop) is ended by its killer. */
|
|
31
|
+
private settleVanished;
|
|
26
32
|
private cancel;
|
|
27
33
|
}
|
|
@@ -1,2 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
WHERE j.status = 'running' AND o.deleted_at IS NULL`).all();for(const{object:e,job_dir:
|
|
1
|
+
var y=Object.defineProperty;var p=(h,t)=>y(h,"name",{value:t,configurable:!0});import{existsSync as n,readFileSync as m,readdirSync as _,statSync as w}from"node:fs";import{join as s}from"node:path";import{bashJobPaths as u,bashJobsDir as x,activeBackgroundBashJobs as E,expiredAutoBackgroundBashJobs as S,isBashJobProcessConfirmedGone as B,readJobPgid as N,readJobPgidIdentity as g,stopBackgroundBashJob as v}from"../../core/bash-jobs.js";import{killBashJobObject as J,recordBashJobObject as A}from"../../core/spaces/stop.js";import{createFileBeneath as I}from"../../core/spaces/open-beneath.js";import{withCanvasWrite as d}from"../../core/canvas/db.js";import{finishJob as j}from"../../core/graph/jobs.js";import{getById as l}from"../../core/graph/objects.js";import{isSafeNodeId as f}from"../../core/canvas/paths.js";import{contextDir as P}from"../../core/canvas/node-agent-paths.js";import{emitEvent as c}from"../../core/events/emit.js";import{operationIdContext as b}from"../../core/events/operation-id.js";import{isProfilePaused as k}from"../../core/profiles/manifest.js";const C=5*1e3;class q{static{p(this,"BashDeadlineReconciler")}lastScanAt=Number.NEGATIVE_INFINITY;startedAt=Date.now();async run(t,r){if(await this.publishExits(),!(t-this.lastScanAt<C)){this.lastScanAt=t;for(const e of r.rows){if(e.status==="dead"||k(e.profile_id))continue;const a=await P(e.node_id);let i;try{await this.adoptUnrecorded(e.node_id,a),await this.settleVanished(a),i=S(a,t)}catch(o){b.fresh(()=>{c({level:"error",event:"bash_deadline.scan_failed",...f(e.node_id)?{node_id:e.node_id}:{},error:o})});continue}for(const o of i)await this.cancel(e.node_id,a,o.jobId)}}}async publishExits(){try{await d(async t=>{const r=await t.prepare(`SELECT j.object, j.job_dir FROM jobs j JOIN objects o ON o.id = j.object
|
|
2
|
+
WHERE j.status = 'running' AND o.deleted_at IS NULL`).all();for(const{object:e,job_dir:a}of r){const i=s(a,"job.exit");if(!n(i)||n(s(a,"job.stop")))continue;const o=Number(m(i,"utf8").trim());Number.isSafeInteger(o)&&await j(t,await l(t,e),{exitCode:o})}})}catch(t){b.fresh(()=>c({level:"error",event:"bash_completion.delivery_failed",error:t}))}}async adoptUnrecorded(t,r){let e;try{e=_(x(r))}catch{return}await d(async a=>{for(const i of e){if(await l(a,i)!==null)continue;const o=u(r,i);!n(o.jobBg)||!n(o.cmdSh)||n(o.jobExit)&&w(o.jobExit).mtimeMs<this.startedAt||await A(t,i,{command:m(o.cmdSh,"utf8"),jobDir:o.dir,logPath:o.jobLog})}})}async settleVanished(t){for(const{jobId:r}of E(t)){const e=u(t,r);n(e.jobExit)||n(s(e.dir,"job.stop"))||B(N(t,r),g(t,r))&&await d(async a=>{const i=await l(a,r);if(!(i===null||i.type!=="job")&&!(n(e.jobExit)||n(s(e.dir,"job.stop")))){await j(a,i,{killedBy:null,reason:"process disappeared without an exit record"});try{I(e.root,e.jobExit,`-1
|
|
3
|
+
`)}catch(o){if(o.code!=="EEXIST")throw o}}})}}async cancel(t,r,e){(await v(r,e,!1,t)).kind==="stopped"&&await b.fresh(async()=>{try{c({level:"info",event:"bash_deadline.canceled",...f(t)?{node_id:t}:{},fields:{job_id:e}}),await J(e,async()=>null,"deadline")}catch(i){c({level:"error",event:"bash_deadline.notice_failed",...f(t)?{node_id:t}:{},error:i,fields:{job_id:e}})}})}}export{q as BashDeadlineReconciler};
|
|
@@ -8,6 +8,8 @@ export type OpenAssistantBlock = {
|
|
|
8
8
|
};
|
|
9
9
|
/** The newest block of the node's open assistant message; null when no message is open or nothing has streamed yet. */
|
|
10
10
|
export declare function openAssistantBlock(nodeId: string): OpenAssistantBlock | null;
|
|
11
|
+
/** Test-only: stop every observer and wait out the polls in flight, so none touches a home the test is about to delete. */
|
|
12
|
+
export declare function closeRunObserversForTests(): Promise<void>;
|
|
11
13
|
export declare function ensureRunObserver(nodeId: string, runId: string): Promise<void>;
|
|
12
14
|
/** Observes run nodes with a live broker, plus those whose current outcome
|
|
13
15
|
* (settled within the event retention window) has no `node.settled` event yet. */
|