@north-light/cli 0.3.594 → 0.3.596
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/client.js +3 -3
- package/dist/clients/attach/viewer.js +345 -345
- package/dist/commands/pkg/app-installs.js +2 -2
- package/dist/core/command-plugins/transport/http-plan.d.ts +4 -0
- package/dist/core/command-plugins/transport/http-plan.js +1 -1
- package/dist/core/io.js +4 -4
- package/dist/core/providers/call.js +1 -1
- package/dist/core/runs/initial-input.d.ts +15 -0
- package/dist/core/runs/initial-input.js +1 -0
- package/dist/core/runs/operations.js +5 -5
- package/dist/core/runtime/broker/model-adapter.d.ts +3 -3
- package/dist/core/runtime/broker/model-adapter.js +3 -3
- package/dist/core/runtime/broker/spilled-body.d.ts +2 -4
- package/dist/core/runtime/broker/spilled-body.js +1 -1
- package/dist/core/runtime/broker/turn-cause.d.ts +4 -0
- package/dist/core/runtime/broker/turn-cause.js +1 -1
- package/dist/core/runtime/headless-pi.d.ts +2 -0
- package/dist/core/runtime/headless-pi.js +1 -1
- package/dist/core/runtime/naming.d.ts +2 -2
- package/dist/core/runtime/naming.js +9 -9
- package/dist/core/runtime/recap.d.ts +1 -1
- package/dist/core/runtime/recap.js +4 -4
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/pi-extensions/broker-local.d.ts +3 -1
- package/dist/pi-extensions/broker-local.js +1 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +1 -1
- package/dist/pi-extensions/canvas-recap.js +7 -7
- package/docs/ci-runner.md +5 -5
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
package/dist/api/client.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var x=Object.defineProperty;var o=(i,e)=>x(i,"name",{value:e,configurable:!0});import{ApiError as f,isErrorBody as N}from"./errors.js";import{routes as r}from"./routes.js";import{isSafeNodeId as b}from"./dto/common.js";import{isSafeBashJobId as B}from"./dto/bash-jobs.js";import{isSafeCronId as L}from"./dto/crons.js";const I=3e4,F=Symbol.for("@north-light/api/local-socket-fetch"),$=1e4,H=200;async function U({windowMs:i,probe:e,initialError:t,pollIntervalMs:n=H,retry:s=o(()=>!0,"retry"),now:a=Date.now,sleep:u=M}){const c=a()+i;let l=t;for(;;){const m=c-a();if(m<=0)throw l??new Error("crtrd availability window expired without a probe failure");try{await e(m);return}catch(P){if(l=P,!s(P))throw P}const h=c-a();if(h<=0)throw l;await u(Math.min(n,h))}}o(U,"waitForDaemonAvailability");const y=2147483647;function S(i,e="elapsed",t){const n=e==="retry_after"?`the server asked to retry after ${t}s, which is later than the call's deadline (${new Date(i).toISOString()}); not waiting`:`the call's deadline (${new Date(i).toISOString()}) passed`;return new f(504,"deadline_exceeded",n,{deadline_at:i,reason:e,...t===void 0?{}:{retry_after_s:t}})}o(S,"deadlineExceeded");const p=o(i=>S(i??Date.now()),"budgetExhausted");class
|
|
2
|
-
`))!==-1;){const P=c.slice(0,h);c=c.slice(h+1),P!==""&&(yield JSON.parse(P))}}if(c+=u.decode(),c.trim()!=="")throw new f(502,"invalid_response","broker signal stream ended mid-line")}finally{await a.cancel().catch(()=>{})}}createStructuredRequest(e,t){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,t):this.request("POST","/v1/structured-requests",e,t)}getStructuredRequest(e,{wait:t=0,budgetMs:n}={}){if(!Number.isInteger(t)||t<0||t>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",d(`/v1/structured-requests/${this.requestPath(e)}`,{wait:t}),void 0,{budgetMs:n})}cancelStructuredRequest(e,t){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},t)}registerOutcomeDelivery(e,t){return this.request("PUT",r.nodeOutcomeDelivery(this.nodePath(e)),t)}getOutcomeDelivery(e){return this.request("GET",r.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",r.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",r.nodeJobs(this.nodePath(e)))}readBashJobOutput(e,t,n={}){const s=new URLSearchParams;n.tail_lines!==void 0&&s.set("tail_lines",String(n.tail_lines)),n.max_bytes!==void 0&&s.set("max_bytes",String(n.max_bytes));const a=s.size===0?"":`?${s.toString()}`;return this.request("GET",`${r.nodeJobOutput(this.nodePath(e),this.jobPath(t))}${a}`)}stopBashJob(e,t){return this.request("DELETE",r.nodeJob(this.nodePath(e),this.jobPath(t)))}async patchBashJob(e,t,n){await this.request("PATCH",r.nodeJob(this.nodePath(e),this.jobPath(t)),n)}async reportBashJob(e,t,n){await this.request("POST",r.nodeJobReport(this.nodePath(e),this.jobPath(t)),n)}sendMessage(e,t){return this.request("POST",r.nodeMessages(this.nodePath(e)),t)}interruptNode(e){return this.request("POST",r.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,t){return this.request("POST",r.nodeReports(this.nodePath(e)),t)}submitResult(e,t){return this.request("POST",r.nodeResult(this.nodePath(e)),t)}forkNode(e){return this.request("POST",r.nodeFork(this.nodePath(e)),{})}reviveNode(e,t){return this.request("POST",r.nodeRevive(this.nodePath(e)),t??{})}relaunchRoot(e){return this.request("POST",r.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,t){return this.request("POST",r.nodeBrokerSessionBound(this.nodePath(e)),t)}settleBroker(e,t){return this.request("POST",r.nodeBrokerSettle(this.nodePath(e)),t)}async postBrokerIdle(e,t){await this.request("POST",r.nodeBrokerIdle(this.nodePath(e)),t)}completeBrokerPark(e,t){return this.request("POST",r.nodeBrokerParkComplete(this.nodePath(e)),t)}recordBrokerParkActivity(e,t){return this.request("POST",r.nodeBrokerParkActivity(this.nodePath(e)),t)}async recordBrokerTelemetry(e,t){await this.request("POST",r.nodeBrokerTelemetry(this.nodePath(e)),t)}claimNodeMail(e,t){return this.request("POST",r.nodeMailClaim(this.nodePath(e)),t)}acknowledgeNodeMail(e,t){return this.request("POST",r.nodeMailAcknowledge(this.nodePath(e)),t)}recordBrokerTurn(e,t){return this.request("POST",r.brokerTurn(this.nodePath(e)),t)}mutateBrokerProviderRetry(e,t){return this.request("POST",r.brokerProviderRetry(this.nodePath(e)),t)}mutateBrokerFault(e,t){return this.request("POST",r.brokerFault(this.nodePath(e)),t)}getBrokerRecovery(e,t){return this.request("GET",`${r.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(t)}`)}recordNodeFault(e,t){return this.request("POST",r.nodeFault(this.nodePath(e)),t)}clearNodeFault(e,t={}){const n=new URLSearchParams;t.link!==void 0&&n.set("link",t.link),t.preserve_episode!==void 0&&n.set("preserve_episode",String(t.preserve_episode));const s=n.size===0?"":`?${n.toString()}`;return this.request("DELETE",`${r.nodeFault(this.nodePath(e))}${s}`)}commitBrokerModel(e,t){return this.request("POST",r.nodeBrokerModel(this.nodePath(e)),t)}executionStart(e){return this.request("GET",r.executionStart(e))}executionImportUnpacked(e){return this.request("POST",r.executionImportUnpacked(e),{})}gitCredential(e,t){return this.request("POST",r.environmentGitCredential(e),t)}brokerExtensionState(e){return this.request("GET",r.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",r.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,t){return this.request("POST",r.nodeBrokerGoal(this.nodePath(e)),t)}commitBrokerGeneratedName(e,t){return this.request("POST",r.nodeBrokerGeneratedName(this.nodePath(e)),t)}commitBrokerPersonaAck(e,t){return this.request("POST",r.nodeBrokerPersonaAck(this.nodePath(e)),t)}closeNode(e,t){return this.request("POST",r.nodeClose(this.nodePath(e)),t??{})}async markNodeRead(e){await this.request("POST",r.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",r.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",r.nodeDemote(this.nodePath(e)),{})}promoteNode(e,t){return this.request("POST",r.nodePromote(this.nodePath(e)),t)}yieldNode(e,t){return this.request("POST",r.nodeYield(this.nodePath(e)),t)}waitNode(e,t){return this.request("POST",r.nodeWait(this.nodePath(e)),t)}listKinds(){return this.request("GET",r.kinds())}patchConfig(e,t){return this.request("PATCH",r.nodeConfig(this.nodePath(e)),t,t.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",r.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,t){return this.request("POST",r.nodeWorktreeAbandon(this.nodePath(e)),t)}retryDelivery(e){return this.request("POST",r.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",r.quarantinedWorktrees())}showLimits(){return this.request("GET",r.limits())}setAppLimits(e,t){return this.request("PUT",r.limitsApp(e),t)}removeAppLimits(e,t){return this.request("DELETE",d(r.limitsApp(e),{fields:t.join(",")}))}listCharges(e={}){return this.request("GET",d(r.charges(),e))}listSpendLimits(){return this.request("GET",r.spendLimits())}setSpendLimit(e,t){return this.request("PUT",r.spendLimit(e),t)}removeSpendLimit(e){return this.request("DELETE",r.spendLimit(e))}listSpaces(){return this.request("GET",r.spaces())}subscribe(e,t){return this.request("POST",r.nodeSubscriptions(this.nodePath(e)),t)}listFocuses(){return this.request("GET",r.focuses())}focusOf(e){return this.request("GET",d(r.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",d(r.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",r.focuses(),e)}async setFocusPane(e,t){await this.request("PATCH",r.focus(e),t)}async closeFocus(e){await this.request("DELETE",r.focus(e))}async unsubscribe(e,t){await this.request("DELETE",r.nodeSubscription(this.nodePath(e),this.nodePath(t)))}armCron(e){return this.request("POST",r.crons(),e)}listCrons(e){return this.request("GET",d(r.crons(),e))}showCron(e,t){return this.request("GET",d(r.cron(this.cronPath(e)),t))}pauseCron(e,t){return this.request("POST",d(r.cronPause(this.cronPath(e)),t),{})}resumeCron(e,t){return this.request("POST",d(r.cronResume(this.cronPath(e)),t),{})}runCron(e,t){return this.request("POST",d(r.cronRun(this.cronPath(e)),t),{})}async cancelCron(e,t){await this.request("DELETE",d(r.cron(this.cronPath(e)),t))}pokeCrons(){return this.request("POST",r.cronsPoke(),{})}ensureAttach(e,t){return this.request("POST",r.nodeAttach(this.nodePath(e)),t??{})}getReports(e,t){return this.request("GET",d(r.nodeReports(this.nodePath(e)),t))}getTranscript(e,t){return this.request("GET",d(r.nodeTranscript(this.nodePath(e)),t))}getSnapshot(e){return this.request("GET",r.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",r.nodeSubject(this.nodePath(e)))}getNodeMessages(e,t){return this.request("GET",d(r.nodeMessages(this.nodePath(e)),t))}getSession(e){return this.request("GET",r.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",r.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",d(r.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",r.nodeContext(this.nodePath(e)))}peekFile(e,t,n){return this.request("GET",d(r.filePeek(),{path:e,encoding:t}),void 0,n)}writeFile(e,t,n,s){return this.request("POST",r.fileWrite(),{path:e,content:t,encoding:n},s)}listFiles(e,t,n){return this.request("GET",d(r.fileList(),{path:e,limit:t}),void 0,n)}runBash(e,t){return this.request("POST",r.bash(),e,t)}objects={read:o((e,t)=>this.request("GET",d(r.object(e),t)),"read"),list:o(e=>this.request("GET",d(r.objects(),e)),"list"),search:o(e=>this.request("POST",r.objectsSearch(),e),"search"),watch:o((e,t={})=>this.request("POST",r.objectWatch(e),t),"watch"),unwatch:o((e,t)=>this.request("DELETE",d(r.objectWatch(e),t)),"unwatch"),edges:o((e,t)=>this.request("GET",d(r.objectEdges(e),t)),"edges")};docs={write:o(e=>this.request("POST",r.docs(),e),"write"),edit:o((e,t)=>this.request("PATCH",r.doc(e),t),"edit"),move:o((e,t)=>this.request("POST",r.docMove(e),t),"move"),delete:o(e=>this.request("DELETE",r.doc(e)),"delete"),history:o((e,t)=>this.request("GET",d(r.docHistory(e),t)),"history"),lint:o((e={})=>this.request("POST",r.docsLint(),e),"lint")};documents={browserAccess:o(()=>this.request("GET",r.documentsBrowserAccess()),"browserAccess"),reconcilePackages:o(e=>this.request("POST",r.documentsReconcilePackages(),e),"reconcilePackages")};plugins={appToken:o(e=>this.request("GET",r.pluginAppToken(e)),"appToken"),callHeaders:o((e,t)=>this.request("POST",r.pluginCallHeaders(e),t),"callHeaders")};nodeDelivery(e,t){return this.request("POST",r.nodeDelivery(this.nodePath(e)),t)}deliveryDryRun(e){return this.request("POST",r.deliveryDryRun(),e)}recordBackgroundedJob(e,t,n){return this.request("POST",r.nodeJobBackground(this.nodePath(e),this.jobPath(t)),n)}ensureProfile(e,t){return this.request("PUT",r.profile(e),t??{})}createProfile(e){return this.request("POST",r.profiles(),e)}listProfiles(){return this.request("GET",r.profiles())}updateProfile(e,t){return this.request("PATCH",r.profile(e),t)}listAppEnv(){return this.request("GET",r.appEnv())}setAppEnv(e,t){return this.request("PUT",r.appEnvVar(e),{value:t})}removeAppEnv(e){return this.request("DELETE",r.appEnvVar(e))}listProfileEnv(e){return this.request("GET",r.profileEnv(e))}setProfileEnv(e,t,n){return this.request("PUT",r.profileEnvVar(e,t),{value:n})}removeProfileEnv(e,t){return this.request("DELETE",r.profileEnvVar(e,t))}getProfile(e){return this.request("GET",r.profile(e))}pauseProfile(e){return this.request("POST",r.profilePause(e),{})}resumeProfile(e){return this.request("POST",r.profileResume(e),{})}updateProfileMetadata(e,t){return this.request("PATCH",r.profileMetadata(e),t)}deleteProfile(e,t){return this.request("DELETE",r.profile(e),t)}getSettings(){return this.request("GET",r.settings())}putSettings(e){return this.request("PUT",r.settings(),e)}listModelAuth(){return this.request("GET",r.modelAuths())}getModelAuthReadiness(e){return this.request("GET",d(r.modelAuthReadiness(),e))}installCredential(e,t){return this.request("PUT",r.modelAuth(e),t)}removeCredential(e){return this.request("DELETE",r.modelAuth(e))}patchModelAuthAccount(e,t,n){return this.request("PATCH",r.modelAuthAccount(e,t),n)}removeModelAuthAccount(e,t){return this.request("DELETE",r.modelAuthAccount(e,t))}startModelAuth(e){return this.request("POST",r.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,t){return this.request("POST",r.modelAuthFlowComplete(e),t,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",r.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,t){return this.request("GET",d(r.modelAuthFlow(e),{wait:t}),void 0,{timeout:(t??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",r.humanReviews(),e)}listReviews(e){return this.request("GET",d(r.humanReviews(),e))}getReview(e){return this.request("GET",r.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",r.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,t={}){return this.request("POST",r.humanReviewCancel(this.reviewPath(e)),t)}getReviewDocumentBase(e){return this.request("GET",r.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,t){const n=e===void 0?"self":this.reviewPath(e);return this.request("POST",r.humanReviewComments(n),t)}listReviewComments(e,t){const n=e===void 0?"self":this.reviewPath(e);return this.request("GET",d(r.humanReviewComments(n),t))}readReviewCommentEvents(e,t){return this.request("GET",d(r.humanReviewCommentEvents(this.reviewPath(e)),t))}updateReviewCommentRanges(e,t){return this.request("POST",r.humanReviewCommentRanges(this.reviewPath(e)),t)}getReviewComment(e){return this.request("GET",r.humanComment(this.commentPath(e)))}editReviewComment(e,t){return this.request("POST",r.humanCommentEdit(this.commentPath(e)),t)}resolveReviewComment(e,t={}){return this.request("POST",r.humanCommentResolve(this.commentPath(e)),t)}reopenReviewComment(e,t={}){return this.request("POST",r.humanCommentReopen(this.commentPath(e)),t)}deleteReviewComment(e,t={}){return this.request("POST",r.humanCommentDelete(this.commentPath(e)),t)}forkReviewComment(e){return this.request("POST",r.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",r.humanInbox())}getHumanInboxPage(e){return this.request("GET",r.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,t={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",d(r.humanInbox()+"/history",{node_id:e,state:t.state}))}respondHumanInboxPage(e,t){return this.request("POST",r.humanInboxRespond(this.ticketId(e)),t)}postInboxProgress(e,t){return this.request("POST",r.humanInboxProgress(this.ticketId(e)),{responses:t})}getInboxResponse(e){return this.request("GET",r.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,t){return this.request("POST",r.humanInboxCancel(this.ticketId(e)),t??{})}createHumanRequest(e){return this.request("POST",r.humanRequests(),e)}listPageComponents(){return this.request("GET",r.humanComponents())}getHumanRequest(e){return this.request("GET",r.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,t){return this.request("POST",r.humanRequestReplace(this.requestPath(e)),t)}respondHumanRequest(e,t){return this.request("POST",r.humanRequestRespond(this.requestPath(e)),t)}dismissHumanRequest(e,t={}){return this.request("POST",r.humanRequestDismiss(this.requestPath(e)),t)}cancelHumanRequest(e,t={}){return this.request("POST",r.humanRequestCancel(this.requestPath(e)),t)}resolvePageFeedbackComment(e,t,n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(t)}`);return this.request("POST",r.humanInboxFeedbackResolve(this.ticketId(e),t),{node_id:n})}async dashboard(e){const t=e?.under!==void 0?{under:e.under}:void 0,[n,s]=await Promise.all([this.listNodes(t),this.status()]);return{nodes:n,counts:s.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",r.canvasAttention())}attentionCounts(e){const t={node_ids:e};return this.request("POST",r.canvasAttentionCounts(),t)}historySearch(e){return this.request("POST",r.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",r.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",d(r.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",r.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",r.canvasSnapshot())}analytics(e){return this.request("GET",d(r.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,t){await this.request("POST",r.nodeMemoryReads(this.nodePath(e)),t)}liveRoots(e={}){return this.request("GET",d(r.canvasLiveRoots(),e))}canvasRoster(){return this.request("GET",r.canvasRoster())}async canvasBrowseCompressed(){const e=await this.send("GET",r.canvasBrowse());return e.ok||await q(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",r.canvasGraph())}prune(e){return this.request("POST",r.canvasPrune(),e)}async request(e,t,n,s){try{const a=s===void 0?void 0:this.resolveBudget(s),u=await this.send(e,t,n,a);return await q(u,a?.deadlineAt)}catch(a){throw w(a,s?.signal)}}async rawResponse(e,t,n){try{return await this.send(e,t,void 0,n)}catch(s){throw w(s,n?.signal)}}async send(e,t,n,s={}){const a=this.resolveBudget(s),u=e==="GET"||e==="HEAD"||e==="DELETE",c=a.maxRetries??this.maxRetries,l=Math.min(a.deadlineAt??1/0,Date.now()+j);for(let m=0;;m++){let h;try{h=await this.transport(e,t,n,a)}catch(P){if(this.isColdSocketError(P)||this.isInterruptedSocketError(P)){const T=this.availabilityFailure?.();if(T!==void 0)throw T}if(this.isColdSocketError(P))try{await this.handleColdSocket(P,a.deadlineAt),h=await this.transport(e,t,n,a)}catch(T){throw a.deadlineAt!==void 0&&Date.now()>=a.deadlineAt&&!A(T,a.signal)?S(a.deadlineAt):w(T,a.signal)}else{if(this.isInterruptedSocketError(P)&&this.localSocketTransport&&(!u||m<c))return await this.rideOutInterruptedRequest(e,t,n,a);if(u&&m<c&&!A(P,a.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(P))){await R(G(m+1),a);continue}else throw w(P,a.signal)}}if(J(e)&&c>0&&h.status===503&&await W(h,a.deadlineAt)){const P=Math.max(250,(D(h)??0)*1e3)+Math.random()*250;if(Date.now()+P>=l)return h;await g(h,a.deadlineAt),await R(P,{signal:a.signal});continue}if(u&&m<c&&z(h.status)){await g(h,a.deadlineAt),await R(G(m+1),a,D(h));continue}return h}}resolveBudget(e){const{budgetMs:t,deadlineAt:n,...s}=e;if(t===void 0&&n===void 0)return s;if(t!==void 0&&(!Number.isFinite(t)||t<=0||t>y))throw new RangeError(`budgetMs must be a positive finite number of at most ${y}`);if(n!==void 0&&(!Number.isFinite(n)||n-Date.now()>y))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${y} ms from now`);return{...s,deadlineAt:Math.min(n??1/0,t===void 0?1/0:Date.now()+t)}}async awaitWithinBudget(e,t){if(t===void 0)return e;const n=t-Date.now();if(n<=0)throw p(t);let s;try{return await Promise.race([e,new Promise((a,u)=>{s=setTimeout(()=>u(p(t)),n)})])}finally{s!==void 0&&clearTimeout(s)}}async sendOnce(e,t,n,s={}){const a=this.resolveBudget(s);try{return await q(await this.transport(e,t,n,a))}catch(u){throw w(u,a.signal)}}nodePath(e){if(!b(e))throw new f(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!B(e))throw new f(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!L(e))throw new f(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!b(e))throw new f(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!b(e))throw new f(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new f(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,t,n,s={}){const a=s.deadlineAt===void 0?void 0:s.deadlineAt-Date.now();if(a!==void 0&&a<=0)return Promise.reject(p(s.deadlineAt));const u=n===void 0?void 0:JSON.stringify(n),c={accept:"application/json",...this.headers,...s.headers};u!==void 0&&(c["content-type"]="application/json");const l=s.timeout??this.timeoutMs,m=a===void 0?l:l>0?Math.min(l,a):a,h=new AbortController,P=a!==void 0&&(l<=0||a<=l),T=m>0?setTimeout(()=>h.abort(P?p(s.deadlineAt):new DOMException("request timed out","TimeoutError")),m):void 0,E=s.signal,k=o(()=>h.abort(E?.reason),"onExternalAbort");E!==void 0&&(E.aborted?h.abort(E.reason):E.addEventListener("abort",k,{once:!0}));const C=o(()=>{T!==void 0&&clearTimeout(T),E?.removeEventListener("abort",k)},"finish");return V(this.fetch(new URL(t,this.baseUrl),{method:e,headers:c,body:u,signal:h.signal}),h.signal).then(v=>this.retainRequestLifetime(v,C,()=>h.signal.aborted?h.signal.reason:void 0),v=>{throw C(),v})}retainRequestLifetime(e,t,n){if(e.body===null)return t(),e;const s=e.body.getReader();let a=!1;const u=o(()=>{a||(a=!0,t())},"close"),c=new ReadableStream({async pull(l){try{const{done:m,value:h}=await s.read();m?(u(),l.close()):l.enqueue(h)}catch(m){u(),l.error(n()??m)}},async cancel(l){u(),await s.cancel(l)}});return new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){const t=O(e);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"}isInterruptedSocketError(e){const t=O(e);return t==="ECONNRESET"||t==="EPIPE"}async rideOutInterruptedRequest(e,t,n,s={}){try{await this.awaitAvailability(void 0,s.deadlineAt)}catch(a){throw w(a,s.signal)}if(e!=="GET"&&e!=="HEAD")throw new f(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,t,n,s)}catch(a){throw w(a,s.signal)}}async awaitAvailability(e,t){const n=t===void 0?void 0:t-Date.now();if(n!==void 0&&n<=0)throw p(t);let s,a;try{await U({windowMs:Math.min(this.coldStartPollWindowMs,n??this.coldStartPollWindowMs),initialError:e,retry:o(u=>u!==s&&u!==a,"retry"),probe:o(async u=>{const c=this.availabilityFailure?.();if(c!==void 0)throw a=c,c;const l=this.coldStartFailure?.();if(l!==void 0)throw s=new f(503,"daemon_unavailable",`crtrd failed to start: ${l}`),s;const m=await this.transport("GET",r.healthz(),void 0,{timeout:u});if(m.status>=200&&m.status<300){await g(m);return}const h=await m.text();try{if(typeof JSON.parse(h).startup_blocked=="string")return}catch{}throw new f(m.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${m.status}: ${h.slice(0,500)}`)},"probe")})}catch(u){throw u===s&&(this.startupFailureReported=!0),u}}async handleColdSocket(e,t){const n=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;n&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),t));try{await this.awaitAvailability(e,t)}catch(s){if(n&&!this.startupFailureReported){const a=K(this.coldStartDiagnostic);if(a!==void 0){const u=w(s);throw new f(u.status,u.code,`${u.message}
|
|
3
|
-
${a}`)}}throw s}}}function d(i,e){if(e===void 0)return i;const t=new URLSearchParams;for(const[s,a]of Object.entries(e))a!=null&&t.set(s,String(a));const n=t.toString();return n===""?i:`${i}?${n}`}o(d,"withQuery");async function q(i,e){const t=i.status>=200&&i.status<300,n=(await _(i,e)).trim();let s;if(n!=="")try{s=JSON.parse(n)}catch{if(t)return;throw new f(i.status,"invalid_response",n.slice(0,500),void 0,i.headers)}if(t)return s;throw N(s)?new f(i.status,s.error.code,s.error.message,s.error.details,i.headers,s.error):new f(i.status,"internal",`request failed with status ${i.status}`,void 0,i.headers)}o(q,"parse");const j=6e4;function J(i){return i==="GET"||i==="HEAD"}o(J,"isRead");async function W(i,e){try{if(Number(i.headers.get("content-length")??0)>8192)return!1;const t=await _(i.clone(),Math.min(e??1/0,Date.now()+5e3)),n=JSON.parse(t).error;return n?.origin==="router"&&n.details?.forwarded===!1&&(n.details.runtime_state==="creating"||n.details.runtime_state==="recovering")}catch{return!1}}o(W,"isRefusedBeforeForwarding");function z(i){return i===429||i>=500}o(z,"isRetryableStatus");async function g(i,e){const t=(async()=>{try{await i.body?.cancel()}catch{}})();if(e===void 0)return t;let n;try{await Promise.race([t,new Promise(s=>{n=setTimeout(s,Math.max(0,e-Date.now()))})])}finally{n!==void 0&&clearTimeout(n)}}o(g,"drainResponseBody");async function _(i,e){if(e===void 0)return i.text();const t=e-Date.now(),n=i.text();if(n.catch(()=>{}),t<=0)throw i.body?.cancel().catch(()=>{}),S(e);let s;try{return await Promise.race([n,new Promise((a,u)=>{s=setTimeout(()=>{i.body?.cancel().catch(()=>{}),u(S(e))},t)})])}finally{s!==void 0&&clearTimeout(s)}}o(_,"readTextWithin");function G(i){return Math.min(2e3,250*2**(i-1))}o(G,"retryDelayMs");function O(i){if(typeof i!="object"||i===null)return;const e=i.code;if(typeof e=="string")return e;const t=i.cause;if(typeof t=="object"&&t!==null){const n=t.code;if(typeof n=="string")return n}}o(O,"transportErrorCode");function A(i,e){return e?.aborted?!0:i instanceof DOMException&&(i.name==="AbortError"||i.name==="TimeoutError")}o(A,"isAbortError");function w(i,e){if(e?.aborted)return new f(0,"request_aborted","request aborted by caller signal");if(i instanceof f)return i;if(i instanceof DOMException&&i.name==="TimeoutError")return new f(504,"request_timeout",`crtrd request timed out: ${i.message}`);if(i instanceof DOMException&&i.name==="AbortError")return new f(0,"request_aborted","request aborted by caller signal");const t=O(i),n=i instanceof Error?i.message:String(i);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"?new f(503,"daemon_unavailable",`crtrd is not reachable: ${n}`):t==="ETIMEDOUT"?new f(504,"request_timeout",`crtrd request timed out: ${n}`):new f(503,"transport_error",n)}o(w,"toTransportApiError");function D(i){const e=Number(i.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}o(D,"retryAfterHeaderS");async function R(i,e,t,n){const{deadlineAt:s,signal:a}=e;if(a?.aborted)throw new f(0,"request_aborted","request aborted by caller signal");const u=s!==void 0&&t!==void 0?t*1e3:void 0,c=Math.max(i,u??0);if(s!==void 0&&Date.now()+c>=s){const l=S(s,u!==void 0&&u>=i?"retry_after":"elapsed",u===void 0?void 0:t);throw n!==void 0&&Object.defineProperty(l,"cause",{value:n,configurable:!0,writable:!0}),l}if(a===void 0)return M(c);await new Promise((l,m)=>{const h=o(()=>{clearTimeout(P),a.removeEventListener("abort",h),m(new f(0,"request_aborted","request aborted by caller signal"))},"onAbort"),P=setTimeout(()=>{a.removeEventListener("abort",h),l()},c);a.addEventListener("abort",h,{once:!0})})}o(R,"sleepWithin");function
|
|
1
|
+
var x=Object.defineProperty;var o=(i,e)=>x(i,"name",{value:e,configurable:!0});import{ApiError as f,isErrorBody as N}from"./errors.js";import{routes as r}from"./routes.js";import{isSafeNodeId as b}from"./dto/common.js";import{isSafeBashJobId as B}from"./dto/bash-jobs.js";import{isSafeCronId as L}from"./dto/crons.js";const I=3e4,F=Symbol.for("@north-light/api/local-socket-fetch"),$=1e4,H=200;async function U({windowMs:i,probe:e,initialError:t,pollIntervalMs:n=H,retry:s=o(()=>!0,"retry"),now:a=Date.now,sleep:u=M}){const c=a()+i;let l=t;for(;;){const m=c-a();if(m<=0)throw l??new Error("crtrd availability window expired without a probe failure");try{await e(m);return}catch(P){if(l=P,!s(P))throw P}const h=c-a();if(h<=0)throw l;await u(Math.min(n,h))}}o(U,"waitForDaemonAvailability");const y=2147483647;function S(i,e="elapsed",t){const n=e==="retry_after"?`the server asked to retry after ${t}s, which is later than the call's deadline (${new Date(i).toISOString()}); not waiting`:`the call's deadline (${new Date(i).toISOString()}) passed`;return new f(504,"deadline_exceeded",n,{deadline_at:i,reason:e,...t===void 0?{}:{retry_after_s:t}})}o(S,"deadlineExceeded");const p=o(i=>S(i??Date.now()),"budgetExhausted");class ne{static{o(this,"CrtrClient")}baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;availabilityFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??I,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[F]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),e.availabilityFailure!==void 0&&(this.availabilityFailure=e.availabilityFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??$}healthz(){return this.request("GET",r.healthz())}async probeHealthz(e){const t=await this.transport("GET",r.healthz(),void 0,{timeout:e});if(t.status===503)try{const n=await t.clone().json();if(typeof n.startup_blocked=="string")return n}catch{}return q(t)}async ready(){const e=await this.transport("GET",r.ready(),void 0,{});if(e.status===503)try{const t=await e.clone().json();if(t.ready===!1)return t}catch{}return q(e)}status(){return this.request("GET",r.status())}due(){return this.request("GET",r.due())}restartDaemon(){return this.request("POST",r.daemonRestart())}drainDaemon(e={}){const t=e.settle_limit_ms??0;return this.request("POST",r.daemonDrain(),e,{timeout:t+this.timeoutMs})}endDaemonDrain(){return this.request("DELETE",r.daemonDrain())}admitDaemon(){return this.request("POST",r.daemonAdmit())}migrateState(e){return this.request("POST",r.daemonMigrate(),e)}appendNodeLog(e,t){return this.request("POST",r.nodeLog(this.nodePath(e)),t)}async putNodeTelemetry(e,t){await this.request("PUT",r.nodeTelemetry(this.nodePath(e)),t)}async putNodeSummaries(e,t){await this.request("PUT",r.nodeSummaries(this.nodePath(e)),t)}async putNodeRecap(e,t){await this.request("PUT",r.nodeRecap(this.nodePath(e)),t)}readNodeInboxReport(e,t,n){return this.request("GET",d(r.nodeInboxReport(this.nodePath(e)),{ref:t,execution_id:n}))}listNodeAttachments(e){return this.request("GET",r.nodeAttachments(this.nodePath(e)))}async readNodeAttachment(e,t){const n=await this.send("GET",r.nodeAttachment(this.nodePath(e),t));return n.ok||await q(n),new Uint8Array(await n.arrayBuffer())}readNodePassiveMessage(e,t){return this.request("GET",d(r.nodePassiveMessage(this.nodePath(e)),{ref:t}))}nodePushedFinal(e,t){return this.request("POST",r.nodePushedFinal(this.nodePath(e)),t)}createNode(e){return this.request("POST",r.nodes(),e)}listNodes(e){return this.request("GET",d(r.nodes(),e))}getNode(e){return this.request("GET",r.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:t}={}){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",d(r.nodeOutcome(this.nodePath(e)),{wait:t}),void 0,{timeout:(t??0)*1e3+this.timeoutMs})}getNodeEvents(e,t={},n={}){if(t.after!==void 0&&(!Number.isSafeInteger(t.after)||t.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",d(r.nodeEvents(this.nodePath(e)),t),void 0,{...n,headers:{accept:"text/event-stream",...n.headers??{}},timeout:0})}async*getBrokerSignals(e,t,n={}){const s=await this.send("GET",d(r.nodeBrokerSignals(this.nodePath(e)),{execution_id:t}),void 0,{...n,headers:{accept:"application/x-ndjson",...n.headers??{}},timeout:0});if(!s.ok){await q(s);return}if(s.body===null)throw new f(s.status,"invalid_response","broker signal stream has no body");const a=s.body.getReader(),u=new TextDecoder;let c="";try{for(;;){const{done:l,value:m}=await a.read();if(l)break;c+=u.decode(m,{stream:!0});let h;for(;(h=c.indexOf(`
|
|
2
|
+
`))!==-1;){const P=c.slice(0,h);c=c.slice(h+1),P!==""&&(yield JSON.parse(P))}}if(c+=u.decode(),c.trim()!=="")throw new f(502,"invalid_response","broker signal stream ended mid-line")}finally{await a.cancel().catch(()=>{})}}createStructuredRequest(e,t){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,t):this.request("POST","/v1/structured-requests",e,t)}getStructuredRequest(e,{wait:t=0,budgetMs:n}={}){if(!Number.isInteger(t)||t<0||t>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",d(`/v1/structured-requests/${this.requestPath(e)}`,{wait:t}),void 0,{budgetMs:n})}cancelStructuredRequest(e,t){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},t)}registerOutcomeDelivery(e,t){return this.request("PUT",r.nodeOutcomeDelivery(this.nodePath(e)),t)}getOutcomeDelivery(e){return this.request("GET",r.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",r.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",r.nodeJobs(this.nodePath(e)))}readBashJobOutput(e,t,n={}){const s=new URLSearchParams;n.tail_lines!==void 0&&s.set("tail_lines",String(n.tail_lines)),n.max_bytes!==void 0&&s.set("max_bytes",String(n.max_bytes));const a=s.size===0?"":`?${s.toString()}`;return this.request("GET",`${r.nodeJobOutput(this.nodePath(e),this.jobPath(t))}${a}`)}stopBashJob(e,t){return this.request("DELETE",r.nodeJob(this.nodePath(e),this.jobPath(t)))}async patchBashJob(e,t,n){await this.request("PATCH",r.nodeJob(this.nodePath(e),this.jobPath(t)),n)}async reportBashJob(e,t,n){await this.request("POST",r.nodeJobReport(this.nodePath(e),this.jobPath(t)),n)}sendMessage(e,t){return this.request("POST",r.nodeMessages(this.nodePath(e)),t)}interruptNode(e){return this.request("POST",r.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,t){return this.request("POST",r.nodeReports(this.nodePath(e)),t)}submitResult(e,t){return this.request("POST",r.nodeResult(this.nodePath(e)),t)}forkNode(e){return this.request("POST",r.nodeFork(this.nodePath(e)),{})}reviveNode(e,t){return this.request("POST",r.nodeRevive(this.nodePath(e)),t??{})}relaunchRoot(e){return this.request("POST",r.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,t){return this.request("POST",r.nodeBrokerSessionBound(this.nodePath(e)),t)}settleBroker(e,t){return this.request("POST",r.nodeBrokerSettle(this.nodePath(e)),t)}async postBrokerIdle(e,t){await this.request("POST",r.nodeBrokerIdle(this.nodePath(e)),t)}completeBrokerPark(e,t){return this.request("POST",r.nodeBrokerParkComplete(this.nodePath(e)),t)}recordBrokerParkActivity(e,t){return this.request("POST",r.nodeBrokerParkActivity(this.nodePath(e)),t)}async recordBrokerTelemetry(e,t){await this.request("POST",r.nodeBrokerTelemetry(this.nodePath(e)),t)}claimNodeMail(e,t){return this.request("POST",r.nodeMailClaim(this.nodePath(e)),t)}acknowledgeNodeMail(e,t){return this.request("POST",r.nodeMailAcknowledge(this.nodePath(e)),t)}recordBrokerTurn(e,t){return this.request("POST",r.brokerTurn(this.nodePath(e)),t)}mutateBrokerProviderRetry(e,t){return this.request("POST",r.brokerProviderRetry(this.nodePath(e)),t)}mutateBrokerFault(e,t){return this.request("POST",r.brokerFault(this.nodePath(e)),t)}getBrokerRecovery(e,t){return this.request("GET",`${r.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(t)}`)}recordNodeFault(e,t){return this.request("POST",r.nodeFault(this.nodePath(e)),t)}clearNodeFault(e,t={}){const n=new URLSearchParams;t.link!==void 0&&n.set("link",t.link),t.preserve_episode!==void 0&&n.set("preserve_episode",String(t.preserve_episode));const s=n.size===0?"":`?${n.toString()}`;return this.request("DELETE",`${r.nodeFault(this.nodePath(e))}${s}`)}commitBrokerModel(e,t){return this.request("POST",r.nodeBrokerModel(this.nodePath(e)),t)}executionStart(e){return this.request("GET",r.executionStart(e))}executionImportUnpacked(e){return this.request("POST",r.executionImportUnpacked(e),{})}gitCredential(e,t){return this.request("POST",r.environmentGitCredential(e),t)}brokerExtensionState(e){return this.request("GET",r.nodeBrokerExtensionState(this.nodePath(e)))}brokerStructuredRequest(e){return this.request("GET",r.nodeBrokerStructuredRequest(this.nodePath(e)))}captureBrokerGoal(e,t){return this.request("POST",r.nodeBrokerGoal(this.nodePath(e)),t)}commitBrokerGeneratedName(e,t){return this.request("POST",r.nodeBrokerGeneratedName(this.nodePath(e)),t)}commitBrokerPersonaAck(e,t){return this.request("POST",r.nodeBrokerPersonaAck(this.nodePath(e)),t)}closeNode(e,t){return this.request("POST",r.nodeClose(this.nodePath(e)),t??{})}async markNodeRead(e){await this.request("POST",r.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",r.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",r.nodeDemote(this.nodePath(e)),{})}promoteNode(e,t){return this.request("POST",r.nodePromote(this.nodePath(e)),t)}yieldNode(e,t){return this.request("POST",r.nodeYield(this.nodePath(e)),t)}waitNode(e,t){return this.request("POST",r.nodeWait(this.nodePath(e)),t)}listKinds(){return this.request("GET",r.kinds())}patchConfig(e,t){return this.request("PATCH",r.nodeConfig(this.nodePath(e)),t,t.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",r.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,t){return this.request("POST",r.nodeWorktreeAbandon(this.nodePath(e)),t)}retryDelivery(e){return this.request("POST",r.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",r.quarantinedWorktrees())}showLimits(){return this.request("GET",r.limits())}setAppLimits(e,t){return this.request("PUT",r.limitsApp(e),t)}removeAppLimits(e,t){return this.request("DELETE",d(r.limitsApp(e),{fields:t.join(",")}))}listCharges(e={}){return this.request("GET",d(r.charges(),e))}listSpendLimits(){return this.request("GET",r.spendLimits())}setSpendLimit(e,t){return this.request("PUT",r.spendLimit(e),t)}removeSpendLimit(e){return this.request("DELETE",r.spendLimit(e))}listSpaces(){return this.request("GET",r.spaces())}subscribe(e,t){return this.request("POST",r.nodeSubscriptions(this.nodePath(e)),t)}listFocuses(){return this.request("GET",r.focuses())}focusOf(e){return this.request("GET",d(r.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",d(r.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",r.focuses(),e)}async setFocusPane(e,t){await this.request("PATCH",r.focus(e),t)}async closeFocus(e){await this.request("DELETE",r.focus(e))}async unsubscribe(e,t){await this.request("DELETE",r.nodeSubscription(this.nodePath(e),this.nodePath(t)))}armCron(e){return this.request("POST",r.crons(),e)}listCrons(e){return this.request("GET",d(r.crons(),e))}showCron(e,t){return this.request("GET",d(r.cron(this.cronPath(e)),t))}pauseCron(e,t){return this.request("POST",d(r.cronPause(this.cronPath(e)),t),{})}resumeCron(e,t){return this.request("POST",d(r.cronResume(this.cronPath(e)),t),{})}runCron(e,t){return this.request("POST",d(r.cronRun(this.cronPath(e)),t),{})}async cancelCron(e,t){await this.request("DELETE",d(r.cron(this.cronPath(e)),t))}pokeCrons(){return this.request("POST",r.cronsPoke(),{})}ensureAttach(e,t){return this.request("POST",r.nodeAttach(this.nodePath(e)),t??{})}getReports(e,t){return this.request("GET",d(r.nodeReports(this.nodePath(e)),t))}getTranscript(e,t){return this.request("GET",d(r.nodeTranscript(this.nodePath(e)),t))}getSnapshot(e){return this.request("GET",r.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",r.nodeSubject(this.nodePath(e)))}getNodeMessages(e,t){return this.request("GET",d(r.nodeMessages(this.nodePath(e)),t))}getSession(e){return this.request("GET",r.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",r.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",d(r.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",r.nodeContext(this.nodePath(e)))}peekFile(e,t,n){return this.request("GET",d(r.filePeek(),{path:e,encoding:t}),void 0,n)}writeFile(e,t,n,s){return this.request("POST",r.fileWrite(),{path:e,content:t,encoding:n},s)}listFiles(e,t,n){return this.request("GET",d(r.fileList(),{path:e,limit:t}),void 0,n)}runBash(e,t){return this.request("POST",r.bash(),e,t)}objects={read:o((e,t)=>this.request("GET",d(r.object(e),t)),"read"),list:o(e=>this.request("GET",d(r.objects(),e)),"list"),search:o(e=>this.request("POST",r.objectsSearch(),e),"search"),watch:o((e,t={})=>this.request("POST",r.objectWatch(e),t),"watch"),unwatch:o((e,t)=>this.request("DELETE",d(r.objectWatch(e),t)),"unwatch"),edges:o((e,t)=>this.request("GET",d(r.objectEdges(e),t)),"edges")};docs={write:o(e=>this.request("POST",r.docs(),e),"write"),edit:o((e,t)=>this.request("PATCH",r.doc(e),t),"edit"),move:o((e,t)=>this.request("POST",r.docMove(e),t),"move"),delete:o(e=>this.request("DELETE",r.doc(e)),"delete"),history:o((e,t)=>this.request("GET",d(r.docHistory(e),t)),"history"),lint:o((e={})=>this.request("POST",r.docsLint(),e),"lint")};documents={browserAccess:o(()=>this.request("GET",r.documentsBrowserAccess()),"browserAccess"),reconcilePackages:o(e=>this.request("POST",r.documentsReconcilePackages(),e),"reconcilePackages")};plugins={appToken:o(e=>this.request("GET",r.pluginAppToken(e)),"appToken"),callHeaders:o((e,t)=>this.request("POST",r.pluginCallHeaders(e),t),"callHeaders")};nodeDelivery(e,t){return this.request("POST",r.nodeDelivery(this.nodePath(e)),t)}deliveryDryRun(e){return this.request("POST",r.deliveryDryRun(),e)}recordBackgroundedJob(e,t,n){return this.request("POST",r.nodeJobBackground(this.nodePath(e),this.jobPath(t)),n)}ensureProfile(e,t){return this.request("PUT",r.profile(e),t??{})}createProfile(e){return this.request("POST",r.profiles(),e)}listProfiles(){return this.request("GET",r.profiles())}updateProfile(e,t){return this.request("PATCH",r.profile(e),t)}listAppEnv(){return this.request("GET",r.appEnv())}setAppEnv(e,t){return this.request("PUT",r.appEnvVar(e),{value:t})}removeAppEnv(e){return this.request("DELETE",r.appEnvVar(e))}listProfileEnv(e){return this.request("GET",r.profileEnv(e))}setProfileEnv(e,t,n){return this.request("PUT",r.profileEnvVar(e,t),{value:n})}removeProfileEnv(e,t){return this.request("DELETE",r.profileEnvVar(e,t))}getProfile(e){return this.request("GET",r.profile(e))}pauseProfile(e){return this.request("POST",r.profilePause(e),{})}resumeProfile(e){return this.request("POST",r.profileResume(e),{})}updateProfileMetadata(e,t){return this.request("PATCH",r.profileMetadata(e),t)}deleteProfile(e,t){return this.request("DELETE",r.profile(e),t)}getSettings(){return this.request("GET",r.settings())}putSettings(e){return this.request("PUT",r.settings(),e)}listModelAuth(){return this.request("GET",r.modelAuths())}getModelAuthReadiness(e){return this.request("GET",d(r.modelAuthReadiness(),e))}installCredential(e,t){return this.request("PUT",r.modelAuth(e),t)}removeCredential(e){return this.request("DELETE",r.modelAuth(e))}patchModelAuthAccount(e,t,n){return this.request("PATCH",r.modelAuthAccount(e,t),n)}removeModelAuthAccount(e,t){return this.request("DELETE",r.modelAuthAccount(e,t))}startModelAuth(e){return this.request("POST",r.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,t){return this.request("POST",r.modelAuthFlowComplete(e),t,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",r.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,t){return this.request("GET",d(r.modelAuthFlow(e),{wait:t}),void 0,{timeout:(t??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",r.humanReviews(),e)}listReviews(e){return this.request("GET",d(r.humanReviews(),e))}getReview(e){return this.request("GET",r.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",r.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,t={}){return this.request("POST",r.humanReviewCancel(this.reviewPath(e)),t)}getReviewDocumentBase(e){return this.request("GET",r.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,t){const n=e===void 0?"self":this.reviewPath(e);return this.request("POST",r.humanReviewComments(n),t)}listReviewComments(e,t){const n=e===void 0?"self":this.reviewPath(e);return this.request("GET",d(r.humanReviewComments(n),t))}readReviewCommentEvents(e,t){return this.request("GET",d(r.humanReviewCommentEvents(this.reviewPath(e)),t))}updateReviewCommentRanges(e,t){return this.request("POST",r.humanReviewCommentRanges(this.reviewPath(e)),t)}getReviewComment(e){return this.request("GET",r.humanComment(this.commentPath(e)))}editReviewComment(e,t){return this.request("POST",r.humanCommentEdit(this.commentPath(e)),t)}resolveReviewComment(e,t={}){return this.request("POST",r.humanCommentResolve(this.commentPath(e)),t)}reopenReviewComment(e,t={}){return this.request("POST",r.humanCommentReopen(this.commentPath(e)),t)}deleteReviewComment(e,t={}){return this.request("POST",r.humanCommentDelete(this.commentPath(e)),t)}forkReviewComment(e){return this.request("POST",r.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",r.humanInbox())}getHumanInboxPage(e){return this.request("GET",r.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e,t={}){if(e!==void 0&&(typeof e!="string"||e===""))throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",d(r.humanInbox()+"/history",{node_id:e,state:t.state}))}respondHumanInboxPage(e,t){return this.request("POST",r.humanInboxRespond(this.ticketId(e)),t)}postInboxProgress(e,t){return this.request("POST",r.humanInboxProgress(this.ticketId(e)),{responses:t})}getInboxResponse(e){return this.request("GET",r.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,t){return this.request("POST",r.humanInboxCancel(this.ticketId(e)),t??{})}createHumanRequest(e){return this.request("POST",r.humanRequests(),e)}listPageComponents(){return this.request("GET",r.humanComponents())}getHumanRequest(e){return this.request("GET",r.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,t){return this.request("POST",r.humanRequestReplace(this.requestPath(e)),t)}respondHumanRequest(e,t){return this.request("POST",r.humanRequestRespond(this.requestPath(e)),t)}dismissHumanRequest(e,t={}){return this.request("POST",r.humanRequestDismiss(this.requestPath(e)),t)}cancelHumanRequest(e,t={}){return this.request("POST",r.humanRequestCancel(this.requestPath(e)),t)}resolvePageFeedbackComment(e,t,n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(t))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(t)}`);return this.request("POST",r.humanInboxFeedbackResolve(this.ticketId(e),t),{node_id:n})}async dashboard(e){const t=e?.under!==void 0?{under:e.under}:void 0,[n,s]=await Promise.all([this.listNodes(t),this.status()]);return{nodes:n,counts:s.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",r.canvasAttention())}attentionCounts(e){const t={node_ids:e};return this.request("POST",r.canvasAttentionCounts(),t)}historySearch(e){return this.request("POST",r.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",r.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",d(r.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",r.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",r.canvasSnapshot())}analytics(e){return this.request("GET",d(r.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,t){await this.request("POST",r.nodeMemoryReads(this.nodePath(e)),t)}liveRoots(e={}){return this.request("GET",d(r.canvasLiveRoots(),e))}canvasRoster(){return this.request("GET",r.canvasRoster())}async canvasBrowseCompressed(){const e=await this.send("GET",r.canvasBrowse());return e.ok||await q(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",r.canvasGraph())}prune(e){return this.request("POST",r.canvasPrune(),e)}async request(e,t,n,s){try{const a=s===void 0?void 0:this.resolveBudget(s),u=await this.send(e,t,n,a);return await q(u,a?.deadlineAt)}catch(a){throw V(e,w(a,s?.signal))}}async rawResponse(e,t,n){try{return await this.send(e,t,void 0,n)}catch(s){throw w(s,n?.signal)}}async send(e,t,n,s={}){const a=this.resolveBudget(s),u=e==="GET"||e==="HEAD"||e==="DELETE",c=a.maxRetries??this.maxRetries,l=Math.min(a.deadlineAt??1/0,Date.now()+j);for(let m=0;;m++){let h;try{h=await this.transport(e,t,n,a)}catch(P){if(this.isColdSocketError(P)||this.isInterruptedSocketError(P)){const T=this.availabilityFailure?.();if(T!==void 0)throw T}if(this.isColdSocketError(P))try{await this.handleColdSocket(P,a.deadlineAt),h=await this.transport(e,t,n,a)}catch(T){throw a.deadlineAt!==void 0&&Date.now()>=a.deadlineAt&&!A(T,a.signal)?S(a.deadlineAt):w(T,a.signal)}else{if(this.isInterruptedSocketError(P)&&this.localSocketTransport&&(!u||m<c))return await this.rideOutInterruptedRequest(e,t,n,a);if(u&&m<c&&!A(P,a.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(P))){await R(G(m+1),a);continue}else throw w(P,a.signal)}}if(J(e)&&c>0&&h.status===503&&await W(h,a.deadlineAt)){const P=Math.max(250,(D(h)??0)*1e3)+Math.random()*250;if(Date.now()+P>=l)return h;await g(h,a.deadlineAt),await R(P,{signal:a.signal});continue}if(u&&m<c&&z(h.status)){await g(h,a.deadlineAt),await R(G(m+1),a,D(h));continue}return h}}resolveBudget(e){const{budgetMs:t,deadlineAt:n,...s}=e;if(t===void 0&&n===void 0)return s;if(t!==void 0&&(!Number.isFinite(t)||t<=0||t>y))throw new RangeError(`budgetMs must be a positive finite number of at most ${y}`);if(n!==void 0&&(!Number.isFinite(n)||n-Date.now()>y))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${y} ms from now`);return{...s,deadlineAt:Math.min(n??1/0,t===void 0?1/0:Date.now()+t)}}async awaitWithinBudget(e,t){if(t===void 0)return e;const n=t-Date.now();if(n<=0)throw p(t);let s;try{return await Promise.race([e,new Promise((a,u)=>{s=setTimeout(()=>u(p(t)),n)})])}finally{s!==void 0&&clearTimeout(s)}}async sendOnce(e,t,n,s={}){const a=this.resolveBudget(s);try{return await q(await this.transport(e,t,n,a))}catch(u){throw w(u,a.signal)}}nodePath(e){if(!b(e))throw new f(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!B(e))throw new f(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!L(e))throw new f(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!b(e))throw new f(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!b(e))throw new f(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new f(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,t,n,s={}){const a=s.deadlineAt===void 0?void 0:s.deadlineAt-Date.now();if(a!==void 0&&a<=0)return Promise.reject(p(s.deadlineAt));const u=n===void 0?void 0:JSON.stringify(n),c={accept:"application/json",...this.headers,...s.headers};u!==void 0&&(c["content-type"]="application/json");const l=s.timeout??this.timeoutMs,m=a===void 0?l:l>0?Math.min(l,a):a,h=new AbortController,P=a!==void 0&&(l<=0||a<=l),T=m>0?setTimeout(()=>h.abort(P?p(s.deadlineAt):new DOMException("request timed out","TimeoutError")),m):void 0,E=s.signal,k=o(()=>h.abort(E?.reason),"onExternalAbort");E!==void 0&&(E.aborted?h.abort(E.reason):E.addEventListener("abort",k,{once:!0}));const C=o(()=>{T!==void 0&&clearTimeout(T),E?.removeEventListener("abort",k)},"finish");return K(this.fetch(new URL(t,this.baseUrl),{method:e,headers:c,body:u,signal:h.signal}),h.signal).then(v=>this.retainRequestLifetime(v,C,()=>h.signal.aborted?h.signal.reason:void 0),v=>{throw C(),v})}retainRequestLifetime(e,t,n){if(e.body===null)return t(),e;const s=e.body.getReader();let a=!1;const u=o(()=>{a||(a=!0,t())},"close"),c=new ReadableStream({async pull(l){try{const{done:m,value:h}=await s.read();m?(u(),l.close()):l.enqueue(h)}catch(m){u(),l.error(n()??m)}},async cancel(l){u(),await s.cancel(l)}});return new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){const t=O(e);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"}isInterruptedSocketError(e){const t=O(e);return t==="ECONNRESET"||t==="EPIPE"}async rideOutInterruptedRequest(e,t,n,s={}){try{await this.awaitAvailability(void 0,s.deadlineAt)}catch(a){throw w(a,s.signal)}if(e!=="GET"&&e!=="HEAD")throw new f(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,t,n,s)}catch(a){throw w(a,s.signal)}}async awaitAvailability(e,t){const n=t===void 0?void 0:t-Date.now();if(n!==void 0&&n<=0)throw p(t);let s,a;try{await U({windowMs:Math.min(this.coldStartPollWindowMs,n??this.coldStartPollWindowMs),initialError:e,retry:o(u=>u!==s&&u!==a,"retry"),probe:o(async u=>{const c=this.availabilityFailure?.();if(c!==void 0)throw a=c,c;const l=this.coldStartFailure?.();if(l!==void 0)throw s=new f(503,"daemon_unavailable",`crtrd failed to start: ${l}`),s;const m=await this.transport("GET",r.healthz(),void 0,{timeout:u});if(m.status>=200&&m.status<300){await g(m);return}const h=await m.text();try{if(typeof JSON.parse(h).startup_blocked=="string")return}catch{}throw new f(m.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${m.status}: ${h.slice(0,500)}`)},"probe")})}catch(u){throw u===s&&(this.startupFailureReported=!0),u}}async handleColdSocket(e,t){const n=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;n&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),t));try{await this.awaitAvailability(e,t)}catch(s){if(n&&!this.startupFailureReported){const a=Q(this.coldStartDiagnostic);if(a!==void 0){const u=w(s);throw new f(u.status,u.code,`${u.message}
|
|
3
|
+
${a}`)}}throw s}}}function d(i,e){if(e===void 0)return i;const t=new URLSearchParams;for(const[s,a]of Object.entries(e))a!=null&&t.set(s,String(a));const n=t.toString();return n===""?i:`${i}?${n}`}o(d,"withQuery");async function q(i,e){const t=i.status>=200&&i.status<300,n=(await _(i,e)).trim();let s;if(n!=="")try{s=JSON.parse(n)}catch{if(t)return;throw new f(i.status,"invalid_response",n.slice(0,500),void 0,i.headers)}if(t)return s;throw N(s)?new f(i.status,s.error.code,s.error.message,s.error.details,i.headers,s.error):new f(i.status,"internal",`request failed with status ${i.status}`,void 0,i.headers)}o(q,"parse");const j=6e4;function J(i){return i==="GET"||i==="HEAD"}o(J,"isRead");async function W(i,e){try{if(Number(i.headers.get("content-length")??0)>8192)return!1;const t=await _(i.clone(),Math.min(e??1/0,Date.now()+5e3)),n=JSON.parse(t).error;return n?.origin==="router"&&n.details?.forwarded===!1&&(n.details.runtime_state==="creating"||n.details.runtime_state==="recovering")}catch{return!1}}o(W,"isRefusedBeforeForwarding");function z(i){return i===429||i>=500}o(z,"isRetryableStatus");async function g(i,e){const t=(async()=>{try{await i.body?.cancel()}catch{}})();if(e===void 0)return t;let n;try{await Promise.race([t,new Promise(s=>{n=setTimeout(s,Math.max(0,e-Date.now()))})])}finally{n!==void 0&&clearTimeout(n)}}o(g,"drainResponseBody");async function _(i,e){if(e===void 0)return i.text();const t=e-Date.now(),n=i.text();if(n.catch(()=>{}),t<=0)throw i.body?.cancel().catch(()=>{}),S(e);let s;try{return await Promise.race([n,new Promise((a,u)=>{s=setTimeout(()=>{i.body?.cancel().catch(()=>{}),u(S(e))},t)})])}finally{s!==void 0&&clearTimeout(s)}}o(_,"readTextWithin");function G(i){return Math.min(2e3,250*2**(i-1))}o(G,"retryDelayMs");function O(i){if(typeof i!="object"||i===null)return;const e=i.code;if(typeof e=="string")return e;const t=i.cause;if(typeof t=="object"&&t!==null){const n=t.code;if(typeof n=="string")return n}}o(O,"transportErrorCode");function A(i,e){return e?.aborted?!0:i instanceof DOMException&&(i.name==="AbortError"||i.name==="TimeoutError")}o(A,"isAbortError");function w(i,e){if(e?.aborted)return new f(0,"request_aborted","request aborted by caller signal");if(i instanceof f)return i;if(i instanceof DOMException&&i.name==="TimeoutError")return new f(504,"request_timeout",`crtrd request timed out: ${i.message}`);if(i instanceof DOMException&&i.name==="AbortError")return new f(0,"request_aborted","request aborted by caller signal");const t=O(i),n=i instanceof Error?i.message:String(i);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"?new f(503,"daemon_unavailable",`crtrd is not reachable: ${n}`):t==="ETIMEDOUT"?new f(504,"request_timeout",`crtrd request timed out: ${n}`):new f(503,"transport_error",n)}o(w,"toTransportApiError");function V(i,e){return i==="GET"||i==="HEAD"||e.status!==504||e.code!=="request_timeout"?e:new f(e.status,e.code,`${e.message}; the ${i} request was sent, so it may or may not have been applied`,{outcome:"unknown"},e.headers)}o(V,"withUnknownOutcome");function D(i){const e=Number(i.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}o(D,"retryAfterHeaderS");async function R(i,e,t,n){const{deadlineAt:s,signal:a}=e;if(a?.aborted)throw new f(0,"request_aborted","request aborted by caller signal");const u=s!==void 0&&t!==void 0?t*1e3:void 0,c=Math.max(i,u??0);if(s!==void 0&&Date.now()+c>=s){const l=S(s,u!==void 0&&u>=i?"retry_after":"elapsed",u===void 0?void 0:t);throw n!==void 0&&Object.defineProperty(l,"cause",{value:n,configurable:!0,writable:!0}),l}if(a===void 0)return M(c);await new Promise((l,m)=>{const h=o(()=>{clearTimeout(P),a.removeEventListener("abort",h),m(new f(0,"request_aborted","request aborted by caller signal"))},"onAbort"),P=setTimeout(()=>{a.removeEventListener("abort",h),l()},c);a.addEventListener("abort",h,{once:!0})})}o(R,"sleepWithin");function K(i,e){return new Promise((t,n)=>{const s=o(()=>n(e.reason),"onAbort");e.aborted?s():e.addEventListener("abort",s,{once:!0}),i.then(a=>{e.removeEventListener("abort",s),e.aborted?a.body?.cancel().catch(()=>{}):t(a)},a=>{e.removeEventListener("abort",s),n(a)})})}o(K,"abortable");function M(i){return new Promise(e=>setTimeout(e,i))}o(M,"sleepMs");function Q(i){if(i!==void 0)try{return i()}catch{return}}o(Q,"safeColdStartDiagnostic");export{ne as CrtrClient,y as MAX_TIMER_MS,S as deadlineExceeded,Q as safeColdStartDiagnostic,R as sleepWithin,U as waitForDaemonAvailability};
|