@tomflow/chatloop-tools 0.9.26 → 0.9.27

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.
@@ -1,7 +1,9 @@
1
1
  // Supervisor cutover lifecycle. All package/runtime helpers arrive as
2
2
  // explicit ports from the SDK composition root; this module owns no state.
3
3
  import {randomUUID} from 'node:crypto';
4
+ import {spawn} from 'node:child_process';
4
5
  import {existsSync,mkdirSync,openSync,closeSync,unlinkSync,lstatSync,readFileSync,writeFileSync} from 'node:fs';
6
+ import {homedir} from 'node:os';
5
7
  import {join,dirname} from 'node:path';
6
8
  let PACKAGE_VERSION,CONTRACT,lifecycleDeadlineMs,talkForUpgrade,
7
9
  activeDesktopCommands,awaitStopped,checkedUpgradeBase,upgradeLayout,
@@ -59,6 +61,100 @@ function backupConfiguration(p){
59
61
  return directory;
60
62
  }
61
63
 
64
+ async function verifyTunnelConnection(p,verified){
65
+ if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return {result:'ok',testOnly:true};
66
+ const tunnel=verified.results?.find(x=>x.toolId==='tunnel');
67
+ const platform=process.platform+'-'+process.arch;
68
+ const binary=join(dirname(dirname(p.entry)),'node_modules','@tomflow',
69
+ 'chatloop-tunnel-'+platform,'bin','tunnel-client');
70
+ const healthFile=join(homedir(),'Library','Application Support',
71
+ 'tunnel-client','health','chat-loop.url');
72
+ if(!Number.isSafeInteger(tunnel?.pid)||!existsSync(binary)||!existsSync(healthFile))
73
+ throw Object.assign(Error('NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'),{
74
+ code:'NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'});
75
+ let last;
76
+ for(let attempt=0;attempt<30;attempt++){
77
+ try{
78
+ const output=await run(binary,['health','--url-file',healthFile,
79
+ '--pid',String(tunnel.pid),'--require-control-plane-poll','--json'],
80
+ {env:runtimeLaunchEnv()});
81
+ const result=JSON.parse(output.trim());
82
+ if(result.result==='ok'&&result.healthz?.ok===true
83
+ &&result.readyz?.ok===true&&result.control_plane_poll?.ok===true)
84
+ return {result:'ok',pid:tunnel.pid,controlPlanePoll:true};
85
+ last=result;
86
+ }catch(error){last={code:error.code||'TUNNEL_HEALTH_FAILED'};}
87
+ await new Promise(resolve=>setTimeout(resolve,500));
88
+ }
89
+ throw Object.assign(Error('NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY'),{
90
+ code:'NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY',tunnelStatus:last});
91
+ }
92
+
93
+ async function verifyMcpTools(p){
94
+ if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return {ok:true,testOnly:true};
95
+ const child=spawn(process.execPath,[p.entry,'mcp'],{
96
+ env:{...runtimeLaunchEnv(),CHAT_LOOP_API_LOG_STDERR:'0'},
97
+ stdio:['pipe','pipe','pipe'],windowsHide:true
98
+ });
99
+ let buffer='',stderr='',nextId=0;
100
+ const waiting=new Map();
101
+ const rejectPending=error=>{
102
+ for(const pending of waiting.values()){
103
+ clearTimeout(pending.timer);pending.reject(error);
104
+ }
105
+ waiting.clear();
106
+ };
107
+ child.stdout.setEncoding('utf8');
108
+ child.stderr.setEncoding('utf8');
109
+ child.stdout.on('data',chunk=>{
110
+ buffer+=chunk;
111
+ let end;
112
+ while((end=buffer.indexOf('\n'))>=0){
113
+ const line=buffer.slice(0,end);buffer=buffer.slice(end+1);
114
+ let packet;try{packet=JSON.parse(line)}catch{continue;}
115
+ const pending=waiting.get(packet.id);
116
+ if(pending){waiting.delete(packet.id);clearTimeout(pending.timer);pending.resolve(packet);}
117
+ }
118
+ });
119
+ child.stderr.on('data',chunk=>{stderr=(stderr+chunk).slice(-2048)});
120
+ child.once('error',error=>rejectPending(error));
121
+ child.once('exit',code=>rejectPending(Error('MCP_PROBE_EXIT:'+code+':'+stderr.slice(-500))));
122
+ const request=(method,params={})=>new Promise((resolve,reject)=>{
123
+ const id=++nextId;
124
+ const timer=setTimeout(()=>{waiting.delete(id);reject(Error('MCP_PROBE_TIMEOUT:'+method))},8000);
125
+ waiting.set(id,{resolve,reject,timer});
126
+ child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');
127
+ });
128
+ try{
129
+ const init=await request('initialize',{protocolVersion:'2025-11-25',
130
+ capabilities:{},clientInfo:{name:'chat-loop-upgrade-probe',version:p.version}});
131
+ if(init.result?.serverInfo?.version!==p.version)
132
+ throw Object.assign(Error('MCP_PROBE_VERSION_MISMATCH'),{
133
+ code:'MCP_PROBE_VERSION_MISMATCH'});
134
+ child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');
135
+ const listed=await request('tools/list');
136
+ const names=listed.result?.tools?.map(x=>x.name)||[];
137
+ for(const name of ['chat_loop_form__prepare','chat_loop_form__render',
138
+ 'chat_loop_form__submit'])
139
+ if(!names.includes(name))throw Object.assign(Error('MCP_PROBE_REQUIRED_TOOL_MISSING'),{
140
+ code:'MCP_PROBE_REQUIRED_TOOL_MISSING'});
141
+ const resources=await request('resources/list');
142
+ const uri=resources.result?.resources?.find(x=>x.uri==='ui://chat-loop/form/v3')?.uri;
143
+ if(!uri)throw Object.assign(Error('MCP_PROBE_FORM_RESOURCE_MISSING'),{
144
+ code:'MCP_PROBE_FORM_RESOURCE_MISSING'});
145
+ const view=await request('resources/read',{uri});
146
+ const html=view.result?.contents?.[0]?.text||'';
147
+ if(!html.includes('chat_loop_form__render'))
148
+ throw Object.assign(Error('MCP_PROBE_FORM_APP_OUTDATED'),{
149
+ code:'MCP_PROBE_FORM_APP_OUTDATED'});
150
+ return {ok:true,toolCount:names.length,formResource:uri};
151
+ }finally{
152
+ try{child.stdin.end();child.kill('SIGTERM')}catch{}
153
+ await Promise.race([new Promise(resolve=>child.once('exit',resolve)),
154
+ new Promise(resolve=>setTimeout(resolve,1000))]);
155
+ }
156
+ }
157
+
62
158
  export async function upgradeRuntime(options={}){
63
159
  if(options.args?.length)return freshResult('FAILED',{code:'INVALID_ARGUMENT'});
64
160
  const base=checkedUpgradeBase(options);
@@ -176,28 +272,44 @@ export async function upgradeRuntime(options={}){
176
272
  });
