@coreframe/dev-supervisor 0.2.5 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -46,6 +46,13 @@ type DevSupervisorReplayCompleteEvent = {
46
46
  timestamp: string;
47
47
  };
48
48
  type DevSupervisorManagedDevEvent = {
49
+ event: "managed-dev";
50
+ kind: "handoff";
51
+ resource: "managed-dev";
52
+ implementationVersion: string;
53
+ sequence: number;
54
+ timestamp: string;
55
+ } | {
49
56
  event: "managed-dev";
50
57
  kind: "codex";
51
58
  requestId: string;
@@ -121,11 +128,13 @@ type DevSupervisorManagedDevSession = {
121
128
  activate(): Promise<void>;
122
129
  getStatus(): unknown;
123
130
  notifyCheckoutChanged?(): void;
131
+ prepareHandoff?(): boolean;
124
132
  close(): Promise<void>;
125
133
  };
126
134
  type DevSupervisorManagedDevStarter = (options: {
127
135
  cwd: string;
128
136
  env: NodeJS.ProcessEnv;
137
+ onCheckoutUpdate(id: string): Promise<void>;
129
138
  onRestart(): void;
130
139
  onStatusChange(status: unknown): void;
131
140
  }) => Promise<DevSupervisorManagedDevSession>;
@@ -134,13 +143,15 @@ declare function connectDevSupervisor({
134
143
  env,
135
144
  requiredResources,
136
145
  supervisorEntry,
137
- implementationVersion
146
+ implementationVersion,
147
+ forceRestart
138
148
  }?: {
139
149
  cwd?: string;
140
150
  env?: NodeJS.ProcessEnv;
141
151
  requiredResources?: DevSupervisorResource[];
142
152
  supervisorEntry?: string;
143
- implementationVersion?: string;
153
+ implementationVersion?: string; /** Request shutdown of a mismatched supervisor even if it still holds leases. */
154
+ forceRestart?: boolean;
144
155
  }): Promise<DevSupervisorClient>;
145
156
  declare function connectExistingDevSupervisor({
146
157
  cwd,
@@ -153,11 +164,13 @@ declare function connectExistingDevSupervisor({
153
164
  requiredResources?: DevSupervisorResource[];
154
165
  implementationVersion?: string;
155
166
  }): Promise<DevSupervisorClient | undefined>;
156
- /** Stops the detached supervisor for a project directory. */
167
+ /** Stops the detached supervisor for a project directory and waits for its shutdown. */
157
168
  declare function stopDevSupervisor({
158
- cwd
169
+ cwd,
170
+ onlyIfIdle
159
171
  }?: {
160
- cwd?: string;
172
+ cwd?: string; /** Refuse active leases and work, and shut down any lingering local database. */
173
+ onlyIfIdle?: boolean;
161
174
  }): Promise<boolean>;
162
175
  declare class DevSupervisorClient {
163
176
  readonly state: DevSupervisorState;
@@ -201,9 +214,13 @@ declare class DevSupervisorClient {
201
214
  leaseId: string;
202
215
  }>;
203
216
  acquireManagedDev({
204
- env
217
+ env,
218
+ followsHandoff,
219
+ holdsCheckoutUpdates
205
220
  }?: {
206
221
  env?: NodeJS.ProcessEnv;
222
+ followsHandoff?: boolean;
223
+ holdsCheckoutUpdates?: boolean;
207
224
  }): Promise<{
208
225
  leaseId: string;
209
226
  state: "reused" | "started";
@@ -227,6 +244,7 @@ declare class DevSupervisorClient {
227
244
  status: unknown;
228
245
  }>;
229
246
  notifyManagedDevCheckoutChanged(leaseId: string): Promise<void>;
247
+ acknowledgeCheckoutUpdate(leaseId: string, id: string): Promise<void>;
230
248
  resetIdleManagedDev(): Promise<{
231
249
  reset: boolean;
232
250
  }>;
@@ -235,8 +253,8 @@ declare class DevSupervisorClient {
235
253
  subscriptionId: string;
236
254
  }>;
237
255
  status(): Promise<unknown>;
238
- shutdown(): Promise<void>;
239
- retireIfIdle(): Promise<void>;
256
+ shutdown(handoffVersion?: string): Promise<void>;
257
+ retireIfIdle(implementationVersion?: string): Promise<void>;
240
258
  onEvent(listener: (event: DevSupervisorEvent) => void): () => boolean;
241
259
  onClose(listener: (error: Error) => void): () => boolean;
242
260
  waitForServiceExit(resource: DevSupervisorResource): Promise<void>;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{DevDiagnostics as e,devDiagnosticContext as t,devDiagnosticError as n,devDiagnosticEvent as r,devDiagnosticPhase as i}from"./diagnostics.js";import{createLazyTcpProxy as a}from"./lazy-tcp-proxy.js";import{prepareProjectServices as o}from"./project-services.js";import{spawn as s}from"node:child_process";import{createHash as c,randomUUID as l}from"node:crypto";import{readFileSync as ee}from"node:fs";import{appendFile as u,mkdir as d,readFile as f,rename as te,rm as ne,stat as re,unlink as p,writeFile as m}from"node:fs/promises";import{createConnection as h,createServer as ie}from"node:net";import{tmpdir as g}from"node:os";import _ from"node:path";import v from"node:process";import{Writable as ae}from"node:stream";import{fileURLToPath as oe}from"node:url";const y=JSON.parse(ee(_.resolve(_.dirname(oe(import.meta.url)),`../package.json`),`utf8`)).version,b=`.coreframe/dev-supervisor`,x=`supervisor.json`,S=`logs`,C=1*1024*1024,w=4*1024*1024,T=45e3;async function E({cwd:e=v.cwd(),env:t=v.env,requiredResources:n=[],supervisorEntry:r,implementationVersion:i}={}){let a=await D({cwd:e,env:t,requiredResources:n,implementationVersion:i});if(a)return a;let o=await R(e),s=await F(e,!i);if(!s){if(o=await I(e),!B(o,n))throw Error(`The development supervisor does not provide the required resources.`);return N({cwd:e,env:t,state:o})}try{if(o=await R(e),o&&o.cwd===_.resolve(e)&&Z(o.pid)&&i&&o.implementationVersion!==i){let n=await N({cwd:e,env:t,state:o});try{await n.retireIfIdle()}catch(e){let t=e instanceof Error&&`code`in e&&e.code===`INVALID_REQUEST`;throw Error(t?`The existing development supervisor predates automatic handoff. Stop its dev servers and supervisor, then retry.`:`The existing development supervisor uses a different version and cannot hand off while it is active. Stop its dev servers and supervisor, then retry.`,{cause:e})}finally{n.close()}await L(e,o.supervisorId),o=void 0}if(o&&o.cwd===_.resolve(e)&&Z(o.pid)){if(!B(o,n))throw Error(`The development supervisor does not provide the required resources.`);return await N({cwd:e,env:t,state:o})}if(o&&await H(e,o),!r)throw Error(`A development supervisor process entry is required to start the supervisor.`);if(await P({cwd:e,env:t,entry:r}),o=await I(e),i&&o.implementationVersion!==i)throw Error(`The started development supervisor has an unexpected implementation version.`);if(!B(o,n))throw Error(`The development supervisor does not provide the required resources.`);return N({cwd:e,env:t,state:o})}finally{await s()}}async function D({cwd:e=v.cwd(),env:t=v.env,requiredResources:n=[],implementationVersion:r}={}){let i=await R(e);if(!(!i||i.cwd!==_.resolve(e)||!Z(i.pid)||!B(i,n)||r!==void 0&&i.implementationVersion!==r))try{return await N({cwd:e,env:t,state:i})}catch{await H(e,i);return}}async function O({cwd:e=v.cwd()}={}){let t=await R(e);if(!t||t.cwd!==_.resolve(e)||!Z(t.pid))return await H(e,t),!1;let n=await N({cwd:e,env:v.env,state:t});try{await n.shutdown()}finally{n.close()}return await L(e,t.supervisorId),!0}var k=class e{state;socket;pending=new Map;listeners=new Set;closeListeners=new Set;leases=new Set;decoder=new j;closed=!1;closeError;renewalTimer;constructor(e){this.state=e.state,this.socket=e.socket,this.socket.on(`data`,e=>{for(let t of this.decoder.push(e))this.handleFrame(t)}),this.socket.on(`close`,()=>this.handleClose(Error(`Development supervisor disconnected.`))),this.socket.on(`error`,e=>this.handleClose(e)),this.renewalTimer=setInterval(()=>void this.renewLeases(),T/3),this.renewalTimer.unref()}static async create(t){let n=new e(t);return await n.request(`hello`,{protocol:1,token:t.state.token}),n}async acquirePostgres({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`postgres`,config:e,env:Y(t??v.env)});return this.leases.add(n.leaseId),n}async acquireSqlite({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`sqlite`,config:e,env:Y(t??v.env)});return this.leases.add(n.leaseId),n}async acquireProjectServices({services:e,env:t=v.env}){let n=await this.request(`acquire`,{resource:`project-services`,services:e,env:Y(t)});return this.leases.add(n.leaseId),n}async acquireManagedDev({env:e}={}){let t=await this.request(`acquire`,{resource:`managed-dev`,env:Y(e??v.env)});return this.leases.add(t.leaseId),t}async managedDevAction({action:e,requestId:t,operationId:n,requestKey:r}){return this.request(`managed-dev-action`,{action:e,requestId:t,operationId:n,requestKey:r})}async managedDevStatus(){return this.request(`managed-dev-status`)}async notifyManagedDevCheckoutChanged(e){await this.request(`managed-dev-checkout-changed`,{leaseId:e})}async resetIdleManagedDev(){return this.request(`managed-dev-reset-idle`)}async release(e){this.leases.delete(e),await this.request(`release`,{leaseId:e})}async subscribe(e){return this.request(`subscribe`,{resources:e})}async status(){return this.request(`status`)}async shutdown(){await this.request(`shutdown`)}async retireIfIdle(){await this.request(`retire-if-idle`)}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onClose(e){return this.closed?(e(this.closeError??Error(`Development supervisor client is closed.`)),()=>!1):(this.closeListeners.add(e),()=>this.closeListeners.delete(e))}waitForServiceExit(e){return this.closed?Promise.resolve():new Promise(t=>{let n=()=>{r(),this.closeListeners.delete(n),t()},r=this.onEvent(t=>{!(`resource`in t)||t.resource!==e||t.event!==`service`||(t.state===`failed`||t.state===`stopped`)&&n()});this.closeListeners.add(n)})}close(){this.closed||(this.socket.end(),this.handleClose(Error(`Development supervisor client closed.`)))}request(e,t){if(this.closed)return Promise.reject(Error(`Development supervisor client is closed.`));let n=l();return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i}),this.socket.write(M({id:n,method:e,params:t,type:`request`}))})}async renewLeases(){for(let e of this.leases)if(await this.request(`renew`,{leaseId:e}).catch(t=>{this.leases.delete(e),this.handleClose(t instanceof Error?t:Error(String(t))),this.socket.destroy()}),this.closed)return}handleFrame(e){if(e.type===`event`){for(let t of this.listeners)t(e.event);return}if(e.type!==`response`)return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.result):t.reject(le(e.error)))}handleClose(e){if(!this.closed){this.closed=!0,this.closeError=e,clearInterval(this.renewalTimer);for(let t of this.pending.values())t.reject(e);this.pending.clear();for(let t of this.closeListeners)t(e);this.closeListeners.clear()}}};async function A({cwd:e=v.cwd(),startPostgres:t,startSqlite:n,startManagedDev:r,implementationVersion:i}={}){if(!t)throw Error(`A PostgreSQL starter is required to run the development supervisor.`);let a=_.resolve(e,b);await d(a,{recursive:!0,mode:448}),await d(_.join(a,S),{recursive:!0,mode:448});let o=await R(e);if(o&&o.pid!==v.pid&&Z(o.pid))throw Error(`A Coreframe development supervisor is already running for this directory.`);let s=U(e);v.platform!==`win32`&&await p(s).catch(()=>void 0);let c=new se({cwd:_.resolve(e),endpoint:s,root:a,startPostgres:t,startSqlite:n,startManagedDev:r,implementationVersion:i});await c.listen();let l=()=>{c.shutdown()};v.once(`SIGINT`,l),v.once(`SIGTERM`,l);try{await c.waitForShutdown()}finally{v.off(`SIGINT`,l),v.off(`SIGTERM`,l)}}var se=class{diagnostics;clients=new Set;leases=new Map;resourceOperations=new Map;server;root;state;startPostgres;startSqlite;startManagedDev;postgres;sqlite;managedDev;projectServices=new Map;sequence=0;shutdownPromise;shutdownRequested=!1;idleTimer;leaseTimer;lastLeaseSweepAt=Date.now();postgresStopTimer;sqliteStopTimer;managedDevStopTimer;constructor({cwd:e,endpoint:t,root:n,startPostgres:r,startSqlite:i,startManagedDev:a,implementationVersion:o}){this.root=n,this.startPostgres=r,this.startSqlite=i,this.startManagedDev=a;let s=[`postgres`,`project-services`];i&&s.push(`sqlite`),a&&s.push(`managed-dev`),this.state={availableResources:s,cwd:e,endpoint:t,pid:v.pid,protocol:1,supervisorId:l(),token:l(),implementationVersion:o},this.server=ie(e=>this.accept(e)),this.leaseTimer=setInterval(()=>this.expireLeases(),5e3),this.leaseTimer.unref()}async listen(){await new Promise((e,t)=>{this.server.once(`error`,t),this.server.listen(this.state.endpoint,()=>{this.server.off(`error`,t),e()})}),await V(this.state,this.root)}waitForShutdown(){return new Promise(e=>{this.shutdownPromise?this.shutdownPromise.then(()=>e()):this.resolveShutdown=e})}async shutdown({stopPostgres:e=!0,stopSqlite:t=!0}={}){return this.shutdownPromise||=(async()=>{this.shutdownRequested=!0,this.idleTimer&&clearTimeout(this.idleTimer),clearInterval(this.leaseTimer),await Promise.all(this.resourceOperations.values()),this.leases.clear(),await Promise.all([...this.projectServices.values()].map(e=>e.close())),this.projectServices.clear(),await this.stopManagedDev(),e?await this.stopPostgres():(this.cancelPostgresStop(),this.postgres=void 0),t?await this.stopSqlite():(this.cancelSqliteStop(),this.sqlite=void 0);for(let e of this.clients)e.close();await new Promise(e=>this.server.close(()=>e())),await p(this.state.endpoint).catch(()=>void 0),await p(_.join(this.root,x)).catch(()=>void 0),this.diagnostics?.event(`supervisor.stopped`,{supervisorId:this.state.supervisorId}),this.diagnostics?.close(),this.resolveShutdown?.()})(),this.shutdownPromise}resolveShutdown;accept(e){let t=new ce(this,e);this.clients.add(t),e.once(`close`,()=>{this.clients.delete(t);for(let e of this.leases.values())e.connection===t&&this.releaseLease(e.id);this.maybeScheduleIdleShutdown()})}async handleRequest(e,t){try{let n=await this.dispatch(e,t.method,t.params??{});e.respond(t.id,{ok:!0,result:n})}catch(n){e.respond(t.id,{ok:!1,error:$(n)})}}publish(e,t){let n={...e,sequence:++this.sequence,timestamp:new Date().toISOString()};if(t)t.publish(n);else for(let e of this.clients)e.publish(n);return n}async addSubscription(e,t){return e.subscribe(t),e.publish({event:`replay-complete`,sequence:this.sequence,timestamp:new Date().toISOString()}),{subscriptionId:l()}}async dispatch(e,t,n){if(this.shutdownRequested&&t!==`shutdown`)throw Q(`SUPERVISOR_STOPPING`,`Development supervisor is stopping.`,!0);switch(t){case`hello`:return this.hello(e,n);case`status`:return this.status();case`managed-dev-status`:return this.managedDevStatus();case`managed-dev-checkout-changed`:{let t=this.leases.get(q(n.leaseId));t?.connection===e&&t.resource===`managed-dev`&&this.managedDev?.session.notifyCheckoutChanged?.();return}case`managed-dev-reset-idle`:return this.withResourceOperation(`managed-dev`,async()=>!this.managedDev||this.managedDev.leases.size>0?{reset:!1}:(await this.stopManagedDev(),{reset:!0}));case`managed-dev-action`:return this.managedDevAction(e,n);case`subscribe`:return this.addSubscription(e,W(n.resources));case`acquire`:return this.withResourceOperation(G(n.resource),()=>this.acquire(e,n));case`release`:await this.releaseLease(q(n.leaseId));return;case`renew`:return this.renewLease(q(n.leaseId));case`shutdown`:this.shutdownRequested=!0,setImmediate(()=>void this.shutdown({stopPostgres:!1}));return;case`retire-if-idle`:if(this.leases.size>0||this.resourceOperations.size>0)throw Q(`SUPERVISOR_BUSY`,`Development supervisor still owns active work.`,!0);this.shutdownRequested=!0,setImmediate(()=>void this.shutdown());return;default:throw Q(`INVALID_REQUEST`,`Unknown supervisor method: ${t}.`,!1)}}async withResourceOperation(e,t){let n=this.resourceOperations.get(e),r,i=new Promise(e=>{r=e});this.resourceOperations.set(e,i),n&&await n;try{return await t()}finally{r(),this.resourceOperations.get(e)===i&&this.resourceOperations.delete(e)}}hello(e,t){if(t.protocol!==1||t.token!==this.state.token)throw e.close(),Q(`AUTH_FAILED`,`Invalid supervisor protocol or token.`,!1);return e.authenticated=!0,{cwd:this.state.cwd,protocol:1,supervisorId:this.state.supervisorId}}status(){return{managedDev:this.managedDev?{leases:this.managedDev.leases.size,state:`running`}:void 0,postgres:this.postgres?{leases:this.postgres.leases.size,state:`running`}:void 0,sqlite:this.sqlite?{leases:this.sqlite.leases.size,state:`running`}:void 0}}async acquire(e,t){let n=G(t.resource);if(n===`managed-dev`)return this.acquireManagedDev(e,K(t));if(n===`postgres`)return this.acquirePostgres(e,K(t));if(n===`sqlite`)return this.acquireSqlite(e,K(t));if(n===`project-services`)return this.acquireProjectServices(e,t);throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${n}.`,!1)}async acquireProjectServices(e,t){let n=await o({cwd:this.state.cwd,env:J(t.env),services:t.services,onFailure:t=>{this.publish({event:`service`,resource:`project-services`,state:`failed`,error:t},e)}});if(e.closed||this.shutdownRequested)throw await n.close(),Error(`The development session ended before its service endpoints were ready.`);let r=this.createLease(e,`project-services`);return this.projectServices.set(r.id,n),{bindings:n.bindings,endpoints:n.endpoints,leaseId:r.id}}async acquireManagedDev(t,n){if(!this.startManagedDev)throw Error(`A managed development starter is required to run managed development.`);if(this.diagnostics??=new e(this.state.cwd,`supervisor`),this.diagnostics.event(`supervisor.attached`,{supervisorId:this.state.supervisorId,reused:!!this.managedDev}),this.managedDev){this.cancelManagedDevStop();let e=this.createLease(t,`managed-dev`);return this.managedDev.leases.add(e.id),{leaseId:e.id,state:`reused`,status:this.managedDev.session.getStatus()}}let r=J(n.env),i=await this.startManagedDev({cwd:this.state.cwd,env:Y(r),onRestart:()=>{this.diagnostics?.event(`restart.requested`,{supervisorId:this.state.supervisorId}),this.publish({event:`managed-dev`,kind:`restart`,resource:`managed-dev`})},onStatusChange:e=>{this.publish({event:`managed-dev`,kind:`status`,resource:`managed-dev`,status:e})}}),a={leases:new Set,session:i};this.managedDev=a;try{await i.activate()}catch(e){throw this.managedDev=void 0,await i.close(),e}let o=this.createLease(t,`managed-dev`);return a.leases.add(o.id),{leaseId:o.id,state:`started`,status:i.getStatus()}}managedDevStatus(){if(!this.managedDev)throw Error(`Managed development is not active.`);return{status:this.managedDev.session.getStatus()}}async managedDevAction(e,t){if(!this.managedDev)throw Error(`Managed development is not active.`);let n=q(t.requestId);if(!n)throw Q(`INVALID_REQUEST`,`A managed development action request ID is required.`,!1);try{let r=q(t.operationId)||n;return await this.diagnostics.run({operationId:r,supervisorId:this.state.supervisorId,supervisorRequestId:n},()=>i(`supervisor.action`,()=>this.managedDev.session.action(t.action,{operationId:r,requestKey:q(t.requestKey)||void 0,onCodexEvent:t=>{this.publish({codex:t,event:`managed-dev`,kind:`codex`,requestId:n,resource:`managed-dev`},e)}})))}catch(e){return{error:e instanceof Error?e.message:String(e),status:this.managedDev.session.getStatus()}}}async acquirePostgres(e,t){let n=this.postgres===void 0;if(this.postgres)this.cancelPostgresStop();else{let e=await this.createLogStream(`postgres`),n=J(t.env),r=await this.startPostgres({config:t.config,cwd:this.state.cwd,env:Y(n),failIfRunning:!1,postgresOutput:e});this.postgres={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`postgres`,state:`running`})}let r=this.createLease(e,`postgres`);return this.postgres.leases.add(r.id),{env:Y(this.postgres.env),leaseId:r.id,state:n?`started`:`reused`}}async acquireSqlite(e,t){if(!this.startSqlite)throw Error(`A SQLite starter is required to run the development supervisor.`);let n=this.sqlite===void 0;if(this.sqlite)this.cancelSqliteStop();else{let e=await this.createLogStream(`sqlite`),n=J(t.env),r=await this.startSqlite({config:t.config,cwd:this.state.cwd,env:Y(n),tursoOutput:e});this.sqlite={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`sqlite`,state:`running`})}let r=this.createLease(e,`sqlite`);return this.sqlite.leases.add(r.id),{env:Y(this.sqlite.env),leaseId:r.id,state:n?`started`:`reused`}}createLease(e,t){let n={connection:e,expiresAt:Date.now()+T,id:l(),resource:t};return this.leases.set(n.id,n),t===`managed-dev`&&this.diagnostics?.event(`lease.acquired`,{leaseId:n.id,supervisorId:this.state.supervisorId}),n}renewLease(e){let t=this.leases.get(e);if(!t)throw this.diagnostics?.event(`lease.renewal-rejected`,{leaseId:e},`warn`),Q(`LEASE_EXPIRED`,`The supervisor lease is no longer active.`,!0);return t.expiresAt=Date.now()+T,{expiresAt:t.expiresAt}}expireLeases(){let e=Date.now(),t=e-this.lastLeaseSweepAt;if(this.lastLeaseSweepAt=e,t>=1e4){this.diagnostics?.event(`supervisor.resumed`,{sweepDelayMs:t});for(let t of this.leases.values())t.expiresAt=Math.max(t.expiresAt,e+T);return}for(let t of this.leases.values())t.expiresAt<=e&&(t.resource===`managed-dev`&&this.diagnostics?.event(`lease.expired`,{leaseId:t.id,overdueMs:e-t.expiresAt},`warn`),this.releaseLease(t.id))}async releaseLease(e){let t=this.leases.get(e);t&&(this.leases.delete(e),t.resource===`postgres`?(this.postgres?.leases.delete(e),this.postgres?.leases.size===0&&this.schedulePostgresStop()):t.resource===`sqlite`?(this.sqlite?.leases.delete(e),this.sqlite?.leases.size===0&&this.scheduleSqliteStop()):t.resource===`project-services`?await this.withResourceOperation(`project-services`,async()=>{let t=this.projectServices.get(e);this.projectServices.delete(e),await t?.close()}):t.resource===`managed-dev`&&(this.managedDev?.leases.delete(e),this.diagnostics?.event(`lease.released`,{leaseId:e,remainingLeases:this.managedDev?.leases.size}),this.managedDev?.leases.size===0&&this.scheduleManagedDevStop()),this.maybeScheduleIdleShutdown())}async stopPostgres(){if(this.cancelPostgresStop(),!this.postgres)return;let e=this.postgres;this.postgres=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`postgres`,state:`stopped`})}schedulePostgresStop(){this.postgresStopTimer||(this.postgresStopTimer=setTimeout(()=>{this.postgresStopTimer=void 0,this.withResourceOperation(`postgres`,async()=>{this.postgres?.leases.size===0&&await this.stopPostgres()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.postgresStopTimer.unref())}async stopSqlite(){if(this.cancelSqliteStop(),!this.sqlite)return;let e=this.sqlite;this.sqlite=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`sqlite`,state:`stopped`})}async stopManagedDev(){if(this.cancelManagedDevStop(),!this.managedDev)return;let e=this.managedDev;this.diagnostics?.event(`session.stopping`,{supervisorId:this.state.supervisorId}),await e.session.close(),this.managedDev=void 0}scheduleSqliteStop(){this.sqliteStopTimer||(this.sqliteStopTimer=setTimeout(()=>{this.sqliteStopTimer=void 0,this.withResourceOperation(`sqlite`,async()=>{this.sqlite?.leases.size===0&&await this.stopSqlite()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.sqliteStopTimer.unref())}cancelPostgresStop(){this.postgresStopTimer&&=(clearTimeout(this.postgresStopTimer),void 0)}cancelSqliteStop(){this.sqliteStopTimer&&=(clearTimeout(this.sqliteStopTimer),void 0)}scheduleManagedDevStop(){this.managedDevStopTimer||(this.managedDevStopTimer=setTimeout(()=>{this.managedDevStopTimer=void 0,this.withResourceOperation(`managed-dev`,async()=>{this.managedDev?.leases.size===0&&await this.stopManagedDev()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e4),this.managedDevStopTimer.unref())}cancelManagedDevStop(){this.managedDevStopTimer&&=(clearTimeout(this.managedDevStopTimer),void 0)}async createLogStream(e){let t=_.join(this.root,S,`${e.replaceAll(`:`,`-`)}.log`);await d(_.dirname(t),{recursive:!0,mode:448}),await m(t,``);let n=0;return new ae({write:(r,i,a)=>{let o=String(r),s=Buffer.from(o),c=s.subarray(Math.max(0,s.length-C)),l=n+c.length>C;(l?m(t,c):u(t,c)).then(()=>{n=l?c.length:n+c.length,a()},a),this.publish({event:`log`,resource:e,stream:`stdout`,data:o})}})}maybeScheduleIdleShutdown(){this.leases.size>0||this.postgres||this.sqlite||this.managedDev||this.idleTimer||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.leases.size===0&&!this.postgres&&!this.sqlite&&!this.managedDev&&this.shutdown()},3e4),this.idleTimer.unref())}},ce=class{authenticated=!1;decoder=new j;subscriptions=new Set;eventQueue=[];queuedEventBytes=0;writingEvent=!1;droppedEventRange;server;socket;constructor(e,t){this.server=e,this.socket=t,t.on(`error`,()=>this.close()),t.on(`data`,t=>{try{for(let n of this.decoder.push(t))n.type===`request`&&(!this.authenticated&&n.method!==`hello`?this.respond(n.id,{ok:!1,error:$(Q(`AUTH_FAILED`,`Send hello first.`,!1))}):e.handleRequest(this,n))}catch{this.close()}})}get closed(){return this.socket.destroyed||this.socket.readableEnded}respond(e,t){this.socket.write(M({...t,id:e,type:`response`}))}publish(e){let t=[...this.subscriptions];t.length!==0&&(e.event!==`replay-complete`&&e.event!==`gap`&&(e.resource===void 0||!t.some(t=>t.has(e.resource)))||this.enqueueEvent(e))}subscribe(e){this.subscriptions.add(new Set(e))}close(){this.eventQueue.length=0,this.queuedEventBytes=0,this.socket.destroy()}enqueueEvent(e){let t=M({event:e,type:`event`});if(t.length>w){this.noteDropped(e);return}for(;;){let n=this.droppedEventRange?{event:{event:`gap`,from:this.droppedEventRange.from,reason:`buffer-overflow`,to:this.droppedEventRange.to,sequence:e.sequence,timestamp:new Date().toISOString()},frame:Buffer.alloc(0)}:void 0;n&&(n.frame=M({event:n.event,type:`event`}));let r=t.length+(n?.frame.length??0),i=!1;for(;this.queuedEventBytes+r>w;){let e=this.eventQueue.shift();if(!e)break;i=!0,this.queuedEventBytes-=e.frame.length,this.noteDropped(e.event)}if(!i){if(this.queuedEventBytes+r<=w){n&&(this.eventQueue.push(n),this.queuedEventBytes+=n.frame.length,this.droppedEventRange=void 0),this.eventQueue.push({event:e,frame:t}),this.queuedEventBytes+=t.length,this.pumpEvents();return}if(this.eventQueue.length===0){this.noteDropped(e);return}}}}noteDropped(e){let t=e.sequence;if(!this.droppedEventRange){this.droppedEventRange={from:t,to:t};return}this.droppedEventRange.from=Math.min(this.droppedEventRange.from,t),this.droppedEventRange.to=Math.max(this.droppedEventRange.to,t)}pumpEvents(){if(this.writingEvent||this.eventQueue.length===0||this.socket.destroyed)return;let e=this.eventQueue.shift();this.queuedEventBytes-=e.frame.length,this.writingEvent=!0,this.socket.write(e.frame,()=>{this.writingEvent=!1,this.pumpEvents()})}},j=class{buffer=Buffer.alloc(0);push(e){this.buffer=Buffer.concat([this.buffer,Buffer.from(e)]);let t=[];for(;this.buffer.length>=4;){let e=this.buffer.readUInt32BE(0);if(e>16777216)throw Error(`Development supervisor protocol frame is too large.`);if(this.buffer.length<e+4)break;let n=this.buffer.subarray(4,e+4).toString(`utf8`);this.buffer=this.buffer.subarray(e+4),t.push(JSON.parse(n))}return t}};function M(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.allocUnsafe(t.length+4);return n.writeUInt32BE(t.length,0),t.copy(n,4),n}async function N(e){let t=await new Promise((t,n)=>{let r=h(e.state.endpoint);r.once(`connect`,()=>t(r)),r.once(`error`,n)});return k.create({...e,socket:t})}async function P({cwd:e,env:t,entry:n}){s(v.execPath,[n,`--cwd`,e],{cwd:e,detached:!0,env:{...t,COREFRAME_DEV_SUPERVISOR:`1`},stdio:`ignore`}).unref()}async function F(e,t=!0){let n=_.join(e,b),r=_.join(n,`start.lock`),i=Date.now()+1e4;for(await d(n,{recursive:!0,mode:448});Date.now()<i;)try{return await m(r,`${v.pid}\n`,{flag:`wx`,mode:384}),async()=>{await p(r).catch(()=>void 0)}}catch(n){if(!(n instanceof Error&&n.code===`EEXIST`))throw n;let i=await R(e);if(t&&i&&Z(i.pid))return;try{let e=await re(r);if(Date.now()-e.mtimeMs>1e4){await p(r).catch(()=>void 0);continue}}catch{continue}await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor startup is already in progress.`)}async function I(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await R(e);if(t&&Z(t.pid))return t;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not start within 10 seconds.`)}async function L(e,t){let n=Date.now()+1e4;for(;Date.now()<n;){let n=await R(e);if(!n||n.supervisorId!==t)return;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not stop within 10 seconds.`)}async function R(e){try{let t=JSON.parse(await f(_.join(e,b,x),`utf8`)),n=t.availableResources===void 0?[`postgres`]:Array.isArray(t.availableResources)&&t.availableResources.every(z)?t.availableResources:void 0;return!n||t.protocol!==1||typeof t.cwd!=`string`||typeof t.endpoint!=`string`||typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.supervisorId!=`string`||t.implementationVersion!==void 0&&typeof t.implementationVersion!=`string`||typeof t.token!=`string`?void 0:(t.projectServices===!0&&!n.includes(`project-services`)&&n.push(`project-services`),{...t,availableResources:n})}catch{return}}function z(e){return e===`managed-dev`||e===`postgres`||e===`sqlite`||e===`project-services`}function B(e,t){return t.every(t=>e.availableResources.includes(t))}async function V(e,t){let n=_.join(t,x),r=`${n}.${l()}.tmp`;await d(_.dirname(n),{recursive:!0,mode:448});try{let t={...e,availableResources:e.availableResources.filter(e=>e!==`project-services`),projectServices:e.availableResources.includes(`project-services`)};await m(r,`${JSON.stringify(t)}\n`,{flag:`wx`,mode:384}),await te(r,n)}finally{await p(r).catch(()=>void 0)}}async function H(e,t){t&&t.cwd!==_.resolve(e)||(await ne(_.join(e,b,x),{force:!0}),t&&v.platform!==`win32`&&await p(t.endpoint).catch(()=>void 0))}function U(e){if(v.platform===`win32`)return`\\\\.\\pipe\\coreframe-dev-${c(`sha256`).update(_.resolve(e)).digest(`hex`).slice(0,24)}`;let t=c(`sha256`).update(_.resolve(e)).digest(`hex`).slice(0,24);return _.join(g(),`coreframe-dev-${t}-supervisor.sock`)}function W(e){return Array.isArray(e)?e.map(G):[`managed-dev`,`postgres`,`sqlite`,`project-services`]}function G(e){if(z(e))return e;throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${String(e)}.`,!1)}function K(e){return e&&typeof e==`object`?e:{}}function q(e){return typeof e==`string`?e:String(e??``)}function J(e){let t=K(e);return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}function Y(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function X(e,t){return Object.fromEntries(Object.entries(t).filter(t=>{let[n,r]=t;return r!==void 0&&e[n]!==r}))}function Z(e){try{return v.kill(e,0),!0}catch(e){return e instanceof Error&&e.code===`EPERM`}}function Q(e,t,n,r){return Object.assign(Error(t),{code:e,details:r,retryable:n})}function $(e){if(e&&typeof e==`object`){let t=e;return{code:t.code??`SUPERVISOR_ERROR`,details:t.details,message:t.message??String(e),retryable:t.retryable??!1}}return{code:`SUPERVISOR_ERROR`,message:String(e),retryable:!1}}function le(e){let t=Error(e?.message??`Development supervisor request failed.`);return t.code=e?.code,t.details=e?.details,t.retryable=e?.retryable,t}export{e as DevDiagnostics,k as DevSupervisorClient,E as connectDevSupervisor,D as connectExistingDevSupervisor,a as createLazyTcpProxy,t as devDiagnosticContext,n as devDiagnosticError,r as devDiagnosticEvent,i as devDiagnosticPhase,y as devSupervisorVersion,A as runDevSupervisorProcess,O as stopDevSupervisor};
1
+ import{DevDiagnostics as e,devDiagnosticContext as t,devDiagnosticError as n,devDiagnosticEvent as r,devDiagnosticPhase as i}from"./diagnostics.js";import{createLazyTcpProxy as a}from"./lazy-tcp-proxy.js";import{prepareProjectServices as o}from"./project-services.js";import{spawn as s}from"node:child_process";import{createHash as c,randomUUID as l}from"node:crypto";import{readFileSync as u}from"node:fs";import{appendFile as d,mkdir as f,readFile as p,rename as m,rm as ee,stat as h,unlink as g,writeFile as _}from"node:fs/promises";import{createConnection as te,createServer as ne}from"node:net";import{tmpdir as v}from"node:os";import y from"node:path";import b from"node:process";import{Writable as re}from"node:stream";import{fileURLToPath as ie}from"node:url";const ae=JSON.parse(u(y.resolve(y.dirname(ie(import.meta.url)),`../package.json`),`utf8`)).version,x=`.coreframe/dev-supervisor`,S=`supervisor.json`,C=`start.lock`,w=`logs`,T=1*1024*1024,E=4*1024*1024,D=45e3;async function O({cwd:e=b.cwd(),env:t=b.env,requiredResources:n=[],supervisorEntry:r,implementationVersion:i,forceRestart:a=!1}={}){let o=await k({cwd:e,env:t,requiredResources:n,implementationVersion:i});if(o)return o;let s=await z(e),c=await I(e,!i);if(!c){if(s=await L(e),!V(s,n))throw Error(`The development supervisor does not provide the required resources.`);return F({cwd:e,env:t,state:s})}try{if(s=await z(e),s&&s.cwd===y.resolve(e)&&Z(s.pid)&&i&&s.implementationVersion!==i){let n=await F({cwd:e,env:t,state:s});try{a&&r?await n.shutdown(i):await n.retireIfIdle(r?i:void 0)}catch(e){let t=e instanceof Error&&`code`in e?e.code:void 0;throw t===`SUPERVISOR_BUSY`&&e instanceof Error?Q(`SUPERVISOR_HANDOFF_BUSY`,`The existing development supervisor cannot hand off while it is active. ${e.message}`,!0):t===`INVALID_REQUEST`?Q(`SUPERVISOR_HANDOFF_UNSUPPORTED`,`The existing development supervisor predates automatic handoff. Stop its dev servers and supervisor, then retry.`,!1):e}finally{n.close()}await R(e,s.supervisorId),s=void 0}if(s&&s.cwd===y.resolve(e)&&Z(s.pid)){if(!V(s,n))throw Error(`The development supervisor does not provide the required resources.`);return await F({cwd:e,env:t,state:s})}if(s&&await U(e,s),!r)throw Error(`A development supervisor process entry is required to start the supervisor.`);if(await ce({cwd:e,env:t,entry:r}),s=await L(e),i&&s.implementationVersion!==i)throw Error(`The started development supervisor has an unexpected implementation version.`);if(!V(s,n))throw Error(`The development supervisor does not provide the required resources.`);return F({cwd:e,env:t,state:s})}finally{await c()}}async function k({cwd:e=b.cwd(),env:t=b.env,requiredResources:n=[],implementationVersion:r}={}){let i=await z(e);if(!(!i||i.cwd!==y.resolve(e)||!Z(i.pid)||!V(i,n)||r!==void 0&&i.implementationVersion!==r))try{return await F({cwd:e,env:t,state:i})}catch{!await h(y.resolve(e,x,C)).catch(()=>void 0)&&(await z(e))?.supervisorId===i.supervisorId&&await U(e,i);return}}async function oe({cwd:e=b.cwd(),onlyIfIdle:t=!1}={}){let n=await z(e);if(!n||n.cwd!==y.resolve(e)||!Z(n.pid))return t||await U(e,n),!1;let r=await F({cwd:e,env:b.env,state:n});try{t?await r.retireIfIdle():await r.shutdown()}finally{r.close()}return await R(e,n.supervisorId),!0}var A=class e{state;socket;pending=new Map;listeners=new Set;closeListeners=new Set;leases=new Set;decoder=new N;closed=!1;closeError;renewalTimer;constructor(e){this.state=e.state,this.socket=e.socket,this.socket.on(`data`,e=>{for(let t of this.decoder.push(e))this.handleFrame(t)}),this.socket.on(`close`,()=>this.handleClose(Error(`Development supervisor disconnected.`))),this.socket.on(`error`,e=>this.handleClose(e)),this.renewalTimer=setInterval(()=>void this.renewLeases(),D/3),this.renewalTimer.unref()}static async create(t){let n=new e(t);return await n.request(`hello`,{protocol:1,token:t.state.token}),n}async acquirePostgres({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`postgres`,config:e,env:Y(t??b.env)});return this.leases.add(n.leaseId),n}async acquireSqlite({config:e,env:t}={}){let n=await this.request(`acquire`,{resource:`sqlite`,config:e,env:Y(t??b.env)});return this.leases.add(n.leaseId),n}async acquireProjectServices({services:e,env:t=b.env}){let n=await this.request(`acquire`,{resource:`project-services`,services:e,env:Y(t)});return this.leases.add(n.leaseId),n}async acquireManagedDev({env:e,followsHandoff:t,holdsCheckoutUpdates:n}={}){let r=await this.request(`acquire`,{resource:`managed-dev`,env:Y(e??b.env),followsHandoff:t,holdsCheckoutUpdates:n});return this.leases.add(r.leaseId),r}async managedDevAction({action:e,requestId:t,operationId:n,requestKey:r}){return this.request(`managed-dev-action`,{action:e,requestId:t,operationId:n,requestKey:r})}async managedDevStatus(){return this.request(`managed-dev-status`)}async notifyManagedDevCheckoutChanged(e){await this.request(`managed-dev-checkout-changed`,{leaseId:e})}async acknowledgeCheckoutUpdate(e,t){await this.request(`managed-dev-checkout-update-ready`,{leaseId:e,id:t})}async resetIdleManagedDev(){return this.request(`managed-dev-reset-idle`)}async release(e){this.leases.delete(e),await this.request(`release`,{leaseId:e})}async subscribe(e){return this.request(`subscribe`,{resources:e})}async status(){return this.request(`status`)}async shutdown(e){await this.request(`shutdown`,{implementationVersion:e})}async retireIfIdle(e){await this.request(`retire-if-idle`,{implementationVersion:e})}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}onClose(e){return this.closed?(e(this.closeError??Error(`Development supervisor client is closed.`)),()=>!1):(this.closeListeners.add(e),()=>this.closeListeners.delete(e))}waitForServiceExit(e){return this.closed?Promise.resolve():new Promise(t=>{let n=()=>{r(),this.closeListeners.delete(n),t()},r=this.onEvent(t=>{!(`resource`in t)||t.resource!==e||t.event!==`service`||(t.state===`failed`||t.state===`stopped`)&&n()});this.closeListeners.add(n)})}close(){this.closed||(this.socket.end(),this.handleClose(Error(`Development supervisor client closed.`)))}request(e,t){if(this.closed)return Promise.reject(Error(`Development supervisor client is closed.`));let n=l();return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i}),this.socket.write(P({id:n,method:e,params:t,type:`request`}))})}async renewLeases(){for(let e of this.leases)if(await this.request(`renew`,{leaseId:e}).catch(t=>{this.leases.delete(e),this.handleClose(t instanceof Error?t:Error(String(t))),this.socket.destroy()}),this.closed)return}handleFrame(e){if(e.type===`event`){for(let t of this.listeners)t(e.event);return}if(e.type!==`response`)return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.result):t.reject(ue(e.error)))}handleClose(e){if(!this.closed){this.closed=!0,this.closeError=e,clearInterval(this.renewalTimer);for(let t of this.pending.values())t.reject(e);this.pending.clear();for(let t of this.closeListeners)t(e);this.closeListeners.clear()}}};async function j({cwd:e=b.cwd(),startPostgres:t,startSqlite:n,startManagedDev:r,implementationVersion:i}={}){if(!t)throw Error(`A PostgreSQL starter is required to run the development supervisor.`);let a=y.resolve(e,x);await f(a,{recursive:!0,mode:448}),await f(y.join(a,w),{recursive:!0,mode:448});let o=await z(e);if(o&&o.pid!==b.pid&&Z(o.pid))throw Error(`A Coreframe development supervisor is already running for this directory.`);let s=W(e);b.platform!==`win32`&&await g(s).catch(()=>void 0);let c=new M({cwd:y.resolve(e),endpoint:s,root:a,startPostgres:t,startSqlite:n,startManagedDev:r,implementationVersion:i});await c.listen();let l=()=>{c.shutdown()};b.once(`SIGINT`,l),b.once(`SIGTERM`,l);try{await c.waitForShutdown()}finally{b.off(`SIGINT`,l),b.off(`SIGTERM`,l)}}var M=class{diagnostics;clients=new Set;leases=new Map;resourceOperations=new Map;server;root;state;startPostgres;startSqlite;startManagedDev;postgres;sqlite;managedDev;checkoutUpdate;projectServices=new Map;sequence=0;shutdownPromise;shutdownRequested=!1;handoffVersion;idleTimer;leaseTimer;lastLeaseSweepAt=Date.now();postgresStopTimer;sqliteStopTimer;managedDevStopTimer;constructor({cwd:e,endpoint:t,root:n,startPostgres:r,startSqlite:i,startManagedDev:a,implementationVersion:o}){this.root=n,this.startPostgres=r,this.startSqlite=i,this.startManagedDev=a;let s=[`postgres`,`project-services`];i&&s.push(`sqlite`),a&&s.push(`managed-dev`),this.state={availableResources:s,cwd:e,endpoint:t,pid:b.pid,protocol:1,supervisorId:l(),token:l(),implementationVersion:o},this.server=ne(e=>this.accept(e)),this.leaseTimer=setInterval(()=>this.expireLeases(),5e3),this.leaseTimer.unref()}async listen(){await new Promise((e,t)=>{this.server.once(`error`,t),this.server.listen(this.state.endpoint,()=>{this.server.off(`error`,t),e()})}),await H(this.state,this.root)}waitForShutdown(){return new Promise(e=>{this.shutdownPromise?this.shutdownPromise.then(()=>e()):this.resolveShutdown=e})}async shutdown({stopPostgres:e=!0,stopSqlite:t=!0}={}){return this.shutdownPromise||=(async()=>{this.shutdownRequested=!0,this.idleTimer&&clearTimeout(this.idleTimer),clearInterval(this.leaseTimer),await Promise.all(this.resourceOperations.values());let n=this.handoffVersion,r=new Set;for(let e of this.leases.values())n&&e.followsHandoff?r.add(e.connection):this.leases.delete(e.id);await Promise.all([...this.projectServices.values()].map(e=>e.close())),this.projectServices.clear(),await this.stopManagedDev(),e?await this.stopPostgres():(this.cancelPostgresStop(),this.postgres=void 0),t?await this.stopSqlite():(this.cancelSqliteStop(),this.sqlite=void 0),this.leases.clear();for(let e of this.clients)n&&r.has(e)?e.close({event:`managed-dev`,kind:`handoff`,resource:`managed-dev`,implementationVersion:n,sequence:++this.sequence,timestamp:new Date().toISOString()}):e.close();await new Promise(e=>this.server.close(()=>e())),await g(this.state.endpoint).catch(()=>void 0),await g(y.join(this.root,S)).catch(()=>void 0),this.diagnostics?.event(`supervisor.stopped`,{supervisorId:this.state.supervisorId}),this.diagnostics?.close(),this.resolveShutdown?.()})(),this.shutdownPromise}resolveShutdown;accept(e){let t=new se(this,e);this.clients.add(t),e.once(`close`,()=>{this.clients.delete(t);for(let e of this.leases.values())e.connection===t&&this.releaseLease(e.id);this.maybeScheduleIdleShutdown()})}async handleRequest(e,t){try{let n=await this.dispatch(e,t.method,t.params??{});e.respond(t.id,{ok:!0,result:n})}catch(n){e.respond(t.id,{ok:!1,error:$(n)})}}publish(e,t){let n={...e,sequence:++this.sequence,timestamp:new Date().toISOString()};if(t)t.publish(n);else for(let e of this.clients)e.publish(n);return n}async addSubscription(e,t){return e.subscribe(t),e.publish({event:`replay-complete`,sequence:this.sequence,timestamp:new Date().toISOString()}),{subscriptionId:l()}}async dispatch(e,t,n){if(this.shutdownRequested){if(this.handoffVersion){if(t!==`renew`&&t!==`hello`)throw Q(`SUPERVISOR_HANDOFF_PENDING`,`Development supervisor is handing off.`,!1,{implementationVersion:this.handoffVersion})}else if(t!==`shutdown`)throw Q(`SUPERVISOR_STOPPING`,`Development supervisor is stopping.`,!0)}switch(t){case`hello`:return this.hello(e,n);case`status`:return this.status();case`managed-dev-status`:return this.managedDevStatus();case`managed-dev-checkout-changed`:{let t=this.leases.get(q(n.leaseId));t?.connection===e&&t.resource===`managed-dev`&&this.managedDev?.session.notifyCheckoutChanged?.();return}case`managed-dev-checkout-update-ready`:{let t=q(n.leaseId);this.leases.get(t)?.connection===e&&this.checkoutUpdate?.id===n.id&&this.releaseCheckoutUpdateParticipant(t);return}case`managed-dev-reset-idle`:return this.withResourceOperation(`managed-dev`,async()=>!this.managedDev||this.managedDev.leases.size>0?{reset:!1}:(await this.stopManagedDev(),{reset:!0}));case`managed-dev-action`:return this.managedDevAction(e,n);case`subscribe`:return this.addSubscription(e,le(n.resources));case`acquire`:return this.withResourceOperation(G(n.resource),()=>this.acquire(e,n));case`release`:await this.releaseLease(q(n.leaseId));return;case`renew`:return this.renewLease(q(n.leaseId));case`shutdown`:this.handoffVersion=q(n.implementationVersion)||void 0,this.shutdownRequested=!0,setImmediate(()=>void this.shutdown({stopPostgres:!1}));return;case`retire-if-idle`:return this.retireIfIdle(q(n.implementationVersion)||void 0);default:throw Q(`INVALID_REQUEST`,`Unknown supervisor method: ${t}.`,!1)}}retireIfIdle(e){let t=new Set(this.resourceOperations.keys());for(let n of this.leases.values())(n.resource!==`managed-dev`||!e||!n.followsHandoff||!this.managedDev?.session.prepareHandoff)&&t.add(n.resource);if(t.size>0)throw Q(`SUPERVISOR_BUSY`,`Waiting for these resources to finish or release their leases: ${[...t].join(`, `)}.`,!0);if(this.managedDev?.session.prepareHandoff?.()===!1)throw Q(`SUPERVISOR_BUSY`,`Waiting for managed development work to finish.`,!0);this.handoffVersion=e,this.shutdownRequested=!0,setImmediate(()=>void this.shutdown())}async withResourceOperation(e,t){let n=this.resourceOperations.get(e),r,i=new Promise(e=>{r=e});this.resourceOperations.set(e,i),n&&await n;try{return await t()}finally{r(),this.resourceOperations.get(e)===i&&this.resourceOperations.delete(e)}}hello(e,t){if(t.protocol!==1||t.token!==this.state.token)throw e.close(),Q(`AUTH_FAILED`,`Invalid supervisor protocol or token.`,!1);return e.authenticated=!0,{cwd:this.state.cwd,protocol:1,supervisorId:this.state.supervisorId}}status(){return{managedDev:this.managedDev?{leases:this.managedDev.leases.size,state:`running`}:void 0,postgres:this.postgres?{leases:this.postgres.leases.size,state:`running`}:void 0,sqlite:this.sqlite?{leases:this.sqlite.leases.size,state:`running`}:void 0}}async acquire(e,t){let n=G(t.resource);if(n===`managed-dev`)return this.acquireManagedDev(e,K(t));if(n===`postgres`)return this.acquirePostgres(e,K(t));if(n===`sqlite`)return this.acquireSqlite(e,K(t));if(n===`project-services`)return this.acquireProjectServices(e,t);throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${n}.`,!1)}async acquireProjectServices(e,t){let n=await o({cwd:this.state.cwd,env:J(t.env),services:t.services,onFailure:t=>{this.publish({event:`service`,resource:`project-services`,state:`failed`,error:t},e)}});if(e.closed||this.shutdownRequested)throw await n.close(),Error(`The development session ended before its service endpoints were ready.`);let r=this.createLease(e,`project-services`);return this.projectServices.set(r.id,n),{bindings:n.bindings,endpoints:n.endpoints,leaseId:r.id}}async acquireManagedDev(t,n){if(!this.startManagedDev)throw Error(`A managed development starter is required to run managed development.`);if(this.diagnostics??=new e(this.state.cwd,`supervisor`),this.diagnostics.event(`supervisor.attached`,{supervisorId:this.state.supervisorId,reused:!!this.managedDev}),this.managedDev){this.cancelManagedDevStop();let e=this.createLease(t,`managed-dev`,n.followsHandoff===!0);return e.holdsCheckoutUpdates=n.holdsCheckoutUpdates===!0,this.managedDev.leases.add(e.id),{leaseId:e.id,state:`reused`,status:this.managedDev.session.getStatus()}}let r=J(n.env),i=await this.startManagedDev({cwd:this.state.cwd,env:Y(r),onCheckoutUpdate:e=>this.waitForCheckoutUpdate(e),onRestart:()=>{this.diagnostics?.event(`restart.requested`,{supervisorId:this.state.supervisorId}),this.publish({event:`managed-dev`,kind:`restart`,resource:`managed-dev`})},onStatusChange:e=>{this.publish({event:`managed-dev`,kind:`status`,resource:`managed-dev`,status:e})}}),a={leases:new Set,session:i};this.managedDev=a;try{await i.activate()}catch(e){throw this.managedDev=void 0,await i.close(),e}let o=this.createLease(t,`managed-dev`,n.followsHandoff===!0);return o.holdsCheckoutUpdates=n.holdsCheckoutUpdates===!0,a.leases.add(o.id),{leaseId:o.id,state:`started`,status:i.getStatus()}}managedDevStatus(){if(!this.managedDev)throw Error(`Managed development is not active.`);return{status:this.managedDev.session.getStatus()}}async waitForCheckoutUpdate(e){let t=new Set([...this.leases.values()].filter(e=>e.holdsCheckoutUpdates&&!e.connection.closed).map(e=>e.id));if(t.size===0)return;let n,r=new Promise(e=>{n=e}),i={id:e,pending:t,complete:n},a=setTimeout(n,2e3);this.checkoutUpdate=i;try{await r,t.size>0&&this.diagnostics?.event(`checkout-update.ack-timeout`,{id:e,pending:t.size},`warn`)}finally{clearTimeout(a),this.checkoutUpdate===i&&(this.checkoutUpdate=void 0)}}releaseCheckoutUpdateParticipant(e){let t=this.checkoutUpdate;t?.pending.delete(e)&&t.pending.size===0&&t.complete()}async managedDevAction(e,t){if(!this.managedDev)throw Error(`Managed development is not active.`);let n=q(t.requestId);if(!n)throw Q(`INVALID_REQUEST`,`A managed development action request ID is required.`,!1);try{let r=q(t.operationId)||n;return await this.diagnostics.run({operationId:r,supervisorId:this.state.supervisorId,supervisorRequestId:n},()=>i(`supervisor.action`,()=>this.managedDev.session.action(t.action,{operationId:r,requestKey:q(t.requestKey)||void 0,onCodexEvent:t=>{this.publish({codex:t,event:`managed-dev`,kind:`codex`,requestId:n,resource:`managed-dev`},e)}})))}catch(e){return{error:e instanceof Error?e.message:String(e),status:this.managedDev.session.getStatus()}}}async acquirePostgres(e,t){let n=this.postgres===void 0;if(this.postgres)this.cancelPostgresStop();else{let e=await this.createLogStream(`postgres`),n=J(t.env),r=await this.startPostgres({config:t.config,cwd:this.state.cwd,env:Y(n),failIfRunning:!1,postgresOutput:e});this.postgres={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`postgres`,state:`running`})}let r=this.createLease(e,`postgres`);return this.postgres.leases.add(r.id),{env:Y(this.postgres.env),leaseId:r.id,state:n?`started`:`reused`}}async acquireSqlite(e,t){if(!this.startSqlite)throw Error(`A SQLite starter is required to run the development supervisor.`);let n=this.sqlite===void 0;if(this.sqlite)this.cancelSqliteStop();else{let e=await this.createLogStream(`sqlite`),n=J(t.env),r=await this.startSqlite({config:t.config,cwd:this.state.cwd,env:Y(n),tursoOutput:e});this.sqlite={env:X(n,r.env),leases:new Set,sidecar:r},this.publish({event:`service`,resource:`sqlite`,state:`running`})}let r=this.createLease(e,`sqlite`);return this.sqlite.leases.add(r.id),{env:Y(this.sqlite.env),leaseId:r.id,state:n?`started`:`reused`}}createLease(e,t,n){let r={connection:e,expiresAt:Date.now()+D,id:l(),resource:t,followsHandoff:n};return this.leases.set(r.id,r),t===`managed-dev`&&this.diagnostics?.event(`lease.acquired`,{leaseId:r.id,supervisorId:this.state.supervisorId}),r}renewLease(e){let t=this.leases.get(e);if(!t)throw this.diagnostics?.event(`lease.renewal-rejected`,{leaseId:e},`warn`),Q(`LEASE_EXPIRED`,`The supervisor lease is no longer active.`,!0);return t.expiresAt=Date.now()+D,{expiresAt:t.expiresAt}}expireLeases(){let e=Date.now(),t=e-this.lastLeaseSweepAt;if(this.lastLeaseSweepAt=e,t>=1e4){this.diagnostics?.event(`supervisor.resumed`,{sweepDelayMs:t});for(let t of this.leases.values())t.expiresAt=Math.max(t.expiresAt,e+D);return}for(let t of this.leases.values())t.expiresAt<=e&&(t.resource===`managed-dev`&&this.diagnostics?.event(`lease.expired`,{leaseId:t.id,overdueMs:e-t.expiresAt},`warn`),this.releaseLease(t.id))}async releaseLease(e){let t=this.leases.get(e);t&&(this.leases.delete(e),this.releaseCheckoutUpdateParticipant(e),t.resource===`postgres`?(this.postgres?.leases.delete(e),this.postgres?.leases.size===0&&this.schedulePostgresStop()):t.resource===`sqlite`?(this.sqlite?.leases.delete(e),this.sqlite?.leases.size===0&&this.scheduleSqliteStop()):t.resource===`project-services`?await this.withResourceOperation(`project-services`,async()=>{let t=this.projectServices.get(e);this.projectServices.delete(e),await t?.close()}):t.resource===`managed-dev`&&(this.managedDev?.leases.delete(e),this.diagnostics?.event(`lease.released`,{leaseId:e,remainingLeases:this.managedDev?.leases.size}),this.managedDev?.leases.size===0&&this.scheduleManagedDevStop()),this.maybeScheduleIdleShutdown())}async stopPostgres(){if(this.cancelPostgresStop(),!this.postgres)return;let e=this.postgres;this.postgres=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`postgres`,state:`stopped`})}schedulePostgresStop(){this.postgresStopTimer||(this.postgresStopTimer=setTimeout(()=>{this.postgresStopTimer=void 0,this.withResourceOperation(`postgres`,async()=>{this.postgres?.leases.size===0&&await this.stopPostgres()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.postgresStopTimer.unref())}async stopSqlite(){if(this.cancelSqliteStop(),!this.sqlite)return;let e=this.sqlite;this.sqlite=void 0,await e.sidecar[Symbol.asyncDispose](),this.publish({event:`service`,resource:`sqlite`,state:`stopped`})}async stopManagedDev(){if(this.cancelManagedDevStop(),!this.managedDev)return;let e=this.managedDev;this.diagnostics?.event(`session.stopping`,{supervisorId:this.state.supervisorId}),await e.session.close(),this.managedDev=void 0}scheduleSqliteStop(){this.sqliteStopTimer||(this.sqliteStopTimer=setTimeout(()=>{this.sqliteStopTimer=void 0,this.withResourceOperation(`sqlite`,async()=>{this.sqlite?.leases.size===0&&await this.stopSqlite()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e5),this.sqliteStopTimer.unref())}cancelPostgresStop(){this.postgresStopTimer&&=(clearTimeout(this.postgresStopTimer),void 0)}cancelSqliteStop(){this.sqliteStopTimer&&=(clearTimeout(this.sqliteStopTimer),void 0)}scheduleManagedDevStop(){this.managedDevStopTimer||(this.managedDevStopTimer=setTimeout(()=>{this.managedDevStopTimer=void 0,this.withResourceOperation(`managed-dev`,async()=>{this.managedDev?.leases.size===0&&await this.stopManagedDev()}).then(()=>this.maybeScheduleIdleShutdown(),()=>this.maybeScheduleIdleShutdown())},3e4),this.managedDevStopTimer.unref())}cancelManagedDevStop(){this.managedDevStopTimer&&=(clearTimeout(this.managedDevStopTimer),void 0)}async createLogStream(e){let t=y.join(this.root,w,`${e.replaceAll(`:`,`-`)}.log`);await f(y.dirname(t),{recursive:!0,mode:448}),await _(t,``);let n=0;return new re({write:(r,i,a)=>{let o=String(r),s=Buffer.from(o),c=s.subarray(Math.max(0,s.length-T)),l=n+c.length>T;(l?_(t,c):d(t,c)).then(()=>{n=l?c.length:n+c.length,a()},a),this.publish({event:`log`,resource:e,stream:`stdout`,data:o})}})}maybeScheduleIdleShutdown(){this.leases.size>0||this.postgres||this.sqlite||this.managedDev||this.idleTimer||(this.idleTimer=setTimeout(()=>{this.idleTimer=void 0,this.leases.size===0&&!this.postgres&&!this.sqlite&&!this.managedDev&&this.shutdown()},3e4),this.idleTimer.unref())}},se=class{authenticated=!1;decoder=new N;subscriptions=new Set;eventQueue=[];queuedEventBytes=0;writingEvent=!1;droppedEventRange;server;socket;constructor(e,t){this.server=e,this.socket=t,t.on(`error`,()=>this.close()),t.on(`data`,t=>{try{for(let n of this.decoder.push(t))n.type===`request`&&(!this.authenticated&&n.method!==`hello`?this.respond(n.id,{ok:!1,error:$(Q(`AUTH_FAILED`,`Send hello first.`,!1))}):e.handleRequest(this,n))}catch{this.close()}})}get closed(){return this.socket.destroyed||this.socket.readableEnded}respond(e,t){this.socket.write(P({...t,id:e,type:`response`}))}publish(e){let t=[...this.subscriptions];t.length!==0&&(e.event!==`replay-complete`&&e.event!==`gap`&&(e.resource===void 0||!t.some(t=>t.has(e.resource)))||this.enqueueEvent(e))}subscribe(e){this.subscriptions.add(new Set(e))}close(e){this.eventQueue.length=0,this.queuedEventBytes=0,e?this.socket.end(P({event:e,type:`event`})):this.socket.destroy()}enqueueEvent(e){let t=P({event:e,type:`event`});if(t.length>E){this.noteDropped(e);return}for(;;){let n=this.droppedEventRange?{event:{event:`gap`,from:this.droppedEventRange.from,reason:`buffer-overflow`,to:this.droppedEventRange.to,sequence:e.sequence,timestamp:new Date().toISOString()},frame:Buffer.alloc(0)}:void 0;n&&(n.frame=P({event:n.event,type:`event`}));let r=t.length+(n?.frame.length??0),i=!1;for(;this.queuedEventBytes+r>E;){let e=this.eventQueue.shift();if(!e)break;i=!0,this.queuedEventBytes-=e.frame.length,this.noteDropped(e.event)}if(!i){if(this.queuedEventBytes+r<=E){n&&(this.eventQueue.push(n),this.queuedEventBytes+=n.frame.length,this.droppedEventRange=void 0),this.eventQueue.push({event:e,frame:t}),this.queuedEventBytes+=t.length,this.pumpEvents();return}if(this.eventQueue.length===0){this.noteDropped(e);return}}}}noteDropped(e){let t=e.sequence;if(!this.droppedEventRange){this.droppedEventRange={from:t,to:t};return}this.droppedEventRange.from=Math.min(this.droppedEventRange.from,t),this.droppedEventRange.to=Math.max(this.droppedEventRange.to,t)}pumpEvents(){if(this.writingEvent||this.eventQueue.length===0||this.socket.destroyed)return;let e=this.eventQueue.shift();this.queuedEventBytes-=e.frame.length,this.writingEvent=!0,this.socket.write(e.frame,()=>{this.writingEvent=!1,this.pumpEvents()})}},N=class{buffer=Buffer.alloc(0);push(e){this.buffer=Buffer.concat([this.buffer,Buffer.from(e)]);let t=[];for(;this.buffer.length>=4;){let e=this.buffer.readUInt32BE(0);if(e>16777216)throw Error(`Development supervisor protocol frame is too large.`);if(this.buffer.length<e+4)break;let n=this.buffer.subarray(4,e+4).toString(`utf8`);this.buffer=this.buffer.subarray(e+4),t.push(JSON.parse(n))}return t}};function P(e){let t=Buffer.from(JSON.stringify(e),`utf8`),n=Buffer.allocUnsafe(t.length+4);return n.writeUInt32BE(t.length,0),t.copy(n,4),n}async function F(e){let t=await new Promise((t,n)=>{let r=te(e.state.endpoint);r.once(`connect`,()=>t(r)),r.once(`error`,n)});return A.create({...e,socket:t})}async function ce({cwd:e,env:t,entry:n}){s(b.execPath,[n,`--cwd`,e],{cwd:e,detached:!0,env:{...t,COREFRAME_DEV_SUPERVISOR:`1`},stdio:`ignore`}).unref()}async function I(e,t=!0){let n=y.join(e,x),r=y.join(n,C),i=Date.now()+1e4;for(await f(n,{recursive:!0,mode:448});Date.now()<i;)try{return await _(r,`${b.pid}\n`,{flag:`wx`,mode:384}),async()=>{await g(r).catch(()=>void 0)}}catch(n){if(!(n instanceof Error&&n.code===`EEXIST`))throw n;let i=await z(e);if(t&&i&&Z(i.pid))return;try{let e=await h(r);if(Date.now()-e.mtimeMs>1e4){await g(r).catch(()=>void 0);continue}}catch{continue}await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor startup is already in progress.`)}async function L(e){let t=Date.now()+1e4;for(;Date.now()<t;){let t=await z(e);if(t&&Z(t.pid))return t;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not start within 10 seconds.`)}async function R(e,t){let n=Date.now()+1e4;for(;Date.now()<n;){let n=await z(e);if(!n||n.supervisorId!==t)return;await new Promise(e=>setTimeout(e,25))}throw Error(`Coreframe development supervisor did not stop within 10 seconds.`)}async function z(e){try{let t=JSON.parse(await p(y.join(e,x,S),`utf8`)),n=t.availableResources===void 0?[`postgres`]:Array.isArray(t.availableResources)&&t.availableResources.every(B)?t.availableResources:void 0;return!n||t.protocol!==1||typeof t.cwd!=`string`||typeof t.endpoint!=`string`||typeof t.pid!=`number`||!Number.isSafeInteger(t.pid)||t.pid<=0||typeof t.supervisorId!=`string`||t.implementationVersion!==void 0&&typeof t.implementationVersion!=`string`||typeof t.token!=`string`?void 0:(t.projectServices===!0&&!n.includes(`project-services`)&&n.push(`project-services`),{...t,availableResources:n})}catch{return}}function B(e){return e===`managed-dev`||e===`postgres`||e===`sqlite`||e===`project-services`}function V(e,t){return t.every(t=>e.availableResources.includes(t))}async function H(e,t){let n=y.join(t,S),r=`${n}.${l()}.tmp`;await f(y.dirname(n),{recursive:!0,mode:448});try{let t={...e,availableResources:e.availableResources.filter(e=>e!==`project-services`),projectServices:e.availableResources.includes(`project-services`)};await _(r,`${JSON.stringify(t)}\n`,{flag:`wx`,mode:384}),await m(r,n)}finally{await g(r).catch(()=>void 0)}}async function U(e,t){t&&t.cwd!==y.resolve(e)||(await ee(y.join(e,x,S),{force:!0}),t&&b.platform!==`win32`&&await g(t.endpoint).catch(()=>void 0))}function W(e){if(b.platform===`win32`)return`\\\\.\\pipe\\coreframe-dev-${c(`sha256`).update(y.resolve(e)).digest(`hex`).slice(0,24)}`;let t=c(`sha256`).update(y.resolve(e)).digest(`hex`).slice(0,24);return y.join(v(),`coreframe-dev-${t}-supervisor.sock`)}function le(e){return Array.isArray(e)?e.map(G):[`managed-dev`,`postgres`,`sqlite`,`project-services`]}function G(e){if(B(e))return e;throw Q(`INVALID_REQUEST`,`Unknown supervisor resource: ${String(e)}.`,!1)}function K(e){return e&&typeof e==`object`?e:{}}function q(e){return typeof e==`string`?e:String(e??``)}function J(e){let t=K(e);return Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]==`string`))}function Y(e){return Object.fromEntries(Object.entries(e).filter(e=>e[1]!==void 0))}function X(e,t){return Object.fromEntries(Object.entries(t).filter(t=>{let[n,r]=t;return r!==void 0&&e[n]!==r}))}function Z(e){try{return b.kill(e,0),!0}catch(e){return e instanceof Error&&e.code===`EPERM`}}function Q(e,t,n,r){return Object.assign(Error(t),{code:e,details:r,retryable:n})}function $(e){if(e&&typeof e==`object`){let t=e;return{code:t.code??`SUPERVISOR_ERROR`,details:t.details,message:t.message??String(e),retryable:t.retryable??!1}}return{code:`SUPERVISOR_ERROR`,message:String(e),retryable:!1}}function ue(e){let t=Error(e?.message??`Development supervisor request failed.`);return t.code=e?.code,t.details=e?.details,t.retryable=e?.retryable,t}export{e as DevDiagnostics,A as DevSupervisorClient,O as connectDevSupervisor,k as connectExistingDevSupervisor,a as createLazyTcpProxy,t as devDiagnosticContext,n as devDiagnosticError,r as devDiagnosticEvent,i as devDiagnosticPhase,ae as devSupervisorVersion,j as runDevSupervisorProcess,oe as stopDevSupervisor};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coreframe/dev-supervisor",
3
- "version": "0.2.5",
3
+ "version": "0.2.6",
4
4
  "description": "Process supervision utilities for Coreframe development workflows",
5
5
  "repository": {
6
6
  "type": "git",