@north-light/cli 0.3.483 → 0.3.484

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/api/client.d.ts +6 -0
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/custom-objects.d.ts +5 -1
  6. package/dist/api/dto/docs.d.ts +26 -0
  7. package/dist/api/dto/objects.d.ts +21 -1
  8. package/dist/api/dto/plugins.d.ts +22 -0
  9. package/dist/api/dto/plugins.js +0 -0
  10. package/dist/api/index.d.ts +1 -0
  11. package/dist/api/index.js +1 -1
  12. package/dist/api/routes.d.ts +2 -0
  13. package/dist/api/routes.js +1 -1
  14. package/dist/builtin-memory/crouter-plugin/deploying.md +107 -0
  15. package/dist/builtin-memory/crouter-sdk/release-notes.md +69 -0
  16. package/dist/clients/attach/viewer.js +579 -578
  17. package/dist/commands/pkg/plugin-manage.d.ts +4 -0
  18. package/dist/commands/pkg/plugin-manage.js +18 -16
  19. package/dist/core/canvas/migrations.js +27 -18
  20. package/dist/core/command-plugins/bundle.d.ts +4 -1
  21. package/dist/core/command-plugins/bundle.js +1 -1
  22. package/dist/core/command-plugins/caller-header.d.ts +10 -0
  23. package/dist/core/command-plugins/caller-header.js +1 -0
  24. package/dist/core/command-plugins/compose.js +1 -1
  25. package/dist/core/command-plugins/endpoint.d.ts +4 -0
  26. package/dist/core/command-plugins/endpoint.js +1 -1
  27. package/dist/core/command-plugins/transport/exec-invoke-async.d.ts +11 -0
  28. package/dist/core/command-plugins/transport/exec-invoke-async.js +1 -0
  29. package/dist/core/command-plugins/transport/exec-invoke.d.ts +14 -0
  30. package/dist/core/command-plugins/transport/exec-invoke.js +1 -1
  31. package/dist/core/command-plugins/transport/http-invoke.d.ts +9 -2
  32. package/dist/core/command-plugins/transport/http-invoke.js +3 -3
  33. package/dist/core/command-plugins/transport/http-plan.js +1 -1
  34. package/dist/core/command-plugins/transport/sign.d.ts +55 -0
  35. package/dist/core/command-plugins/transport/sign.js +3 -0
  36. package/dist/core/graph/access.d.ts +19 -0
  37. package/dist/core/graph/access.js +3 -3
  38. package/dist/core/graph/custom.d.ts +29 -9
  39. package/dist/core/graph/custom.js +9 -8
  40. package/dist/core/graph/events.js +8 -8
  41. package/dist/core/graph/package-kinds.d.ts +25 -0
  42. package/dist/core/graph/package-kinds.js +1 -0
  43. package/dist/core/graph/package-reconcile.d.ts +20 -0
  44. package/dist/core/graph/package-reconcile.js +1 -0
  45. package/dist/core/graph/reader.d.ts +5 -0
  46. package/dist/core/graph/reader.js +3 -3
  47. package/dist/core/graph/receivers.d.ts +2 -1
  48. package/dist/core/graph/types.d.ts +2 -0
  49. package/dist/core/graph/watches.d.ts +4 -0
  50. package/dist/core/graph/watches.js +9 -8
  51. package/dist/core/peer/directory.d.ts +2 -1
  52. package/dist/core/peer/directory.js +1 -1
  53. package/dist/core/peer/ingest.d.ts +6 -1
  54. package/dist/core/peer/ingest.js +1 -1
  55. package/dist/core/peer/names.d.ts +2 -0
  56. package/dist/core/peer/names.js +1 -1
  57. package/dist/core/peer/outbox-store.d.ts +2 -0
  58. package/dist/core/peer/receiver.js +1 -1
  59. package/dist/core/peer/stubs.d.ts +26 -1
  60. package/dist/core/peer/stubs.js +1 -1
  61. package/dist/core/plugin-app.d.ts +31 -0
  62. package/dist/core/plugin-app.js +1 -0
  63. package/dist/core/plugin-objects-manifest.d.ts +35 -0
  64. package/dist/core/plugin-objects-manifest.js +1 -0
  65. package/dist/core/providers/bundles.js +2 -2
  66. package/dist/core/providers/call.d.ts +3 -0
  67. package/dist/core/providers/call.js +1 -1
  68. package/dist/core/secrets.d.ts +11 -0
  69. package/dist/core/secrets.js +1 -1
  70. package/dist/daemon/api/app-listener.js +13 -13
  71. package/dist/daemon/api/handlers/custom-objects.js +3 -3
  72. package/dist/daemon/api/handlers/objects.js +3 -2
  73. package/dist/daemon/api/handlers/package-docs.js +1 -1
  74. package/dist/daemon/api/handlers/plugin-app-token.d.ts +6 -0
  75. package/dist/daemon/api/handlers/plugin-app-token.js +1 -0
  76. package/dist/daemon/api/handlers/providers.d.ts +7 -0
  77. package/dist/daemon/api/handlers/providers.js +1 -1
  78. package/dist/daemon/api/operations.js +1 -1
  79. package/dist/daemon/api/server.js +1 -1
  80. package/dist/daemon/crtrd.js +7 -5
  81. package/dist/daemon/peer/forward.d.ts +4 -1
  82. package/dist/daemon/peer/forward.js +1 -1
  83. package/dist/daemon/plugin-objects/read-leaf.d.ts +20 -0
  84. package/dist/daemon/plugin-objects/read-leaf.js +2 -0
  85. package/dist/types.d.ts +16 -0
  86. package/docs/plugin/deploying.md +107 -0
  87. package/docs/sdk/release-notes.md +69 -0
  88. package/package.json +2 -2
  89. package/packages/crouter-identity/dist/index.d.ts +1 -1
  90. package/packages/crouter-identity/dist/index.js +6 -2
  91. package/packages/crouter-identity/package.json +1 -1
  92. package/runtime.lock.json +12 -12
@@ -22,6 +22,7 @@ import type { FileEncoding, FileListDTO, FilePeekDTO, FileWriteDTO } from './dto
22
22
  import type { BashRunDTO, BashRunParams } from './dto/bash.js';
23
23
  import type { EdgesDTO, EdgesQuery, ObjectListDTO, ObjectListRequest, ObjectReadDTO, ObjectReadQuery, ObjectSearchDTO, ObjectSearchRequest, UnwatchQuery, UnwatchResultDTO, WatchRequest, WatchResultDTO } from './dto/objects.js';
24
24
  import type { DocDeletedDTO, DocEditRequest, DocEditedDTO, DocHistoryDTO, DocHistoryQuery, DocLintDTO, DocLintRequest, DocMoveRequest, DocMovedDTO, DocWriteRequest, DocWrittenDTO, ReconcilePackagesDTO } from './dto/docs.js';
25
+ import type { PluginAppTokenDTO, PluginCallHeadersDTO, PluginCallHeadersRequestDTO } from './dto/plugins.js';
25
26
  import type { BackgroundedJobDTO, BackgroundedJobRequest, DeliveryDryRunRequest, DeliveryRequest, DeliveryResponse } from './dto/delivery.js';
26
27
  import type { ChatInventoryDTO, ProspectiveChatInventoryDTO, ProspectiveChatInventoryQuery } from './dto/chat-inventory.js';
27
28
  import type { CredentialRemovalResultDTO, CredentialResultDTO, InstallCredentialRequest, CompleteModelAuthFlowRequest, ModelAuthFlowCompletedDTO, ModelAuthFlowDTO, ModelAuthFlowStartedDTO, ModelAuthListDTO, ModelAuthReadinessDTO, ModelAuthReadinessQuery, StartModelAuthFlowRequest } from './dto/modelauth.js';
@@ -299,6 +300,11 @@ export declare class CrtrClient {
299
300
  readonly documents: {
300
301
  reconcilePackages: () => Promise<ReconcilePackagesDTO>;
301
302
  };
303
+ /** A plugin's `crtr_app_` credential and the headers crtrd adds to its local HTTP calls. */
304
+ readonly plugins: {
305
+ appToken: (name: string) => Promise<PluginAppTokenDTO>;
306
+ callHeaders: (name: string, request: PluginCallHeadersRequestDTO) => Promise<PluginCallHeadersDTO>;
307
+ };
302
308
  /** The broker's delivery of one node activity. */
303
309
  nodeDelivery(id: string, request: DeliveryRequest): Promise<DeliveryResponse>;
304
310
  /** A person's dry run of one delivery activity, for a live or hypothetical node. Writes nothing. */
@@ -1,3 +1,3 @@
1
- var D=Object.defineProperty;var a=(o,e)=>D(o,"name",{value:e,configurable:!0});import{ApiError as m,isErrorBody as x}from"./errors.js";import{routes as r}from"./routes.js";import{isSafeNodeId as y}from"./dto/common.js";import{isSafeBashJobId as A}from"./dto/bash-jobs.js";import{isSafeCronId as N}from"./dto/crons.js";const B=3e4,I=Symbol.for("@north-light/api/local-socket-fetch"),L=1e4,F=200;async function $({windowMs:o,probe:e,initialError:t,pollIntervalMs:n=F,retry:s=a(()=>!0,"retry"),now:i=Date.now,sleep:u=M}){const c=i()+o;let h=t;for(;;){const f=c-i();if(f<=0)throw h??new Error("crtrd availability window expired without a probe failure");try{await e(f);return}catch(P){if(h=P,!s(P))throw P}const l=c-i();if(l<=0)throw h;await u(Math.min(n,l))}}a($,"waitForDaemonAvailability");const p=2147483647;function q(o,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(o).toISOString()}); not waiting`:`the call's deadline (${new Date(o).toISOString()}) passed`;return new m(504,"deadline_exceeded",n,{deadline_at:o,reason:e,...t===void 0?{}:{retry_after_s:t}})}a(q,"deadlineExceeded");const E=a(o=>q(o??Date.now()),"budgetExhausted");class Y{static{a(this,"CrtrClient")}baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;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??B,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[I]===!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),this.coldStartPollWindowMs=e.coldStartPollWindowMs??L}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 S(t)}status(){return this.request("GET",r.status())}due(){return this.request("GET",r.due())}restartDaemon(){return this.request("POST",r.daemonRestart())}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 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}))}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 S(s);return}if(s.body===null)throw new m(s.status,"invalid_response","broker signal stream has no body");const i=s.body.getReader(),u=new TextDecoder;let c="";try{for(;;){const{done:h,value:f}=await i.read();if(h)break;c+=u.decode(f,{stream:!0});let l;for(;(l=c.indexOf(`
2
- `))!==-1;){const P=c.slice(0,l);c=c.slice(l+1),P!==""&&(yield JSON.parse(P))}}if(c+=u.decode(),c.trim()!=="")throw new m(502,"invalid_response","broker signal stream ended mid-line")}finally{await i.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)))}stopBashJob(e,t){return this.request("DELETE",r.nodeJob(this.nodePath(e),this.jobPath(t)))}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)}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)}brokerExtensionState(e){return this.request("GET",r.nodeBrokerExtensionState(this.nodePath(e)))}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??{})}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(",")}))}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:a((e,t)=>this.request("GET",d(r.object(e),t)),"read"),list:a(e=>this.request("GET",d(r.objects(),e)),"list"),search:a(e=>this.request("POST",r.objectsSearch(),e),"search"),watch:a((e,t={})=>this.request("POST",r.objectWatch(e),t),"watch"),unwatch:a((e,t)=>this.request("DELETE",d(r.objectWatch(e),t)),"unwatch"),edges:a((e,t)=>this.request("GET",d(r.objectEdges(e),t)),"edges")};docs={write:a(e=>this.request("POST",r.docs(),e),"write"),edit:a((e,t)=>this.request("PATCH",r.doc(e),t),"edit"),move:a((e,t)=>this.request("POST",r.docMove(e),t),"move"),delete:a(e=>this.request("DELETE",r.doc(e)),"delete"),history:a((e,t)=>this.request("GET",d(r.docHistory(e),t)),"history"),lint:a((e={})=>this.request("POST",r.docsLint(),e),"lint")};documents={reconcilePackages:a(()=>this.request("POST",r.documentsReconcilePackages()),"reconcilePackages")};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)}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))}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){if(e===void 0)return this.request("GET",r.humanInbox()+"/history");if(typeof e!="string"||e==="")throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",d(r.humanInbox()+"/history",{node_id:e}))}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)}canvasRoster(){return this.request("GET",r.canvasRoster())}async canvasBrowseCompressed(){const e=await this.send("GET",r.canvasBrowse());return e.ok||await S(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 i=s===void 0?void 0:this.resolveBudget(s),u=await this.send(e,t,n,i);return await S(u,i?.deadlineAt)}catch(i){throw T(i,s?.signal)}}async rawResponse(e,t,n){try{return await this.send(e,t,void 0,n)}catch(s){throw T(s,n?.signal)}}async send(e,t,n,s={}){const i=this.resolveBudget(s),u=e==="GET"||e==="HEAD"||e==="DELETE",c=i.maxRetries??this.maxRetries;for(let h=0;;h++){let f;try{f=await this.transport(e,t,n,i)}catch(l){if(this.isColdSocketError(l))try{await this.handleColdSocket(l,i.deadlineAt),f=await this.transport(e,t,n,i)}catch(P){throw i.deadlineAt!==void 0&&Date.now()>=i.deadlineAt&&!G(P,i.signal)?q(i.deadlineAt):T(P,i.signal)}else{if(this.isInterruptedSocketError(l)&&this.localSocketTransport&&(!u||h<c))return await this.rideOutInterruptedRequest(e,t,n,i);if(u&&h<c&&!G(l,i.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(l))){await _(C(h+1),i);continue}else throw T(l,i.signal)}}if(u&&h<c&&H(f.status)){await k(f,i.deadlineAt),await _(C(h+1),i,j(f));continue}return f}}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>p))throw new RangeError(`budgetMs must be a positive finite number of at most ${p}`);if(n!==void 0&&(!Number.isFinite(n)||n-Date.now()>p))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${p} 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 E(t);let s;try{return await Promise.race([e,new Promise((i,u)=>{s=setTimeout(()=>u(E(t)),n)})])}finally{s!==void 0&&clearTimeout(s)}}async sendOnce(e,t,n,s={}){const i=this.resolveBudget(s);try{return await S(await this.transport(e,t,n,i))}catch(u){throw T(u,i.signal)}}nodePath(e){if(!y(e))throw new m(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!A(e))throw new m(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!N(e))throw new m(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!y(e))throw new m(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(!y(e))throw new m(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new m(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,t,n,s={}){const i=s.deadlineAt===void 0?void 0:s.deadlineAt-Date.now();if(i!==void 0&&i<=0)return Promise.reject(E(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 h=s.timeout??this.timeoutMs,f=i===void 0?h:h>0?Math.min(h,i):i,l=new AbortController,P=i!==void 0&&(h<=0||i<=h),g=f>0?setTimeout(()=>l.abort(P?E(s.deadlineAt):new DOMException("request timed out","TimeoutError")),f):void 0,w=s.signal,O=a(()=>l.abort(w?.reason),"onExternalAbort");w!==void 0&&(w.aborted?l.abort(w.reason):w.addEventListener("abort",O,{once:!0}));const R=a(()=>{g!==void 0&&clearTimeout(g),w?.removeEventListener("abort",O)},"finish");return W(this.fetch(new URL(t,this.baseUrl),{method:e,headers:c,body:u,signal:l.signal}),l.signal).then(v=>this.retainRequestLifetime(v,R,()=>l.signal.aborted?l.signal.reason:void 0),v=>{throw R(),v})}retainRequestLifetime(e,t,n){if(e.body===null)return t(),e;const s=e.body.getReader();let i=!1;const u=a(()=>{i||(i=!0,t())},"close"),c=new ReadableStream({async pull(h){try{const{done:f,value:l}=await s.read();f?(u(),h.close()):h.enqueue(l)}catch(f){u(),h.error(n()??f)}},async cancel(h){u(),await s.cancel(h)}});return new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){const t=b(e);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"}isInterruptedSocketError(e){const t=b(e);return t==="ECONNRESET"||t==="EPIPE"}async rideOutInterruptedRequest(e,t,n,s={}){try{await this.awaitAvailability(void 0,s.deadlineAt)}catch(i){throw T(i,s.signal)}if(e!=="GET"&&e!=="HEAD")throw new m(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(i){throw T(i,s.signal)}}async awaitAvailability(e,t){const n=t===void 0?void 0:t-Date.now();if(n!==void 0&&n<=0)throw E(t);let s;try{await $({windowMs:Math.min(this.coldStartPollWindowMs,n??this.coldStartPollWindowMs),initialError:e,retry:a(i=>i!==s,"retry"),probe:a(async i=>{const u=this.coldStartFailure?.();if(u!==void 0)throw s=new m(503,"daemon_unavailable",`crtrd failed to start: ${u}`),s;const c=await this.transport("GET",r.healthz(),void 0,{timeout:i});if(c.status>=200&&c.status<300){await k(c);return}const h=await c.text();try{if(typeof JSON.parse(h).startup_blocked=="string")return}catch{}throw new m(c.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${c.status}: ${h.slice(0,500)}`)},"probe")})}catch(i){throw i===s&&(this.startupFailureReported=!0),i}}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 i=J(this.coldStartDiagnostic);if(i!==void 0){const u=T(s);throw new m(u.status,u.code,`${u.message}
3
- ${i}`)}}throw s}}}function d(o,e){if(e===void 0)return o;const t=new URLSearchParams;for(const[s,i]of Object.entries(e))i!=null&&t.set(s,String(i));const n=t.toString();return n===""?o:`${o}?${n}`}a(d,"withQuery");async function S(o,e){const t=o.status>=200&&o.status<300,n=(await U(o,e)).trim();let s;if(n!=="")try{s=JSON.parse(n)}catch{if(t)return;throw new m(o.status,"invalid_response",n.slice(0,500),void 0,o.headers)}if(t)return s;throw x(s)?new m(o.status,s.error.code,s.error.message,s.error.details,o.headers,s.error):new m(o.status,"internal",`request failed with status ${o.status}`,void 0,o.headers)}a(S,"parse");function H(o){return o===429||o>=500}a(H,"isRetryableStatus");async function k(o,e){const t=(async()=>{try{await o.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)}}a(k,"drainResponseBody");async function U(o,e){if(e===void 0)return o.text();const t=e-Date.now(),n=o.text();if(n.catch(()=>{}),t<=0)throw o.body?.cancel().catch(()=>{}),q(e);let s;try{return await Promise.race([n,new Promise((i,u)=>{s=setTimeout(()=>{o.body?.cancel().catch(()=>{}),u(q(e))},t)})])}finally{s!==void 0&&clearTimeout(s)}}a(U,"readTextWithin");function C(o){return Math.min(2e3,250*2**(o-1))}a(C,"retryDelayMs");function b(o){if(typeof o!="object"||o===null)return;const e=o.code;if(typeof e=="string")return e;const t=o.cause;if(typeof t=="object"&&t!==null){const n=t.code;if(typeof n=="string")return n}}a(b,"transportErrorCode");function G(o,e){return e?.aborted?!0:o instanceof DOMException&&(o.name==="AbortError"||o.name==="TimeoutError")}a(G,"isAbortError");function T(o,e){if(e?.aborted)return new m(0,"request_aborted","request aborted by caller signal");if(o instanceof m)return o;if(o instanceof DOMException&&o.name==="TimeoutError")return new m(504,"request_timeout",`crtrd request timed out: ${o.message}`);if(o instanceof DOMException&&o.name==="AbortError")return new m(0,"request_aborted","request aborted by caller signal");const t=b(o),n=o instanceof Error?o.message:String(o);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"?new m(503,"daemon_unavailable",`crtrd is not reachable: ${n}`):t==="ETIMEDOUT"?new m(504,"request_timeout",`crtrd request timed out: ${n}`):new m(503,"transport_error",n)}a(T,"toTransportApiError");function j(o){const e=Number(o.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}a(j,"retryAfterHeaderS");async function _(o,e,t,n){const{deadlineAt:s,signal:i}=e;if(i?.aborted)throw new m(0,"request_aborted","request aborted by caller signal");const u=s!==void 0&&t!==void 0?t*1e3:void 0,c=Math.max(o,u??0);if(s!==void 0&&Date.now()+c>=s){const h=q(s,u!==void 0&&u>=o?"retry_after":"elapsed",u===void 0?void 0:t);throw n!==void 0&&Object.defineProperty(h,"cause",{value:n,configurable:!0,writable:!0}),h}if(i===void 0)return M(c);await new Promise((h,f)=>{const l=a(()=>{clearTimeout(P),i.removeEventListener("abort",l),f(new m(0,"request_aborted","request aborted by caller signal"))},"onAbort"),P=setTimeout(()=>{i.removeEventListener("abort",l),h()},c);i.addEventListener("abort",l,{once:!0})})}a(_,"sleepWithin");function W(o,e){return new Promise((t,n)=>{const s=a(()=>n(e.reason),"onAbort");e.aborted?s():e.addEventListener("abort",s,{once:!0}),o.then(i=>{e.removeEventListener("abort",s),e.aborted?i.body?.cancel().catch(()=>{}):t(i)},i=>{e.removeEventListener("abort",s),n(i)})})}a(W,"abortable");function M(o){return new Promise(e=>setTimeout(e,o))}a(M,"sleepMs");function J(o){if(o!==void 0)try{return o()}catch{return}}a(J,"safeColdStartDiagnostic");export{Y as CrtrClient,p as MAX_TIMER_MS,q as deadlineExceeded,J as safeColdStartDiagnostic,_ as sleepWithin,$ as waitForDaemonAvailability};
1
+ var D=Object.defineProperty;var a=(o,e)=>D(o,"name",{value:e,configurable:!0});import{ApiError as m,isErrorBody as A}from"./errors.js";import{routes as r}from"./routes.js";import{isSafeNodeId as y}from"./dto/common.js";import{isSafeBashJobId as x}from"./dto/bash-jobs.js";import{isSafeCronId as N}from"./dto/crons.js";const B=3e4,I=Symbol.for("@north-light/api/local-socket-fetch"),L=1e4,F=200;async function $({windowMs:o,probe:e,initialError:t,pollIntervalMs:n=F,retry:s=a(()=>!0,"retry"),now:i=Date.now,sleep:u=M}){const c=i()+o;let h=t;for(;;){const f=c-i();if(f<=0)throw h??new Error("crtrd availability window expired without a probe failure");try{await e(f);return}catch(P){if(h=P,!s(P))throw P}const l=c-i();if(l<=0)throw h;await u(Math.min(n,l))}}a($,"waitForDaemonAvailability");const p=2147483647;function q(o,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(o).toISOString()}); not waiting`:`the call's deadline (${new Date(o).toISOString()}) passed`;return new m(504,"deadline_exceeded",n,{deadline_at:o,reason:e,...t===void 0?{}:{retry_after_s:t}})}a(q,"deadlineExceeded");const E=a(o=>q(o??Date.now()),"budgetExhausted");class Y{static{a(this,"CrtrClient")}baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;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??B,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[I]===!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),this.coldStartPollWindowMs=e.coldStartPollWindowMs??L}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 S(t)}status(){return this.request("GET",r.status())}due(){return this.request("GET",r.due())}restartDaemon(){return this.request("POST",r.daemonRestart())}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 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}))}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 S(s);return}if(s.body===null)throw new m(s.status,"invalid_response","broker signal stream has no body");const i=s.body.getReader(),u=new TextDecoder;let c="";try{for(;;){const{done:h,value:f}=await i.read();if(h)break;c+=u.decode(f,{stream:!0});let l;for(;(l=c.indexOf(`
2
+ `))!==-1;){const P=c.slice(0,l);c=c.slice(l+1),P!==""&&(yield JSON.parse(P))}}if(c+=u.decode(),c.trim()!=="")throw new m(502,"invalid_response","broker signal stream ended mid-line")}finally{await i.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)))}stopBashJob(e,t){return this.request("DELETE",r.nodeJob(this.nodePath(e),this.jobPath(t)))}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)}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)}brokerExtensionState(e){return this.request("GET",r.nodeBrokerExtensionState(this.nodePath(e)))}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??{})}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(",")}))}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:a((e,t)=>this.request("GET",d(r.object(e),t)),"read"),list:a(e=>this.request("GET",d(r.objects(),e)),"list"),search:a(e=>this.request("POST",r.objectsSearch(),e),"search"),watch:a((e,t={})=>this.request("POST",r.objectWatch(e),t),"watch"),unwatch:a((e,t)=>this.request("DELETE",d(r.objectWatch(e),t)),"unwatch"),edges:a((e,t)=>this.request("GET",d(r.objectEdges(e),t)),"edges")};docs={write:a(e=>this.request("POST",r.docs(),e),"write"),edit:a((e,t)=>this.request("PATCH",r.doc(e),t),"edit"),move:a((e,t)=>this.request("POST",r.docMove(e),t),"move"),delete:a(e=>this.request("DELETE",r.doc(e)),"delete"),history:a((e,t)=>this.request("GET",d(r.docHistory(e),t)),"history"),lint:a((e={})=>this.request("POST",r.docsLint(),e),"lint")};documents={reconcilePackages:a(()=>this.request("POST",r.documentsReconcilePackages()),"reconcilePackages")};plugins={appToken:a(e=>this.request("GET",r.pluginAppToken(e)),"appToken"),callHeaders:a((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)}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))}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){if(e===void 0)return this.request("GET",r.humanInbox()+"/history");if(typeof e!="string"||e==="")throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",d(r.humanInbox()+"/history",{node_id:e}))}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)}canvasRoster(){return this.request("GET",r.canvasRoster())}async canvasBrowseCompressed(){const e=await this.send("GET",r.canvasBrowse());return e.ok||await S(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 i=s===void 0?void 0:this.resolveBudget(s),u=await this.send(e,t,n,i);return await S(u,i?.deadlineAt)}catch(i){throw T(i,s?.signal)}}async rawResponse(e,t,n){try{return await this.send(e,t,void 0,n)}catch(s){throw T(s,n?.signal)}}async send(e,t,n,s={}){const i=this.resolveBudget(s),u=e==="GET"||e==="HEAD"||e==="DELETE",c=i.maxRetries??this.maxRetries;for(let h=0;;h++){let f;try{f=await this.transport(e,t,n,i)}catch(l){if(this.isColdSocketError(l))try{await this.handleColdSocket(l,i.deadlineAt),f=await this.transport(e,t,n,i)}catch(P){throw i.deadlineAt!==void 0&&Date.now()>=i.deadlineAt&&!G(P,i.signal)?q(i.deadlineAt):T(P,i.signal)}else{if(this.isInterruptedSocketError(l)&&this.localSocketTransport&&(!u||h<c))return await this.rideOutInterruptedRequest(e,t,n,i);if(u&&h<c&&!G(l,i.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(l))){await _(C(h+1),i);continue}else throw T(l,i.signal)}}if(u&&h<c&&H(f.status)){await k(f,i.deadlineAt),await _(C(h+1),i,j(f));continue}return f}}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>p))throw new RangeError(`budgetMs must be a positive finite number of at most ${p}`);if(n!==void 0&&(!Number.isFinite(n)||n-Date.now()>p))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${p} 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 E(t);let s;try{return await Promise.race([e,new Promise((i,u)=>{s=setTimeout(()=>u(E(t)),n)})])}finally{s!==void 0&&clearTimeout(s)}}async sendOnce(e,t,n,s={}){const i=this.resolveBudget(s);try{return await S(await this.transport(e,t,n,i))}catch(u){throw T(u,i.signal)}}nodePath(e){if(!y(e))throw new m(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!x(e))throw new m(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!N(e))throw new m(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!y(e))throw new m(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(!y(e))throw new m(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new m(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,t,n,s={}){const i=s.deadlineAt===void 0?void 0:s.deadlineAt-Date.now();if(i!==void 0&&i<=0)return Promise.reject(E(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 h=s.timeout??this.timeoutMs,f=i===void 0?h:h>0?Math.min(h,i):i,l=new AbortController,P=i!==void 0&&(h<=0||i<=h),g=f>0?setTimeout(()=>l.abort(P?E(s.deadlineAt):new DOMException("request timed out","TimeoutError")),f):void 0,w=s.signal,O=a(()=>l.abort(w?.reason),"onExternalAbort");w!==void 0&&(w.aborted?l.abort(w.reason):w.addEventListener("abort",O,{once:!0}));const R=a(()=>{g!==void 0&&clearTimeout(g),w?.removeEventListener("abort",O)},"finish");return W(this.fetch(new URL(t,this.baseUrl),{method:e,headers:c,body:u,signal:l.signal}),l.signal).then(v=>this.retainRequestLifetime(v,R,()=>l.signal.aborted?l.signal.reason:void 0),v=>{throw R(),v})}retainRequestLifetime(e,t,n){if(e.body===null)return t(),e;const s=e.body.getReader();let i=!1;const u=a(()=>{i||(i=!0,t())},"close"),c=new ReadableStream({async pull(h){try{const{done:f,value:l}=await s.read();f?(u(),h.close()):h.enqueue(l)}catch(f){u(),h.error(n()??f)}},async cancel(h){u(),await s.cancel(h)}});return new Response(c,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){const t=b(e);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"}isInterruptedSocketError(e){const t=b(e);return t==="ECONNRESET"||t==="EPIPE"}async rideOutInterruptedRequest(e,t,n,s={}){try{await this.awaitAvailability(void 0,s.deadlineAt)}catch(i){throw T(i,s.signal)}if(e!=="GET"&&e!=="HEAD")throw new m(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(i){throw T(i,s.signal)}}async awaitAvailability(e,t){const n=t===void 0?void 0:t-Date.now();if(n!==void 0&&n<=0)throw E(t);let s;try{await $({windowMs:Math.min(this.coldStartPollWindowMs,n??this.coldStartPollWindowMs),initialError:e,retry:a(i=>i!==s,"retry"),probe:a(async i=>{const u=this.coldStartFailure?.();if(u!==void 0)throw s=new m(503,"daemon_unavailable",`crtrd failed to start: ${u}`),s;const c=await this.transport("GET",r.healthz(),void 0,{timeout:i});if(c.status>=200&&c.status<300){await k(c);return}const h=await c.text();try{if(typeof JSON.parse(h).startup_blocked=="string")return}catch{}throw new m(c.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${c.status}: ${h.slice(0,500)}`)},"probe")})}catch(i){throw i===s&&(this.startupFailureReported=!0),i}}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 i=J(this.coldStartDiagnostic);if(i!==void 0){const u=T(s);throw new m(u.status,u.code,`${u.message}
3
+ ${i}`)}}throw s}}}function d(o,e){if(e===void 0)return o;const t=new URLSearchParams;for(const[s,i]of Object.entries(e))i!=null&&t.set(s,String(i));const n=t.toString();return n===""?o:`${o}?${n}`}a(d,"withQuery");async function S(o,e){const t=o.status>=200&&o.status<300,n=(await U(o,e)).trim();let s;if(n!=="")try{s=JSON.parse(n)}catch{if(t)return;throw new m(o.status,"invalid_response",n.slice(0,500),void 0,o.headers)}if(t)return s;throw A(s)?new m(o.status,s.error.code,s.error.message,s.error.details,o.headers,s.error):new m(o.status,"internal",`request failed with status ${o.status}`,void 0,o.headers)}a(S,"parse");function H(o){return o===429||o>=500}a(H,"isRetryableStatus");async function k(o,e){const t=(async()=>{try{await o.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)}}a(k,"drainResponseBody");async function U(o,e){if(e===void 0)return o.text();const t=e-Date.now(),n=o.text();if(n.catch(()=>{}),t<=0)throw o.body?.cancel().catch(()=>{}),q(e);let s;try{return await Promise.race([n,new Promise((i,u)=>{s=setTimeout(()=>{o.body?.cancel().catch(()=>{}),u(q(e))},t)})])}finally{s!==void 0&&clearTimeout(s)}}a(U,"readTextWithin");function C(o){return Math.min(2e3,250*2**(o-1))}a(C,"retryDelayMs");function b(o){if(typeof o!="object"||o===null)return;const e=o.code;if(typeof e=="string")return e;const t=o.cause;if(typeof t=="object"&&t!==null){const n=t.code;if(typeof n=="string")return n}}a(b,"transportErrorCode");function G(o,e){return e?.aborted?!0:o instanceof DOMException&&(o.name==="AbortError"||o.name==="TimeoutError")}a(G,"isAbortError");function T(o,e){if(e?.aborted)return new m(0,"request_aborted","request aborted by caller signal");if(o instanceof m)return o;if(o instanceof DOMException&&o.name==="TimeoutError")return new m(504,"request_timeout",`crtrd request timed out: ${o.message}`);if(o instanceof DOMException&&o.name==="AbortError")return new m(0,"request_aborted","request aborted by caller signal");const t=b(o),n=o instanceof Error?o.message:String(o);return t==="ECONNREFUSED"||t==="ENOENT"||t==="ENOTSOCK"?new m(503,"daemon_unavailable",`crtrd is not reachable: ${n}`):t==="ETIMEDOUT"?new m(504,"request_timeout",`crtrd request timed out: ${n}`):new m(503,"transport_error",n)}a(T,"toTransportApiError");function j(o){const e=Number(o.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}a(j,"retryAfterHeaderS");async function _(o,e,t,n){const{deadlineAt:s,signal:i}=e;if(i?.aborted)throw new m(0,"request_aborted","request aborted by caller signal");const u=s!==void 0&&t!==void 0?t*1e3:void 0,c=Math.max(o,u??0);if(s!==void 0&&Date.now()+c>=s){const h=q(s,u!==void 0&&u>=o?"retry_after":"elapsed",u===void 0?void 0:t);throw n!==void 0&&Object.defineProperty(h,"cause",{value:n,configurable:!0,writable:!0}),h}if(i===void 0)return M(c);await new Promise((h,f)=>{const l=a(()=>{clearTimeout(P),i.removeEventListener("abort",l),f(new m(0,"request_aborted","request aborted by caller signal"))},"onAbort"),P=setTimeout(()=>{i.removeEventListener("abort",l),h()},c);i.addEventListener("abort",l,{once:!0})})}a(_,"sleepWithin");function W(o,e){return new Promise((t,n)=>{const s=a(()=>n(e.reason),"onAbort");e.aborted?s():e.addEventListener("abort",s,{once:!0}),o.then(i=>{e.removeEventListener("abort",s),e.aborted?i.body?.cancel().catch(()=>{}):t(i)},i=>{e.removeEventListener("abort",s),n(i)})})}a(W,"abortable");function M(o){return new Promise(e=>setTimeout(e,o))}a(M,"sleepMs");function J(o){if(o!==void 0)try{return o()}catch{return}}a(J,"safeColdStartDiagnostic");export{Y as CrtrClient,p as MAX_TIMER_MS,q as deadlineExceeded,J as safeColdStartDiagnostic,_ as sleepWithin,$ as waitForDaemonAvailability};
@@ -1,5 +1,5 @@
1
1
  /** The contract level this build serves and requires. Written by `scripts/contract.mjs release`; never edit by hand. */
2
- export declare const CONTRACT_LEVEL = "1.9";
2
+ export declare const CONTRACT_LEVEL = "1.10";
3
3
  /** Request header naming the one contract level the caller needs, e.g. `1.3`. Optional: absent means no check. */
4
4
  export declare const REQUIRED_CONTRACT_HEADER = "Crouter-Required-Contract";
5
5
  /** Response header listing the contract levels the server serves, comma-separated, one per major, e.g. `1.3`. */
@@ -1 +1 @@
1
- var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.9",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
1
+ var c=Object.defineProperty;var e=(r,t)=>c(r,"name",{value:t,configurable:!0});const f="1.10",i="Crouter-Required-Contract",p="Crouter-Contract";function l(r){const t=/^(\d+)\.(\d+)$/.exec(r.trim());return t===null?null:{major:Number(t[1]),minor:Number(t[2])}}e(l,"parseContractLevel");function a(r){return r==null?[]:r.split(",").map(t=>l(t)).filter(t=>t!==null)}e(a,"parseServedContracts");function s(r,t){const n=l(r);return n===null?!1:(typeof t=="string"||t===null||t===void 0?a(t):t).some(u=>u.major===n.major&&u.minor>=n.minor)}e(s,"contractSatisfies");function C(r,t,n={}){if(r===void 0)return null;if(l(r)===null)return{status:400,code:"invalid_request",param:i,message:`${i} must be a contract level like 1.0.`};if(s(r,t))return null;const o=r.trim();return{status:426,code:"runtime_version_unsupported",message:t===null||a(t).length===0?`The runtime did not name its contract level; the caller requires contract ${o} or later. Roll the runtime forward.`:`The runtime serves contract ${t}; the caller requires contract ${o} or later within the same major. Roll the runtime forward, or pin an SDK whose crouterContract the runtime serves.`,details:{sdk_version:(n.legacyMinimum??"").trim(),runtime_version:n.runtimeVersion??null,required_contract:o,runtime_contract:t}}}e(C,"contractRefusal");export{p as CONTRACT_HEADER,f as CONTRACT_LEVEL,i as REQUIRED_CONTRACT_HEADER,C as contractRefusal,s as contractSatisfies,l as parseContractLevel,a as parseServedContracts};
@@ -1,3 +1,4 @@
1
+ import type { PrivacyName } from './objects.js';
1
2
  export interface CustomEventSpecDTO {
2
3
  level: number;
3
4
  supersedes?: boolean;
@@ -13,9 +14,12 @@ export interface RegisterCustomObjectRequestDTO {
13
14
  name: string;
14
15
  owner?: string;
15
16
  description: string;
16
- events: Record<string, CustomEventSpecDTO>;
17
+ /** Required unless an installed plugin declares the kind; then a register without it creates only the instance. */
18
+ events?: Record<string, CustomEventSpecDTO>;
17
19
  receiver?: CustomReceiverDTO;
18
20
  rotate_token?: boolean;
21
+ /** Who can read the instance: `public` (default), `friends` or `private`. Setting it on an existing instance changes it. */
22
+ privacy?: PrivacyName;
19
23
  }
20
24
  export interface RegisterCustomObjectResponseDTO {
21
25
  id: string;
@@ -139,4 +139,30 @@ export interface ReconcilePackagesDTO {
139
139
  reason: string;
140
140
  movedTo?: string;
141
141
  }>;
142
+ /** `object_kinds` the installed plugins declared: what applied, what another owner holds, which plugins are invalid */
143
+ kinds?: {
144
+ applied: Array<{
145
+ plugin: string;
146
+ kind: string;
147
+ outcome: 'inserted' | 'updated' | 'unchanged';
148
+ }>;
149
+ refused: Array<{
150
+ plugin: string;
151
+ kind: string;
152
+ code: 'kind_owned';
153
+ message: string;
154
+ }>;
155
+ invalid: Array<{
156
+ plugin: string;
157
+ error: string;
158
+ }>;
159
+ };
160
+ /** the `crtr_app_` tokens after this pass: who holds one (with its scopes) and whose was removed */
161
+ tokens?: {
162
+ granted: Array<{
163
+ plugin: string;
164
+ scopes: string[];
165
+ }>;
166
+ revoked: string[];
167
+ };
142
168
  }
@@ -6,6 +6,22 @@ export interface ObjectOwnerDTO {
6
6
  type: OwnerTypeName;
7
7
  handle: string;
8
8
  }
9
+ /** A custom kind's declaration, carried with an object so another machine can hold a stub of it. It grants nothing. */
10
+ export interface ObjectKindDeclDTO {
11
+ name: string;
12
+ description: string;
13
+ events: Record<string, {
14
+ level: number;
15
+ supersedes?: boolean;
16
+ }>;
17
+ owner: {
18
+ id: string;
19
+ type: 'person' | 'app' | 'repo' | 'profile';
20
+ scheme: string | null;
21
+ external_id: string | null;
22
+ handle: string;
23
+ };
24
+ }
9
25
  export interface ObjectDTO {
10
26
  id: string;
11
27
  /** The object's kind name: `document`, `node`, `job`, `person`, `app`, `repo`, `profile`, or a later kind. */
@@ -17,6 +33,8 @@ export interface ObjectDTO {
17
33
  preview: string;
18
34
  created_at: string;
19
35
  deleted_at: string | null;
36
+ /** Present on an instance of a custom kind. */
37
+ kind_decl?: ObjectKindDeclDTO;
20
38
  }
21
39
  export interface DocHeadDTO {
22
40
  rev_id: string;
@@ -171,11 +189,13 @@ export interface WatchRequest {
171
189
  patterns?: string[];
172
190
  config?: ListenConfigDTO;
173
191
  filter?: Record<string, unknown>;
174
- watcher?: string;
192
+ watcher?: string; /** With `watcher`: the machine of the account that homes that node (a node not on this machine). */
193
+ watcher_machine?: string;
175
194
  }
176
195
  export interface UnwatchQuery {
177
196
  pattern?: string;
178
197
  watcher?: string;
198
+ watcher_machine?: string;
179
199
  }
180
200
  export interface WatchResultDTO {
181
201
  object: ObjectDTO;
@@ -0,0 +1,22 @@
1
+ /** `GET /v1/plugins/:name/app-token`. */
2
+ export interface PluginAppTokenDTO {
3
+ /** The plugin's `crtr_app_` bearer for crtrd's `/v1` API. */
4
+ token: string;
5
+ /** The crtrd unix socket to present it on. */
6
+ socket: string;
7
+ }
8
+ /** `POST /v1/plugins/:name/call-headers`. Digests only: neither the body nor any header value reaches crtrd. */
9
+ export interface PluginCallHeadersRequestDTO {
10
+ method: string;
11
+ url: string;
12
+ /** Lowercase hex sha256 of the exact body bytes sent (of "" when none). */
13
+ body_sha256: string;
14
+ /** Lowercase names of the headers the signature covers, sorted. */
15
+ header_names: string[];
16
+ /** Lowercase hex sha256 over `<name>:<value>\n` for each name in `header_names`. */
17
+ headers_sha256: string;
18
+ }
19
+ export interface PluginCallHeadersDTO {
20
+ /** `Crtr-Caller`, and `Crtr-Signature` when the call qualifies for signing. */
21
+ headers: Record<string, string>;
22
+ }
File without changes
@@ -48,4 +48,5 @@ export * from './dto/review-comments.js';
48
48
  export * from './dto/chat-inventory.js';
49
49
  export * from './dto/analytics.js';
50
50
  export * from './dto/custom-objects.js';
51
+ export * from './dto/plugins.js';
51
52
  export type { WatchRequest, WatchResultDTO, UnwatchQuery, UnwatchResultDTO } from './dto/objects.js';
package/dist/api/index.js CHANGED
@@ -1 +1 @@
1
- import{CrtrClient as e,deadlineExceeded as t,MAX_TIMER_MS as m,sleepWithin as p,waitForDaemonAvailability as f}from"./client.js";import{APIError as E,ApiError as R,isErrorBody as _}from"./errors.js";import{errorCodes as i}from"./error-codes.js";import{API_VERSION as s,routes as n}from"./routes.js";import{RUNTIME_VERSION_HEADER as C,MINIMUM_RUNTIME_VERSION_HEADER as I,compareReleaseVersions as N,minimumRuntimeRefusal as O}from"./runtime-version.js";import{CONTRACT_HEADER as d,CONTRACT_LEVEL as S,REQUIRED_CONTRACT_HEADER as c,contractRefusal as L,contractSatisfies as M,parseContractLevel as u,parseServedContracts as D}from"./contract.js";import{LONG_POLL_MAX_WAIT_SECONDS as H,LONG_POLL_ROUTES as U,longPollHoldSeconds as V,longPollRoute as v,requestedWait as W}from"./long-poll.js";export*from"../shared/generated-context.js";export*from"./dto/common.js";export*from"./dto/health.js";export*from"./dto/limits.js";export*from"./dto/grants.js";export*from"./dto/usage.js";export*from"./dto/nodes.js";export*from"./dto/node-outcomes.js";export*from"./dto/node-events.js";export*from"./dto/run-events.js";export*from"./dto/broker-signals.js";export*from"./dto/bash-jobs.js";export*from"./dto/messages.js";export*from"./dto/reports.js";export*from"./dto/structured-requests.js";export*from"./dto/lifecycle.js";export*from"./dto/subscriptions.js";export*from"./dto/focus.js";export*from"./dto/crons.js";export*from"./dto/config.js";export*from"./dto/attach.js";export*from"./dto/broker.js";export*from"./dto/profiles.js";export*from"./dto/modelauth.js";export*from"./dto/model-config.js";export*from"./dto/canvas.js";export*from"./dto/worktree.js";export*from"./dto/human.js";export*from"./dto/files.js";export*from"./dto/bash.js";export*from"./dto/inbox.js";export*from"./dto/human-requests.js";export*from"./dto/reviews.js";export*from"./dto/review-comments.js";export*from"./dto/chat-inventory.js";export*from"./dto/analytics.js";export*from"./dto/custom-objects.js";export{E as APIError,s as API_VERSION,R as ApiError,d as CONTRACT_HEADER,S as CONTRACT_LEVEL,e as CrtrClient,H as LONG_POLL_MAX_WAIT_SECONDS,U as LONG_POLL_ROUTES,m as MAX_TIMER_MS,I as MINIMUM_RUNTIME_VERSION_HEADER,c as REQUIRED_CONTRACT_HEADER,C as RUNTIME_VERSION_HEADER,N as compareReleaseVersions,L as contractRefusal,M as contractSatisfies,t as deadlineExceeded,i as errorCodes,_ as isErrorBody,V as longPollHoldSeconds,v as longPollRoute,O as minimumRuntimeRefusal,u as parseContractLevel,D as parseServedContracts,W as requestedWait,n as routes,p as sleepWithin,f as waitForDaemonAvailability};
1
+ import{CrtrClient as e,deadlineExceeded as t,MAX_TIMER_MS as m,sleepWithin as p,waitForDaemonAvailability as f}from"./client.js";import{APIError as E,ApiError as R,isErrorBody as _}from"./errors.js";import{errorCodes as i}from"./error-codes.js";import{API_VERSION as s,routes as n}from"./routes.js";import{RUNTIME_VERSION_HEADER as C,MINIMUM_RUNTIME_VERSION_HEADER as I,compareReleaseVersions as N,minimumRuntimeRefusal as O}from"./runtime-version.js";import{CONTRACT_HEADER as d,CONTRACT_LEVEL as S,REQUIRED_CONTRACT_HEADER as c,contractRefusal as L,contractSatisfies as M,parseContractLevel as u,parseServedContracts as D}from"./contract.js";import{LONG_POLL_MAX_WAIT_SECONDS as H,LONG_POLL_ROUTES as U,longPollHoldSeconds as V,longPollRoute as v,requestedWait as W}from"./long-poll.js";export*from"../shared/generated-context.js";export*from"./dto/common.js";export*from"./dto/health.js";export*from"./dto/limits.js";export*from"./dto/grants.js";export*from"./dto/usage.js";export*from"./dto/nodes.js";export*from"./dto/node-outcomes.js";export*from"./dto/node-events.js";export*from"./dto/run-events.js";export*from"./dto/broker-signals.js";export*from"./dto/bash-jobs.js";export*from"./dto/messages.js";export*from"./dto/reports.js";export*from"./dto/structured-requests.js";export*from"./dto/lifecycle.js";export*from"./dto/subscriptions.js";export*from"./dto/focus.js";export*from"./dto/crons.js";export*from"./dto/config.js";export*from"./dto/attach.js";export*from"./dto/broker.js";export*from"./dto/profiles.js";export*from"./dto/modelauth.js";export*from"./dto/model-config.js";export*from"./dto/canvas.js";export*from"./dto/worktree.js";export*from"./dto/human.js";export*from"./dto/files.js";export*from"./dto/bash.js";export*from"./dto/inbox.js";export*from"./dto/human-requests.js";export*from"./dto/reviews.js";export*from"./dto/review-comments.js";export*from"./dto/chat-inventory.js";export*from"./dto/analytics.js";export*from"./dto/custom-objects.js";export*from"./dto/plugins.js";export{E as APIError,s as API_VERSION,R as ApiError,d as CONTRACT_HEADER,S as CONTRACT_LEVEL,e as CrtrClient,H as LONG_POLL_MAX_WAIT_SECONDS,U as LONG_POLL_ROUTES,m as MAX_TIMER_MS,I as MINIMUM_RUNTIME_VERSION_HEADER,c as REQUIRED_CONTRACT_HEADER,C as RUNTIME_VERSION_HEADER,N as compareReleaseVersions,L as contractRefusal,M as contractSatisfies,t as deadlineExceeded,i as errorCodes,_ as isErrorBody,V as longPollHoldSeconds,v as longPollRoute,O as minimumRuntimeRefusal,u as parseContractLevel,D as parseServedContracts,W as requestedWait,n as routes,p as sleepWithin,f as waitForDaemonAvailability};
@@ -160,5 +160,7 @@ export declare const routes: {
160
160
  readonly docMove: (ref: string) => string;
161
161
  readonly docHistory: (ref: string) => string;
162
162
  readonly docsLint: () => string;
163
+ readonly pluginAppToken: (name: string) => string;
164
+ readonly pluginCallHeaders: (name: string) => string;
163
165
  readonly documentsReconcilePackages: () => string;
164
166
  };
@@ -1 +1 @@
1
- var s=Object.defineProperty;var o=(e,n)=>s(e,"name",{value:n,configurable:!0});const $="v1",r="/v1",a={healthz:o(()=>"/healthz","healthz"),status:o(()=>"/v1/status","status"),due:o(()=>"/v1/due","due"),daemonRestart:o(()=>"/v1/daemon/restart","daemonRestart"),daemonMigrate:o(()=>"/v1/daemon/migrate","daemonMigrate"),daemonAdmit:o(()=>"/v1/daemon/admit","daemonAdmit"),nodes:o(()=>"/v1/nodes","nodes"),reviveAll:o(()=>"/v1/nodes/revive-all","reviveAll"),node:o(e=>`/v1/nodes/${e}`,"node"),nodeMemoryReads:o(e=>`/v1/nodes/${e}/memory-reads`,"nodeMemoryReads"),nodeOutcome:o(e=>`/v1/nodes/${e}/outcome`,"nodeOutcome"),nodeOutcomeDelivery:o(e=>`/v1/nodes/${e}/outcome-delivery`,"nodeOutcomeDelivery"),nodeEvents:o(e=>`/v1/nodes/${e}/events`,"nodeEvents"),nodeSnapshot:o(e=>`/v1/nodes/${e}/snapshot`,"nodeSnapshot"),nodeSubject:o(e=>`/v1/nodes/${e}/subject`,"nodeSubject"),nodeSession:o(e=>`/v1/nodes/${e}/session`,"nodeSession"),nodeChatInventory:o(e=>`/v1/nodes/${e}/chat-inventory`,"nodeChatInventory"),prospectiveChatInventory:o(()=>"/v1/prospective-chat-inventory","prospectiveChatInventory"),nodeTranscript:o(e=>`/v1/nodes/${e}/transcript`,"nodeTranscript"),nodeContext:o(e=>`/v1/nodes/${e}/context`,"nodeContext"),nodeReports:o(e=>`/v1/nodes/${e}/reports`,"nodeReports"),nodeResult:o(e=>`/v1/nodes/${e}/result`,"nodeResult"),nodeJobs:o(e=>`/v1/nodes/${e}/jobs`,"nodeJobs"),nodeJob:o((e,n)=>`/v1/nodes/${e}/jobs/${n}`,"nodeJob"),nodeJobBackground:o((e,n)=>`/v1/nodes/${e}/jobs/${n}/background`,"nodeJobBackground"),nodeDelivery:o(e=>`/v1/nodes/${e}/delivery`,"nodeDelivery"),deliveryDryRun:o(()=>"/v1/delivery/dry-run","deliveryDryRun"),deliveryRetry:o(e=>`/v1/deliveries/${encodeURIComponent(e)}/retry`,"deliveryRetry"),nodeMessages:o(e=>`/v1/nodes/${e}/messages`,"nodeMessages"),nodeInterrupt:o(e=>`/v1/nodes/${e}/interrupt`,"nodeInterrupt"),nodeFork:o(e=>`/v1/nodes/${e}/fork`,"nodeFork"),nodeRevive:o(e=>`/v1/nodes/${e}/revive`,"nodeRevive"),nodeRelaunchRoot:o(e=>`/v1/nodes/${e}/relaunch-root`,"nodeRelaunchRoot"),nodeBrokerSessionBound:o(e=>`/v1/nodes/${e}/broker/session-bound`,"nodeBrokerSessionBound"),nodeBrokerSettle:o(e=>`/v1/nodes/${e}/broker/settle`,"nodeBrokerSettle"),nodeBrokerParkComplete:o(e=>`/v1/nodes/${e}/broker/park-complete`,"nodeBrokerParkComplete"),nodeBrokerParkActivity:o(e=>`/v1/nodes/${e}/broker/park-activity`,"nodeBrokerParkActivity"),nodeBrokerTelemetry:o(e=>`/v1/nodes/${e}/broker/telemetry`,"nodeBrokerTelemetry"),nodeLog:o(e=>`/v1/nodes/${e}/records/log`,"nodeLog"),nodeTelemetry:o(e=>`/v1/nodes/${e}/records/telemetry`,"nodeTelemetry"),nodeRecap:o(e=>`/v1/nodes/${e}/records/recap`,"nodeRecap"),nodeInboxReport:o(e=>`/v1/nodes/${e}/records/inbox`,"nodeInboxReport"),nodePassiveMessage:o(e=>`/v1/nodes/${e}/records/passive`,"nodePassiveMessage"),nodePushedFinal:o(e=>`/v1/nodes/${e}/records/pushed-final`,"nodePushedFinal"),nodeMailClaim:o(e=>`/v1/nodes/${e}/mail/claim`,"nodeMailClaim"),nodeMailAcknowledge:o(e=>`/v1/nodes/${e}/mail/acknowledge`,"nodeMailAcknowledge"),nodeBrokerModel:o(e=>`/v1/nodes/${e}/broker/model`,"nodeBrokerModel"),nodeBrokerExtensionState:o(e=>`/v1/nodes/${e}/broker/extension-state`,"nodeBrokerExtensionState"),nodeBrokerSignals:o(e=>`/v1/nodes/${e}/broker/signals`,"nodeBrokerSignals"),nodeBrokerGeneratedName:o(e=>`/v1/nodes/${e}/broker/generated-name`,"nodeBrokerGeneratedName"),nodeBrokerPersonaAck:o(e=>`/v1/nodes/${e}/broker/persona-ack`,"nodeBrokerPersonaAck"),brokerTurn:o(e=>`/v1/broker/${e}/turn`,"brokerTurn"),brokerProviderRetry:o(e=>`/v1/broker/${e}/provider-retry`,"brokerProviderRetry"),brokerFault:o(e=>`/v1/broker/${e}/fault`,"brokerFault"),brokerRecovery:o(e=>`/v1/broker/${e}/recovery`,"brokerRecovery"),nodeFault:o(e=>`/v1/nodes/${e}/fault`,"nodeFault"),nodeClose:o(e=>`/v1/nodes/${e}/close`,"nodeClose"),nodeRecycle:o(e=>`/v1/nodes/${e}/recycle`,"nodeRecycle"),nodeDemote:o(e=>`/v1/nodes/${e}/demote`,"nodeDemote"),nodePromote:o(e=>`/v1/nodes/${e}/promote`,"nodePromote"),nodeYield:o(e=>`/v1/nodes/${e}/yield`,"nodeYield"),nodeWait:o(e=>`/v1/nodes/${e}/wait`,"nodeWait"),nodeConfig:o(e=>`/v1/nodes/${e}/config`,"nodeConfig"),kinds:o(()=>"/v1/kinds","kinds"),nodeWorktreeClose:o(e=>`/v1/nodes/${e}/worktree/close`,"nodeWorktreeClose"),nodeWorktreeAbandon:o(e=>`/v1/nodes/${e}/worktree/abandon`,"nodeWorktreeAbandon"),quarantinedWorktrees:o(()=>"/v1/worktrees/quarantined","quarantinedWorktrees"),spaces:o(()=>"/v1/spaces","spaces"),limits:o(()=>"/v1/limits","limits"),limitsApp:o(e=>`/v1/limits/apps/${encodeURIComponent(e)}`,"limitsApp"),nodeAttach:o(e=>`/v1/nodes/${e}/attach`,"nodeAttach"),focuses:o(()=>"/v1/focuses","focuses"),focusByNode:o(()=>"/v1/focuses/by-node","focusByNode"),focusByPane:o(()=>"/v1/focuses/by-pane","focusByPane"),focus:o(e=>`/v1/focuses/${e}`,"focus"),nodeSubscriptions:o(e=>`/v1/nodes/${e}/subscriptions`,"nodeSubscriptions"),nodeSubscription:o((e,n)=>`/v1/nodes/${e}/subscriptions/${n}`,"nodeSubscription"),crons:o(()=>"/v1/crons","crons"),cron:o(e=>`/v1/crons/${e}`,"cron"),cronPause:o(e=>`/v1/crons/${e}/pause`,"cronPause"),cronResume:o(e=>`/v1/crons/${e}/resume`,"cronResume"),cronRun:o(e=>`/v1/crons/${e}/run`,"cronRun"),cronsPoke:o(()=>"/v1/crons/poke","cronsPoke"),canvasAttention:o(()=>"/v1/canvas/attention","canvasAttention"),canvasAttentionCounts:o(()=>"/v1/canvas/attention/counts","canvasAttentionCounts"),canvasHistorySearch:o(()=>"/v1/canvas/history/search","canvasHistorySearch"),canvasHistoryGrep:o(()=>"/v1/canvas/history/grep","canvasHistoryGrep"),canvasHistoryRead:o(()=>"/v1/canvas/history/read","canvasHistoryRead"),canvasHistoryStats:o(()=>"/v1/canvas/history/stats","canvasHistoryStats"),canvasSnapshot:o(()=>"/v1/canvas/snapshot","canvasSnapshot"),canvasRoster:o(()=>"/v1/canvas/roster","canvasRoster"),canvasBrowse:o(()=>"/v1/canvas/browse","canvasBrowse"),canvasAnalytics:o(()=>"/v1/canvas/analytics","canvasAnalytics"),canvasGraph:o(()=>"/v1/canvas/graph","canvasGraph"),canvasPrune:o(()=>"/v1/canvas/prune","canvasPrune"),humanReviews:o(()=>"/v1/human/reviews","humanReviews"),humanReview:o(e=>`/v1/human/reviews/${e}`,"humanReview"),humanReviewSubmit:o(e=>`/v1/human/reviews/${e}/submit`,"humanReviewSubmit"),humanReviewCancel:o(e=>`/v1/human/reviews/${e}/cancel`,"humanReviewCancel"),humanReviewDocument:o(e=>`/v1/human/reviews/${e}/document`,"humanReviewDocument"),humanReviewComments:o(e=>`/v1/human/reviews/${e}/comments`,"humanReviewComments"),humanReviewCommentEvents:o(e=>`/v1/human/reviews/${e}/comment-events`,"humanReviewCommentEvents"),humanReviewCommentRanges:o(e=>`/v1/human/reviews/${e}/comment-ranges`,"humanReviewCommentRanges"),humanComment:o(e=>`/v1/human/comments/${e}`,"humanComment"),humanCommentEdit:o(e=>`/v1/human/comments/${e}/edit`,"humanCommentEdit"),humanCommentResolve:o(e=>`/v1/human/comments/${e}/resolve`,"humanCommentResolve"),humanCommentReopen:o(e=>`/v1/human/comments/${e}/reopen`,"humanCommentReopen"),humanCommentDelete:o(e=>`/v1/human/comments/${e}/delete`,"humanCommentDelete"),humanCommentFork:o(e=>`/v1/human/comments/${e}/fork`,"humanCommentFork"),humanInbox:o(()=>"/v1/human/inbox","humanInbox"),humanInboxTicket:o(e=>`/v1/human/inbox/${e}`,"humanInboxTicket"),humanInboxRespond:o(e=>`/v1/human/inbox/${e}/respond`,"humanInboxRespond"),humanInboxProgress:o(e=>`/v1/human/inbox/${e}/progress`,"humanInboxProgress"),humanInboxResponse:o(e=>`/v1/human/inbox/${e}/response`,"humanInboxResponse"),humanInboxCancel:o(e=>`/v1/human/inbox/${e}/cancel`,"humanInboxCancel"),humanInboxFeedbackResolve:o((e,n)=>`/v1/human/inbox/${e}/feedback-comments/${n}/resolve`,"humanInboxFeedbackResolve"),humanRequests:o(()=>"/v1/human/requests","humanRequests"),humanComponents:o(()=>"/v1/human/components","humanComponents"),humanRequest:o(e=>`/v1/human/requests/${e}`,"humanRequest"),humanRequestReplace:o(e=>`/v1/human/requests/${e}/replace`,"humanRequestReplace"),humanRequestRespond:o(e=>`/v1/human/requests/${e}/respond`,"humanRequestRespond"),humanRequestDismiss:o(e=>`/v1/human/requests/${e}/dismiss`,"humanRequestDismiss"),humanRequestCancel:o(e=>`/v1/human/requests/${e}/cancel`,"humanRequestCancel"),profiles:o(()=>"/v1/profiles","profiles"),profile:o(e=>`/v1/profiles/${e}`,"profile"),profilePause:o(e=>`/v1/profiles/${e}/pause`,"profilePause"),profileResume:o(e=>`/v1/profiles/${e}/resume`,"profileResume"),profileMetadata:o(e=>`/v1/profiles/${e}/metadata`,"profileMetadata"),appEnv:o(()=>"/v1/apps/self/env","appEnv"),appEnvVar:o(e=>`/v1/apps/self/env/${encodeURIComponent(e)}`,"appEnvVar"),profileEnv:o(e=>`/v1/profiles/${e}/env`,"profileEnv"),profileEnvVar:o((e,n)=>`/v1/profiles/${e}/env/${n}`,"profileEnvVar"),modelAuths:o(()=>"/v1/model-auth","modelAuths"),modelAuthReadiness:o(()=>"/v1/model-auth/readiness","modelAuthReadiness"),modelAuth:o(e=>`/v1/model-auth/${e}`,"modelAuth"),modelAuthFlows:o(()=>"/v1/model-auth/flows","modelAuthFlows"),modelAuthFlow:o(e=>`/v1/model-auth/flows/${encodeURIComponent(e)}`,"modelAuthFlow"),modelAuthFlowComplete:o(e=>`/v1/model-auth/flows/${encodeURIComponent(e)}/complete`,"modelAuthFlowComplete"),modelAuthFlowCancel:o(e=>`/v1/model-auth/flows/${encodeURIComponent(e)}/cancel`,"modelAuthFlowCancel"),filePeek:o(()=>"/v1/files/peek","filePeek"),fileWrite:o(()=>"/v1/files/write","fileWrite"),fileList:o(()=>"/v1/files/list","fileList"),bash:o(()=>"/v1/bash","bash"),objects:o(()=>"/v1/objects","objects"),object:o(e=>`/v1/objects/${encodeURIComponent(e)}`,"object"),objectsSearch:o(()=>"/v1/objects/search","objectsSearch"),objectWatch:o(e=>`/v1/objects/${encodeURIComponent(e)}/watch`,"objectWatch"),customObjects:o(()=>"/v1/custom-objects","customObjects"),customObject:o(e=>`/v1/custom-objects/${encodeURIComponent(e)}`,"customObject"),customObjectEvents:o(e=>`/v1/custom-objects/${encodeURIComponent(e)}/events`,"customObjectEvents"),customObjectDeliveries:o(e=>`/v1/custom-objects/${encodeURIComponent(e)}/deliveries`,"customObjectDeliveries"),customObjectAck:o(e=>`/v1/custom-objects/${encodeURIComponent(e)}/deliveries/ack`,"customObjectAck"),objectEdges:o(e=>`/v1/objects/${encodeURIComponent(e)}/edges`,"objectEdges"),docs:o(()=>"/v1/docs","docs"),doc:o(e=>`/v1/docs/${encodeURIComponent(e)}`,"doc"),docMove:o(e=>`/v1/docs/${encodeURIComponent(e)}/move`,"docMove"),docHistory:o(e=>`/v1/docs/${encodeURIComponent(e)}/history`,"docHistory"),docsLint:o(()=>"/v1/docs/lint","docsLint"),documentsReconcilePackages:o(()=>"/v1/documents/reconcile-packages","documentsReconcilePackages")};export{$ as API_VERSION,a as routes};
1
+ var s=Object.defineProperty;var o=(e,n)=>s(e,"name",{value:n,configurable:!0});const t="v1",r="/v1",a={healthz:o(()=>"/healthz","healthz"),status:o(()=>"/v1/status","status"),due:o(()=>"/v1/due","due"),daemonRestart:o(()=>"/v1/daemon/restart","daemonRestart"),daemonMigrate:o(()=>"/v1/daemon/migrate","daemonMigrate"),daemonAdmit:o(()=>"/v1/daemon/admit","daemonAdmit"),nodes:o(()=>"/v1/nodes","nodes"),reviveAll:o(()=>"/v1/nodes/revive-all","reviveAll"),node:o(e=>`/v1/nodes/${e}`,"node"),nodeMemoryReads:o(e=>`/v1/nodes/${e}/memory-reads`,"nodeMemoryReads"),nodeOutcome:o(e=>`/v1/nodes/${e}/outcome`,"nodeOutcome"),nodeOutcomeDelivery:o(e=>`/v1/nodes/${e}/outcome-delivery`,"nodeOutcomeDelivery"),nodeEvents:o(e=>`/v1/nodes/${e}/events`,"nodeEvents"),nodeSnapshot:o(e=>`/v1/nodes/${e}/snapshot`,"nodeSnapshot"),nodeSubject:o(e=>`/v1/nodes/${e}/subject`,"nodeSubject"),nodeSession:o(e=>`/v1/nodes/${e}/session`,"nodeSession"),nodeChatInventory:o(e=>`/v1/nodes/${e}/chat-inventory`,"nodeChatInventory"),prospectiveChatInventory:o(()=>"/v1/prospective-chat-inventory","prospectiveChatInventory"),nodeTranscript:o(e=>`/v1/nodes/${e}/transcript`,"nodeTranscript"),nodeContext:o(e=>`/v1/nodes/${e}/context`,"nodeContext"),nodeReports:o(e=>`/v1/nodes/${e}/reports`,"nodeReports"),nodeResult:o(e=>`/v1/nodes/${e}/result`,"nodeResult"),nodeJobs:o(e=>`/v1/nodes/${e}/jobs`,"nodeJobs"),nodeJob:o((e,n)=>`/v1/nodes/${e}/jobs/${n}`,"nodeJob"),nodeJobBackground:o((e,n)=>`/v1/nodes/${e}/jobs/${n}/background`,"nodeJobBackground"),nodeDelivery:o(e=>`/v1/nodes/${e}/delivery`,"nodeDelivery"),deliveryDryRun:o(()=>"/v1/delivery/dry-run","deliveryDryRun"),deliveryRetry:o(e=>`/v1/deliveries/${encodeURIComponent(e)}/retry`,"deliveryRetry"),nodeMessages:o(e=>`/v1/nodes/${e}/messages`,"nodeMessages"),nodeInterrupt:o(e=>`/v1/nodes/${e}/interrupt`,"nodeInterrupt"),nodeFork:o(e=>`/v1/nodes/${e}/fork`,"nodeFork"),nodeRevive:o(e=>`/v1/nodes/${e}/revive`,"nodeRevive"),nodeRelaunchRoot:o(e=>`/v1/nodes/${e}/relaunch-root`,"nodeRelaunchRoot"),nodeBrokerSessionBound:o(e=>`/v1/nodes/${e}/broker/session-bound`,"nodeBrokerSessionBound"),nodeBrokerSettle:o(e=>`/v1/nodes/${e}/broker/settle`,"nodeBrokerSettle"),nodeBrokerParkComplete:o(e=>`/v1/nodes/${e}/broker/park-complete`,"nodeBrokerParkComplete"),nodeBrokerParkActivity:o(e=>`/v1/nodes/${e}/broker/park-activity`,"nodeBrokerParkActivity"),nodeBrokerTelemetry:o(e=>`/v1/nodes/${e}/broker/telemetry`,"nodeBrokerTelemetry"),nodeLog:o(e=>`/v1/nodes/${e}/records/log`,"nodeLog"),nodeTelemetry:o(e=>`/v1/nodes/${e}/records/telemetry`,"nodeTelemetry"),nodeRecap:o(e=>`/v1/nodes/${e}/records/recap`,"nodeRecap"),nodeInboxReport:o(e=>`/v1/nodes/${e}/records/inbox`,"nodeInboxReport"),nodePassiveMessage:o(e=>`/v1/nodes/${e}/records/passive`,"nodePassiveMessage"),nodePushedFinal:o(e=>`/v1/nodes/${e}/records/pushed-final`,"nodePushedFinal"),nodeMailClaim:o(e=>`/v1/nodes/${e}/mail/claim`,"nodeMailClaim"),nodeMailAcknowledge:o(e=>`/v1/nodes/${e}/mail/acknowledge`,"nodeMailAcknowledge"),nodeBrokerModel:o(e=>`/v1/nodes/${e}/broker/model`,"nodeBrokerModel"),nodeBrokerExtensionState:o(e=>`/v1/nodes/${e}/broker/extension-state`,"nodeBrokerExtensionState"),nodeBrokerSignals:o(e=>`/v1/nodes/${e}/broker/signals`,"nodeBrokerSignals"),nodeBrokerGeneratedName:o(e=>`/v1/nodes/${e}/broker/generated-name`,"nodeBrokerGeneratedName"),nodeBrokerPersonaAck:o(e=>`/v1/nodes/${e}/broker/persona-ack`,"nodeBrokerPersonaAck"),brokerTurn:o(e=>`/v1/broker/${e}/turn`,"brokerTurn"),brokerProviderRetry:o(e=>`/v1/broker/${e}/provider-retry`,"brokerProviderRetry"),brokerFault:o(e=>`/v1/broker/${e}/fault`,"brokerFault"),brokerRecovery:o(e=>`/v1/broker/${e}/recovery`,"brokerRecovery"),nodeFault:o(e=>`/v1/nodes/${e}/fault`,"nodeFault"),nodeClose:o(e=>`/v1/nodes/${e}/close`,"nodeClose"),nodeRecycle:o(e=>`/v1/nodes/${e}/recycle`,"nodeRecycle"),nodeDemote:o(e=>`/v1/nodes/${e}/demote`,"nodeDemote"),nodePromote:o(e=>`/v1/nodes/${e}/promote`,"nodePromote"),nodeYield:o(e=>`/v1/nodes/${e}/yield`,"nodeYield"),nodeWait:o(e=>`/v1/nodes/${e}/wait`,"nodeWait"),nodeConfig:o(e=>`/v1/nodes/${e}/config`,"nodeConfig"),kinds:o(()=>"/v1/kinds","kinds"),nodeWorktreeClose:o(e=>`/v1/nodes/${e}/worktree/close`,"nodeWorktreeClose"),nodeWorktreeAbandon:o(e=>`/v1/nodes/${e}/worktree/abandon`,"nodeWorktreeAbandon"),quarantinedWorktrees:o(()=>"/v1/worktrees/quarantined","quarantinedWorktrees"),spaces:o(()=>"/v1/spaces","spaces"),limits:o(()=>"/v1/limits","limits"),limitsApp:o(e=>`/v1/limits/apps/${encodeURIComponent(e)}`,"limitsApp"),nodeAttach:o(e=>`/v1/nodes/${e}/attach`,"nodeAttach"),focuses:o(()=>"/v1/focuses","focuses"),focusByNode:o(()=>"/v1/focuses/by-node","focusByNode"),focusByPane:o(()=>"/v1/focuses/by-pane","focusByPane"),focus:o(e=>`/v1/focuses/${e}`,"focus"),nodeSubscriptions:o(e=>`/v1/nodes/${e}/subscriptions`,"nodeSubscriptions"),nodeSubscription:o((e,n)=>`/v1/nodes/${e}/subscriptions/${n}`,"nodeSubscription"),crons:o(()=>"/v1/crons","crons"),cron:o(e=>`/v1/crons/${e}`,"cron"),cronPause:o(e=>`/v1/crons/${e}/pause`,"cronPause"),cronResume:o(e=>`/v1/crons/${e}/resume`,"cronResume"),cronRun:o(e=>`/v1/crons/${e}/run`,"cronRun"),cronsPoke:o(()=>"/v1/crons/poke","cronsPoke"),canvasAttention:o(()=>"/v1/canvas/attention","canvasAttention"),canvasAttentionCounts:o(()=>"/v1/canvas/attention/counts","canvasAttentionCounts"),canvasHistorySearch:o(()=>"/v1/canvas/history/search","canvasHistorySearch"),canvasHistoryGrep:o(()=>"/v1/canvas/history/grep","canvasHistoryGrep"),canvasHistoryRead:o(()=>"/v1/canvas/history/read","canvasHistoryRead"),canvasHistoryStats:o(()=>"/v1/canvas/history/stats","canvasHistoryStats"),canvasSnapshot:o(()=>"/v1/canvas/snapshot","canvasSnapshot"),canvasRoster:o(()=>"/v1/canvas/roster","canvasRoster"),canvasBrowse:o(()=>"/v1/canvas/browse","canvasBrowse"),canvasAnalytics:o(()=>"/v1/canvas/analytics","canvasAnalytics"),canvasGraph:o(()=>"/v1/canvas/graph","canvasGraph"),canvasPrune:o(()=>"/v1/canvas/prune","canvasPrune"),humanReviews:o(()=>"/v1/human/reviews","humanReviews"),humanReview:o(e=>`/v1/human/reviews/${e}`,"humanReview"),humanReviewSubmit:o(e=>`/v1/human/reviews/${e}/submit`,"humanReviewSubmit"),humanReviewCancel:o(e=>`/v1/human/reviews/${e}/cancel`,"humanReviewCancel"),humanReviewDocument:o(e=>`/v1/human/reviews/${e}/document`,"humanReviewDocument"),humanReviewComments:o(e=>`/v1/human/reviews/${e}/comments`,"humanReviewComments"),humanReviewCommentEvents:o(e=>`/v1/human/reviews/${e}/comment-events`,"humanReviewCommentEvents"),humanReviewCommentRanges:o(e=>`/v1/human/reviews/${e}/comment-ranges`,"humanReviewCommentRanges"),humanComment:o(e=>`/v1/human/comments/${e}`,"humanComment"),humanCommentEdit:o(e=>`/v1/human/comments/${e}/edit`,"humanCommentEdit"),humanCommentResolve:o(e=>`/v1/human/comments/${e}/resolve`,"humanCommentResolve"),humanCommentReopen:o(e=>`/v1/human/comments/${e}/reopen`,"humanCommentReopen"),humanCommentDelete:o(e=>`/v1/human/comments/${e}/delete`,"humanCommentDelete"),humanCommentFork:o(e=>`/v1/human/comments/${e}/fork`,"humanCommentFork"),humanInbox:o(()=>"/v1/human/inbox","humanInbox"),humanInboxTicket:o(e=>`/v1/human/inbox/${e}`,"humanInboxTicket"),humanInboxRespond:o(e=>`/v1/human/inbox/${e}/respond`,"humanInboxRespond"),humanInboxProgress:o(e=>`/v1/human/inbox/${e}/progress`,"humanInboxProgress"),humanInboxResponse:o(e=>`/v1/human/inbox/${e}/response`,"humanInboxResponse"),humanInboxCancel:o(e=>`/v1/human/inbox/${e}/cancel`,"humanInboxCancel"),humanInboxFeedbackResolve:o((e,n)=>`/v1/human/inbox/${e}/feedback-comments/${n}/resolve`,"humanInboxFeedbackResolve"),humanRequests:o(()=>"/v1/human/requests","humanRequests"),humanComponents:o(()=>"/v1/human/components","humanComponents"),humanRequest:o(e=>`/v1/human/requests/${e}`,"humanRequest"),humanRequestReplace:o(e=>`/v1/human/requests/${e}/replace`,"humanRequestReplace"),humanRequestRespond:o(e=>`/v1/human/requests/${e}/respond`,"humanRequestRespond"),humanRequestDismiss:o(e=>`/v1/human/requests/${e}/dismiss`,"humanRequestDismiss"),humanRequestCancel:o(e=>`/v1/human/requests/${e}/cancel`,"humanRequestCancel"),profiles:o(()=>"/v1/profiles","profiles"),profile:o(e=>`/v1/profiles/${e}`,"profile"),profilePause:o(e=>`/v1/profiles/${e}/pause`,"profilePause"),profileResume:o(e=>`/v1/profiles/${e}/resume`,"profileResume"),profileMetadata:o(e=>`/v1/profiles/${e}/metadata`,"profileMetadata"),appEnv:o(()=>"/v1/apps/self/env","appEnv"),appEnvVar:o(e=>`/v1/apps/self/env/${encodeURIComponent(e)}`,"appEnvVar"),profileEnv:o(e=>`/v1/profiles/${e}/env`,"profileEnv"),profileEnvVar:o((e,n)=>`/v1/profiles/${e}/env/${n}`,"profileEnvVar"),modelAuths:o(()=>"/v1/model-auth","modelAuths"),modelAuthReadiness:o(()=>"/v1/model-auth/readiness","modelAuthReadiness"),modelAuth:o(e=>`/v1/model-auth/${e}`,"modelAuth"),modelAuthFlows:o(()=>"/v1/model-auth/flows","modelAuthFlows"),modelAuthFlow:o(e=>`/v1/model-auth/flows/${encodeURIComponent(e)}`,"modelAuthFlow"),modelAuthFlowComplete:o(e=>`/v1/model-auth/flows/${encodeURIComponent(e)}/complete`,"modelAuthFlowComplete"),modelAuthFlowCancel:o(e=>`/v1/model-auth/flows/${encodeURIComponent(e)}/cancel`,"modelAuthFlowCancel"),filePeek:o(()=>"/v1/files/peek","filePeek"),fileWrite:o(()=>"/v1/files/write","fileWrite"),fileList:o(()=>"/v1/files/list","fileList"),bash:o(()=>"/v1/bash","bash"),objects:o(()=>"/v1/objects","objects"),object:o(e=>`/v1/objects/${encodeURIComponent(e)}`,"object"),objectsSearch:o(()=>"/v1/objects/search","objectsSearch"),objectWatch:o(e=>`/v1/objects/${encodeURIComponent(e)}/watch`,"objectWatch"),customObjects:o(()=>"/v1/custom-objects","customObjects"),customObject:o(e=>`/v1/custom-objects/${encodeURIComponent(e)}`,"customObject"),customObjectEvents:o(e=>`/v1/custom-objects/${encodeURIComponent(e)}/events`,"customObjectEvents"),customObjectDeliveries:o(e=>`/v1/custom-objects/${encodeURIComponent(e)}/deliveries`,"customObjectDeliveries"),customObjectAck:o(e=>`/v1/custom-objects/${encodeURIComponent(e)}/deliveries/ack`,"customObjectAck"),objectEdges:o(e=>`/v1/objects/${encodeURIComponent(e)}/edges`,"objectEdges"),docs:o(()=>"/v1/docs","docs"),doc:o(e=>`/v1/docs/${encodeURIComponent(e)}`,"doc"),docMove:o(e=>`/v1/docs/${encodeURIComponent(e)}/move`,"docMove"),docHistory:o(e=>`/v1/docs/${encodeURIComponent(e)}/history`,"docHistory"),docsLint:o(()=>"/v1/docs/lint","docsLint"),pluginAppToken:o(e=>`/v1/plugins/${encodeURIComponent(e)}/app-token`,"pluginAppToken"),pluginCallHeaders:o(e=>`/v1/plugins/${encodeURIComponent(e)}/call-headers`,"pluginCallHeaders"),documentsReconcilePackages:o(()=>"/v1/documents/reconcile-packages","documentsReconcilePackages")};export{t as API_VERSION,a as routes};
@@ -67,6 +67,113 @@ A definition with `version: N`, or a list of definitions with one per supported
67
67
 
68
68
  A new optional flag, a new leaf, a new optional output field and changed prose are additive.
69
69
 
70
+ ## Local plugins
71
+
72
+ A plugin whose endpoint is `http://localhost`, `http://*.localhost` or another loopback host is a local plugin. crtr does not start it: run the service however you like (a terminal, launchd, a container). What crtr gives a local plugin is caller context on every call, a signature that proves the call came from crtr, and a credential for acting on the canvas.
73
+
74
+ ### Declaring object kinds and scopes
75
+
76
+ `plugin.json` (and `bundle.json`) take two optional top-level blocks:
77
+
78
+ ```json
79
+ {
80
+ "object_kinds": {
81
+ "search.page": {
82
+ "description": "A tracked web page",
83
+ "events": { "changed": { "level": 5, "supersedes": true } },
84
+ "read": { "command": ["page", "read"] }
85
+ }
86
+ },
87
+ "scopes": ["crtr:objects:link:node"]
88
+ }
89
+ ```
90
+
91
+ - A kind name's first segment is the plugin name. `events` holds at most 64 entries, each with a `level` from 1 to 10 and an optional boolean `supersedes`.
92
+ - `read.command` is a leaf path below the plugin's root command. crtr calls it with `{ "id", "name" }` to read an instance and expects a string field `markdown`.
93
+ - Each `scopes` entry has the form `crtr:objects:<read|watch|link|write>:<user|profile:<p>|app:<x>|node>`. A scope may not name the plugin's own space (`app:<plugin>`). A provider bundle may not declare `scopes`: a cloud app gets its scopes from directory consent.
94
+ - Install and update refuse an invalid block and leave the installed version in place. A kind another plugin already owns is refused with `kind_owned`; the plugin's other kinds still apply.
95
+
96
+ ### The app token
97
+
98
+ crtr gives each enabled local plugin that declares `object_kinds` or `scopes`, or uses an HTTP endpoint, one credential, `crtr_app_…`, carrying the manifest's `scopes`. The plugin uses it as `Authorization: Bearer <token>` against crtrd's `/v1` API, to register instances, link a caller, publish events and read.
99
+
100
+ A service fetches the token once at startup over crtrd's unix socket, with no bearer: it asks as the person who runs it, so it must run as that user.
101
+
102
+ ```
103
+ GET /v1/plugins/<name>/app-token (over the daemon socket)
104
+ → { "token": "crtr_app_…", "socket": "/path/to/the/daemon.sock" }
105
+ ```
106
+
107
+ The answer is `404 not_found` when the plugin is not installed, not enabled, invalid, or holds no token. Fetch it again after an update, which can change the scopes, and after a `401` (uninstall or disable revokes it).
108
+
109
+ crtr never sends this token to the plugin's port: not as a bearer, a header or a body field. It reaches an exec plugin as `CRTR_APP_TOKEN` and `CRTR_DAEMON_SOCKET` in the environment. Keep it in memory or in a file with mode 0600, and never log it.
110
+
111
+ ### `Crtr-Caller`
112
+
113
+ Every HTTP call to a plugin, local or hosted, carries who made it:
114
+
115
+ ```
116
+ Crtr-Caller: node=<id>; machine=<id>; profile=<id>; run=<id>
117
+ ```
118
+
119
+ The fields appear in that order. A field with no value is left out, and a call with none omits the header. A service uses `node` to link the calling node to an object it owns. The value comes from crtrd's view of the caller; a manifest cannot set `Crtr-Caller`, `Crtr-Signature` or `Crtr-Request-Id`.
120
+
121
+ ### `Crtr-Signature`
122
+
123
+ crtrd signs a call to a local plugin when the plugin holds a token and the request goes to the origin of its installed endpoint. Any other URL gets `Crtr-Caller` and no signature.
124
+
125
+ ```
126
+ Crtr-Signature: v1,t=<unix seconds>,h=<signed header names>,sig=<base64url HMAC-SHA256(token, canonical)>
127
+ ```
128
+
129
+ - `h` lists, lowercase, sorted and joined with `;`, every header crtr sent except `crtr-caller` and `crtr-signature`. It always includes `crtr-request-id`, a fresh UUID per call and the signature's nonce. A retry after a connection error sends the same id and the same signature.
130
+ - `canonical` is these lines joined with `\n`, no trailing newline:
131
+ 1. `v1`
132
+ 2. `t`
133
+ 3. the HTTP method, uppercase
134
+ 4. the request path with its query string, as received
135
+ 5. the lowercase hex sha256 of the exact body bytes (of the empty string when there is no body)
136
+ 6. the `Crtr-Caller` value, or an empty line
137
+ 7. `h`
138
+ 8. the lowercase hex sha256 of `<name>:<value>\n` for each name in `h`, in order, with each value as received: leading and trailing spaces and tabs removed, which is what Node and every other HTTP parser hands the service. crtr trims a mapped header value the same way before it signs and sends, so a padded value in a command argument is delivered without its padding
139
+
140
+ A service verifies a call in this order, and answers `401` when any step fails:
141
+
142
+ 1. Parse the header. The version must be `v1`.
143
+ 2. `|now − t| ≤ 300` seconds.
144
+ 3. `h` must include `crtr-request-id`, be sorted, and name only headers present on the request.
145
+ 4. Recompute `canonical` from the request as received and compare the MAC with a constant-time comparison.
146
+ 5. Reject a `Crtr-Request-Id` seen in the last 600 seconds, and remember this one. Do this after step 4, so a forged request cannot fill the cache.
147
+ 6. Trust only the headers named in `h`, plus `Crtr-Caller`.
148
+
149
+ ```ts
150
+ import { createHash, createHmac, timingSafeEqual } from 'node:crypto';
151
+
152
+ const sha = (data: string | Buffer) => createHash('sha256').update(data).digest('hex');
153
+
154
+ export function verify(token: string, req: { method: string; target: string; body: Buffer; headers: Record<string, string> },
155
+ seen: Map<string, number>, now = Date.now()): boolean {
156
+ const [v, t, h, sig] = (req.headers['crtr-signature'] ?? '').split(',');
157
+ if (v !== 'v1' || !t?.startsWith('t=') || !h?.startsWith('h=') || !sig?.startsWith('sig=')) return false;
158
+ const seconds = Number(t.slice(2));
159
+ if (!Number.isInteger(seconds) || Math.abs(now / 1000 - seconds) > 300) return false;
160
+ const names = h.slice(2).split(';');
161
+ if (!names.includes('crtr-request-id') || names.some((n, i) => req.headers[n] === undefined || (i > 0 && names[i - 1]! >= n))) return false;
162
+ const canonical = ['v1', String(seconds), req.method.toUpperCase(), req.target, sha(req.body),
163
+ req.headers['crtr-caller'] ?? '', names.join(';'), sha(names.map((n) => `${n}:${req.headers[n]}\n`).join(''))].join('\n');
164
+ const expected = createHmac('sha256', token).update(canonical).digest();
165
+ const given = Buffer.from(sig.slice(4), 'base64url');
166
+ if (given.length !== expected.length || !timingSafeEqual(given, expected)) return false;
167
+ for (const [id, at] of seen) if (now - at > 600_000) seen.delete(id);
168
+ const id = req.headers['crtr-request-id']!;
169
+ if (seen.has(id)) return false;
170
+ seen.set(id, now);
171
+ return true;
172
+ }
173
+ ```
174
+
175
+ `req.headers` is keyed by lowercase name (Node's `IncomingMessage` already does this) and `req.target` is `req.url`.
176
+
70
177
  ## Archive response
71
178
 
72
179
  The install response is an uncompressed tar with `Content-Type: application/x-tar`. Do not configure a proxy, CDN, or framework middleware to gzip or otherwise compress it. Crtr rejects compressed archive bytes. The handler sends an ETag and supports conditional `If-None-Match` requests automatically.