177
273
  if(!verified){
178
274
  phase='start-new';
179
- const started=await cli(p.entry,'start',{
180
- env:{...runtimeLaunchEnv(),CHAT_LOOP_SKIP_UPGRADE:'1'}
181
- });
182
- if(!['OK','STARTING'].includes(started.status))
275
+ const startEnv={...runtimeLaunchEnv(),CHAT_LOOP_SKIP_UPGRADE:'1'};
276
+ const startupResult=await cli(p.entry,'start',{env:startEnv});
277
+ if(!['OK','STARTING'].includes(startupResult.status)
278
+ &&startupResult.error?.code!=='MANAGER_UNAVAILABLE')
183
279
  throw Object.assign(Error('NEW_RUNTIME_UNHEALTHY'),{
184
- code:'NEW_RUNTIME_UNHEALTHY',startupResult:started
280
+ code:'NEW_RUNTIME_UNHEALTHY',startupResult
185
281
  });
186
- // A successful start acknowledgement is not readiness. Wait for the
187
- // candidate Supervisor and every enabled child to become observable.
282
+ // Supervisor startup can outlive the first CLI IPC probe. A temporary
283
+ // MANAGER_UNAVAILABLE is not a failed cutover: observe the candidate,
284
+ // then issue one idempotent start retry only after its own manager is live.
188
285
  phase='verify-new';
189
- for(let attempt=0;attempt<30;attempt++){
190
- const status=await cli(p.entry,'status');
191
- const running=status.results?.filter(x=>x.enabled)||[];
192
- if(status.status==='OK'&&running.length>0&&
286
+ let lastStatus=null,startRetried=false;
287
+ for(let attempt=0;attempt<60;attempt++){
288
+ try{lastStatus=await cli(p.entry,'status');}
289
+ catch(error){lastStatus={status:'UNAVAILABLE',code:error.code||'MANAGER_UNAVAILABLE'};}
290
+ const running=lastStatus.results?.filter(x=>x.enabled)||[];
291
+ const managerReady=Number.isSafeInteger(lastStatus.managerPid);
292
+ if(lastStatus.status==='OK'&&managerReady&&running.length>0&&
193
293
  running.every(x=>x.after==='RUNNING')){
194
- verified=status;break;
294
+ verified=lastStatus;break;
295
+ }
296
+ if(lastStatus.status==='OK'&&managerReady&&running.length>0&&
297
+ running.every(x=>x.after==='STOPPED')&&!startRetried){
298
+ startRetried=true;
299
+ const retry=await cli(p.entry,'start',{env:startEnv});
300
+ if(!['OK','STARTING'].includes(retry.status)
301
+ &&retry.error?.code!=='MANAGER_UNAVAILABLE')
302
+ throw Object.assign(Error('NEW_RUNTIME_RETRY_START_FAILED'),{
303
+ code:'NEW_RUNTIME_RETRY_START_FAILED',startupResult:retry,
304
+ candidateStatus:lastStatus
305
+ });
195
306
  }
196
307
  await new Promise(resolve=>setTimeout(resolve,500));
197
308
  }
198
309
  if(!verified)
199
310
  throw Object.assign(Error('NEW_RUNTIME_HEALTHCHECK_TIMEOUT'),{
200
- code:'NEW_RUNTIME_HEALTHCHECK_TIMEOUT'
311
+ code:'NEW_RUNTIME_HEALTHCHECK_TIMEOUT',startupResult,
312
+ candidateStatus:lastStatus
201
313
  });
202
314
  }
203
315
  phase='verify-tunnel';
@@ -206,11 +318,16 @@ export async function upgradeRuntime(options={}){
206
318
  throw Object.assign(Error('NEW_RUNTIME_TUNNEL_UNHEALTHY'),{
207
319
  code:'NEW_RUNTIME_TUNNEL_UNHEALTHY'
208
320
  });
321
+ phase='verify-tunnel-connection';
322
+ const tunnelConnection=await verifyTunnelConnection(p,verified);
323
+ phase='verify-mcp';
324
+ const mcp=await verifyMcpTools(p);
209
325
  phase='record-new';
210
326
  atomicWrite(p.current,JSON.stringify({version:p.version,entry:p.entry,
211
327
  status:'ACTIVE'},null,2)+'\n');
212
328
  return freshResult('OK',{outcome:'ACTIVATED',managerPid:verified.managerPid,
213
- healthyTools:verified.results.filter(x=>x.enabled).map(x=>x.toolId),backupDir});
329
+ healthyTools:verified.results.filter(x=>x.enabled).map(x=>x.toolId),
330
+ tunnelConnection,mcp,backupDir});
214
331
  }catch(e){
215
332
  // Never restore or launch a superseded runtime after a failed cutover.
216
333
  if(oldWasStopped&&runtime){
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.26",
6
+ "version": "0.9.27",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {