webhelm 1.0.42 → 1.0.43

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/README.md CHANGED
@@ -33,7 +33,38 @@ npx --yes webhelm@latest session stop SESSION_ID
33
33
  # Long-running worker managers: session heartbeat SESSION_ID every 60 seconds
34
34
  ```
35
35
 
36
- Use `npx skills add lalalic/webhelm --skill webhelm` to install agent guidance. The Extension is bundled with the npm Runtime and staged by WebHelm Daemon at `~/.local/webhelm/extension`. The Skill lives **in this repo** at `skills/webhelm/SKILL.md`. No Chrome Web Store publication or manual Extension installation is required.
36
+ Use `npx skills add lalalic/webhelm --skill webhelm` to install agent guidance.
37
+ The Extension is bundled with the npm Runtime and staged by WebHelm Daemon at `~/.local/webhelm/extension`. The Skill lives **in this repo** at `skills/webhelm/SKILL.md`. No Chrome Web Store publication or manual Extension installation is required.
38
+
39
+ ### Automatic npm Runtime upgrades (macOS)
40
+
41
+ `webhelm setup` installs two independent LaunchAgents: the offline Chrome health
42
+ check (`com.lalalic.webhelm.keepalive`, every 30 seconds) and the npm Runtime
43
+ updater (`com.lalalic.webhelm.runtime-update`, every hour and at login).
44
+ The updater checks the npm registry and downloads new releases to a temporary
45
+ location without running npm lifecycle scripts. It validates that Runtime and
46
+ Extension versions match, stages an immutable copy under
47
+ `~/.local/share/webhelm/runtime-VERSION`, and uses the stable
48
+ `~/.local/share/webhelm/runtime-current` symlink for subsequent launches.
49
+ The scheduled job does not depend on the npx cache. For immediate checking use
50
+ `webhelm upgrade`; for a read-only daemon check use `webhelm status`.
51
+
52
+ **No active Session is interrupted.** Before cutover, the daemon atomically
53
+ checks that no Sessions, pending leases, IPC operations or queue workers are
54
+ running, then pauses new browser work. New queued ChatGPT turns remain durable
55
+ and are accepted during the short cutover. The updater switches the stable
56
+ Runtime pointer, waits for the idle daemon to stop gracefully, starts the
57
+ new daemon against the existing Chrome/profile/queue, and verifies its version.
58
+ A busy daemon returns `deferred` and retries on the next scheduled run. A failed
59
+ installation reverts the pointer and resumes the old queue. Unavailable npm or
60
+ unrecognized old daemon upgrade protocols fail closed rather than killing a
61
+ Session. The update log is at `~/.config/webhelm/runtime/auto-update.log`.
62
+
63
+ Neo Master uses `WEBHELM_SOURCE_MODE=1` and runs its linked Git checkout, not
64
+ a published npm package. Automatic npm updates are deliberately disabled
65
+ there; updating a development checkout is a separate, reviewed Git operation.
66
+ Existing npm installations need to run `webhelm setup` once after receiving
67
+ this release to register the updater LaunchAgent.
37
68
 
38
69
  ## WebHelm Chrome Extension control panel
39
70
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webhelm",
3
- "version": "1.0.42",
3
+ "version": "1.0.43",
4
4
  "description": "Agent browser automation in a visible managed Chrome with persistent JavaScript sessions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,157 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import {execFileSync} from 'node:child_process';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {request} from './node-daemon.mjs';
7
+ import {activateRuntime,currentRuntimePath,installLoginGuard,installRuntimeUpdate,stageRuntimeForLoginGuard} from './login-guard.mjs';
8
+
9
+ const REGISTRY='https://registry.npmjs.org';
10
+ const SOURCE=fileURLToPath(new URL('../',import.meta.url));
11
+ const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
12
+
13
+ export function compareVersions(a,b) {
14
+ const parts=v=>{
15
+ if(typeof v!=='string'||!/^\d+\.\d+\.\d+$/.test(v))throw Error(`Invalid Runtime version: ${v}`);
16
+ return v.split('.').map(Number);
17
+ };
18
+ const x=parts(a),y=parts(b);
19
+ for(let i=0;i<3;i++)if(x[i]!==y[i])return Math.sign(x[i]-y[i]);
20
+ return 0;
21
+ }
22
+
23
+ export function npmLatest() {
24
+ const value=execFileSync('npm',['view','webhelm','version','--json',`--registry=${REGISTRY}`,'--fetch-retries=0','--fetch-timeout=8000'],
25
+ {encoding:'utf8',timeout:15000,stdio:['ignore','pipe','pipe']});
26
+ const version=JSON.parse(value);
27
+ compareVersions(version,version);
28
+ return version;
29
+ }
30
+
31
+ // npm installs into an isolated temporary prefix; lifecycle scripts never run.
32
+ // The existing offline staging contract (Runtime + yaml) remains unchanged.
33
+ export function downloadRuntime(version,{home=os.homedir()}={}) {
34
+ compareVersions(version,version);
35
+ const cached=path.join(home,'.local/share/webhelm',`runtime-${version}`);
36
+ try {
37
+ const pkg=JSON.parse(fs.readFileSync(path.join(cached,'package.json'),'utf8'));
38
+ const ext=JSON.parse(fs.readFileSync(path.join(cached,'runtime/extension/manifest.json'),'utf8'));
39
+ if(pkg.name==='webhelm' && pkg.version===version && ext.version===version &&
40
+ fs.existsSync(path.join(cached,'node_modules/yaml/package.json')) &&
41
+ fs.existsSync(path.join(cached,'runtime/auto-update.mjs')))
42
+ return {path:cached,version,updated:false};
43
+ }catch{}
44
+ const temp=fs.mkdtempSync(path.join(os.tmpdir(),'webhelm-npm-upgrade-'));
45
+ try {
46
+ execFileSync('npm',['install','--prefix',temp,'--no-save','--omit=dev','--ignore-scripts',
47
+ '--no-audit','--no-fund','--package-lock=false','--fetch-retries=0',
48
+ `--registry=${REGISTRY}`,`webhelm@${version}`],
49
+ {timeout:120000,stdio:['ignore','pipe','pipe']});
50
+ const source=path.join(temp,'node_modules/webhelm');
51
+ const manifest=JSON.parse(fs.readFileSync(path.join(source,'package.json'),'utf8'));
52
+ const extension=JSON.parse(fs.readFileSync(path.join(source,'runtime/extension/manifest.json'),'utf8'));
53
+ if(manifest.name!=='webhelm'||manifest.version!==version||extension.version!==version)
54
+ throw Error('npm Runtime/Extension version verification failed');
55
+ if(Object.keys(manifest.dependencies||{}).some(name=>name!=='yaml'))
56
+ throw Error('Runtime dependencies changed; offline staging requires a review');
57
+ return stageRuntimeForLoginGuard({home,source,yamlSource:path.join(temp,'node_modules/yaml')});
58
+ }finally{fs.rmSync(temp,{recursive:true,force:true});}
59
+ }
60
+
61
+ function acquireLock(home) {
62
+ const runtime=path.join(home,'.config/webhelm/runtime');
63
+ fs.mkdirSync(runtime,{recursive:true,mode:0o700});
64
+ const lock=path.join(runtime,'auto-upgrade.lock');
65
+ for(let i=0;i<2;i++){
66
+ try {
67
+ const fd=fs.openSync(lock,'wx',0o600);
68
+ fs.writeFileSync(fd,String(process.pid));fs.closeSync(fd);
69
+ return ()=>{if(fs.existsSync(lock)&&fs.readFileSync(lock,'utf8')===String(process.pid))fs.unlinkSync(lock);};
70
+ }catch(error){
71
+ if(error.code!=='EEXIST')throw error;
72
+ const owner=Number(fs.readFileSync(lock,'utf8'));
73
+ if(owner>0){try{process.kill(owner,0);return null;}catch(e){if(e.code==='EPERM')return null;}}
74
+ fs.unlinkSync(lock);
75
+ }
76
+ }
77
+ return null;
78
+ }
79
+
80
+ // Inject ports for isolated tests. Production never imports npm code or
81
+ // touches another Chrome profile to decide whether to upgrade.
82
+ export async function upgradeRuntime({home=os.homedir(),source=SOURCE,nodePath=process.execPath,
83
+ latest=npmLatest,download=downloadRuntime,ipc=req=>request(req,false),
84
+ installGuard=installLoginGuard,installPoller=installRuntimeUpdate,
85
+ activate=activateRuntime,verify=null,apply=true}={}) {
86
+ if(process.env.WEBHELM_SOURCE_MODE==='1')return {status:'source_checkout',upgraded:false};
87
+ const unlock=acquireLock(home);
88
+ if(!unlock)return {status:'already_running',upgraded:false};
89
+ let prepared=false,prior=null,switched=false,committed=false;
90
+ try {
91
+ const local=JSON.parse(fs.readFileSync(path.join(source,'package.json'),'utf8')).version;
92
+ const published=await latest();
93
+ const target=compareVersions(published,local)>0?published:local;
94
+ let daemon=null;
95
+ try{daemon=await ipc({op:'ping'});}catch{}
96
+ if(daemon?.version && compareVersions(daemon.version,target)>0)
97
+ return {status:'daemon_newer',upgraded:false,daemon_version:daemon.version,latest:published};
98
+ const current=currentRuntimePath(home);
99
+ const currentTarget=fs.existsSync(current)?fs.realpathSync(current):null;
100
+ const upToDate=daemon?.version===target && currentTarget &&
101
+ fs.existsSync(path.join(currentTarget,'package.json')) &&
102
+ JSON.parse(fs.readFileSync(path.join(currentTarget,'package.json'),'utf8')).version===target;
103
+ if(upToDate)return {status:'current',upgraded:false,version:target};
104
+ // Stage before requesting the daemon to drain; download may take time.
105
+ const staged=compareVersions(target,local)>0
106
+ ? await download(target,{home}) : stageRuntimeForLoginGuard({home,source});
107
+ if(daemon && compareVersions(daemon.version,target)<0){
108
+ let gate;
109
+ try{gate=await ipc({op:'upgrade-prepare'});}
110
+ catch(error){return {status:'deferred',upgraded:false,reason:'daemon_upgrade_protocol_unavailable',detail:error.message,latest:target};}
111
+ if(!gate?.ready)return {status:'deferred',upgraded:false,reason:gate?.reason||'daemon_busy',latest:target,session_count:gate?.session_count};
112
+ prepared=true;
113
+ }
114
+ prior=currentTarget;
115
+ activate(staged.path,{home});switched=true;
116
+ const cliPath=path.join(current,'bin/webhelm.mjs');
117
+ const guard=installGuard({home,cliPath,nodePath,apply});
118
+ const poller=installPoller({home,cliPath,nodePath,apply});
119
+ if(['staged_not_loaded','skipped'].includes(guard.status)||
120
+ ['staged_not_loaded','skipped'].includes(poller.status))throw Error('Runtime LaunchAgent activation failed');
121
+ if(prepared){
122
+ const result=await ipc({op:'upgrade-commit'});
123
+ if(!result?.stopping)throw Error('Daemon did not accept Runtime cutover');
124
+ prepared=false;committed=true;
125
+ // SIGTERM completes the daemon's lock/socket cleanup. Never kill Chrome.
126
+ for(let i=0;i<100;i++){
127
+ try{const ping=await ipc({op:'ping'});if(ping?.pid!==daemon.pid)break;}
128
+ catch{break;}
129
+ await sleep(100);
130
+ }
131
+ }
132
+ const run=verify||(()=>{
133
+ const result=execFileSync(nodePath,[cliPath,'status'],{encoding:'utf8',timeout:30000,stdio:['ignore','pipe','pipe']});
134
+ return JSON.parse(result.trim().split('\n').at(-1));
135
+ });
136
+ const state=await run();
137
+ if(state.version!==target)throw Error(`Cutover verification failed: ${state.version} !== ${target}`);
138
+ return {status:'upgraded',upgraded:true,from:daemon?.version||null,to:target,
139
+ daemon_pid:state.daemon?.pid||null,guard:guard.status,auto_update:poller.status};
140
+ }catch(error){
141
+ // Never point new clients at an old Runtime after a committed daemon
142
+ // cutover: the new daemon may already be serving requests.
143
+ if(switched && !committed){
144
+ try{
145
+ if(prior)activate(prior,{home});
146
+ else fs.unlinkSync(currentRuntimePath(home));
147
+ const cliPath=prior?path.join(currentRuntimePath(home),'bin/webhelm.mjs'):path.join(source,'bin/webhelm.mjs');
148
+ installGuard({home,cliPath,nodePath,apply});
149
+ installPoller({home,cliPath,nodePath,apply});
150
+ }catch(rollbackError){error.message+=`; rollback failed: ${rollbackError.message}`;}
151
+ }
152
+ throw error;
153
+ }finally{
154
+ if(prepared)await ipc({op:'upgrade-release'}).catch(()=>{});
155
+ unlock();
156
+ }
157
+ }
@@ -13,6 +13,7 @@ Commands:
13
13
  webhelm setup Set up managed Chrome and local Actions
14
14
  webhelm status Report browser and daemon status (JSON)
15
15
  webhelm ensure Check and recover managed Chrome health
16
+ webhelm upgrade Check npm and safely upgrade the Runtime
16
17
  webhelm capacity Report available browser capacity (JSON)
17
18
  webhelm session start [--url URL] Start a persistent browser Session
18
19
  webhelm session list List CLI-owned Sessions
@@ -55,6 +56,7 @@ Output: JSON with status, Actions checkout path, daemon and browser details.
55
56
 
56
57
  Example:
57
58
  webhelm setup`,
59
+ upgrade: `webhelm upgrade — update the npm Runtime when safely idle\n\nUsage:\n webhelm upgrade\n\nChecks npm once. Stages newer Runtime without executing install scripts.\nCutover waits until all Sessions and in-flight queue workers are idle;\notherwise reports deferred and retries on the next hourly LaunchAgent run.\nNever updates a source-mode checkout or restarts managed Chrome.\n\nOutput: JSON current, upgraded, deferred, or source_checkout.`,
58
60
  status: `webhelm status — inspect managed browser and daemon
59
61
 
60
62
  Usage:
package/runtime/cli.mjs CHANGED
@@ -7,7 +7,8 @@ import { randomUUID } from 'node:crypto';
7
7
  import { ensureDaemon, request, SOCKET } from './node-daemon.mjs';
8
8
  import { PLATFORMS, listPlatforms, platformProfile, actionPath, validateConfig } from './platforms.mjs';
9
9
  import { ACTIONS_DIR, ensureActions, syncActions, publishActions } from './actions-repo.mjs';
10
- import { installLoginGuard, stageRuntimeForLoginGuard } from './login-guard.mjs';
10
+ import { activateRuntime, currentRuntimePath, installLoginGuard, installRuntimeUpdate, stageRuntimeForLoginGuard } from './login-guard.mjs';
11
+ import { upgradeRuntime } from './auto-update.mjs';
11
12
  import { cliHelp } from './cli-help.mjs';
12
13
 
13
14
  const ROOT = path.dirname(fileURLToPath(import.meta.url));
@@ -108,12 +109,15 @@ async function main(args = process.argv.slice(2)) {
108
109
  const repo=await ensureActions();
109
110
  const chrome=await ensureDaemon();
110
111
  const sourceMode=process.env.WEBHELM_SOURCE_MODE==='1';
112
+ if(!sourceMode)activateRuntime(stageRuntimeForLoginGuard().path);
111
113
  const cliPath=sourceMode
112
114
  ? fileURLToPath(new URL('../bin/webhelm.mjs',import.meta.url))
113
- : path.join(stageRuntimeForLoginGuard().path,'bin/webhelm.mjs');
115
+ : path.join(currentRuntimePath(),'bin/webhelm.mjs');
114
116
  const login_guard=installLoginGuard({cliPath,nodePath:process.execPath,sourceMode});
115
- return emit({status:'ready',...repo,daemon_pid:chrome.pid,managed_chrome:chrome.managed_chrome,login_guard});
117
+ const auto_update=installRuntimeUpdate({cliPath,nodePath:process.execPath,sourceMode});
118
+ return emit({status:'ready',...repo,daemon_pid:chrome.pid,managed_chrome:chrome.managed_chrome,login_guard,auto_update});
116
119
  }
120
+ if (group === 'upgrade') return emit(await upgradeRuntime());
117
121
  if (group === 'ensure') {
118
122
  try { return emit(await request({op:'guard-check'})); }
119
123
  catch(error) {
@@ -130,7 +134,12 @@ async function main(args = process.argv.slice(2)) {
130
134
  }
131
135
  if (group === 'status') {
132
136
  const daemon = await ensureDaemon();
133
- return emit({version:daemon.version, platform_dir:PLATFORMS, root:ROOT,
137
+ const link=currentRuntimePath();
138
+ let installed_version=null;
139
+ try{installed_version=JSON.parse(fs.readFileSync(path.join(link,'package.json'),'utf8')).version;}catch{}
140
+ const auto_update_installed=fs.existsSync(path.join(os.homedir(),'Library/LaunchAgents/com.lalalic.webhelm.runtime-update.plist'));
141
+ return emit({version:daemon.version, installed_version, auto_update_installed,
142
+ source_mode:process.env.WEBHELM_SOURCE_MODE==='1',platform_dir:PLATFORMS, root:ROOT,
134
143
  cli:fileURLToPath(import.meta.url),
135
144
  admin_helper:process.env.WEBHELM_ADMIN_HELPER || (fs.existsSync(path.join(os.homedir(),'.agents/skills/webhelm/scripts/admin.mjs')) ? path.join(os.homedir(),'.agents/skills/webhelm/scripts/admin.mjs') : path.join(ROOT,'admin.mjs')),
136
145
  managed_chrome:daemon.managed_chrome, chrome_guard:daemon.chrome_guard,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "WebHelm",
4
- "version": "1.0.42",
4
+ "version": "1.0.43",
5
5
  "description": "Own named Chrome tab-group workspaces and lazy reusable tab pools for browser agents.",
6
6
  "permissions": [
7
7
  "storage",
@@ -5,6 +5,7 @@ import {execFileSync} from 'node:child_process';
5
5
  import {fileURLToPath} from 'node:url';
6
6
 
7
7
  const LABEL='com.lalalic.webhelm.keepalive';
8
+ const UPDATE_LABEL='com.lalalic.webhelm.runtime-update';
8
9
  // launchd must never depend on npm's removable npx cache, or on the Skill
9
10
  // launcher being present. Stage an immutable, package-backed runtime locally.
10
11
  export function stageRuntimeForLoginGuard({home=os.homedir(),source=fileURLToPath(new URL('../',import.meta.url)),yamlSource=null}={}){
@@ -79,3 +80,63 @@ export function installLoginGuard({home=os.homedir(), platform=process.platform,
79
80
  }catch(e){return {status:'staged_not_loaded',path:dest,label:LABEL,reason:e.message};}
80
81
  }
81
82
  }
83
+
84
+ // The npm poller is separate from the offline, 30-second Chrome health guard.
85
+ // It is pinned to a staged Runtime and never relies on a removable npx cache.
86
+ export function runtimeUpdateDefinition(home=os.homedir(),{cliPath,nodePath}={}) {
87
+ const cli=cliPath||path.join(home,'.local/bin/webhelm');
88
+ const node=nodePath||process.execPath;
89
+ const environment=[path.join(home,'.local/bin'),path.join(home,'.local/opt/node22/bin'),
90
+ '/opt/homebrew/bin','/usr/local/bin','/usr/bin','/bin'].join(':');
91
+ const log=path.join(home,'.config/webhelm/runtime/auto-update.log');
92
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${UPDATE_LABEL}</string>\n<key>ProgramArguments</key><array><string>${escapeXml(node)}</string><string>${escapeXml(cli)}</string><string>upgrade</string></array>\n<key>EnvironmentVariables</key><dict><key>PATH</key><string>${escapeXml(environment)}</string><key>HOME</key><string>${escapeXml(home)}</string></dict>\n<key>RunAtLoad</key><true/>\n<key>StartInterval</key><integer>3600</integer>\n<key>StandardOutPath</key><string>${escapeXml(log)}</string>\n<key>StandardErrorPath</key><string>${escapeXml(log)}</string>\n</dict></plist>\n`;
93
+ }
94
+
95
+ export function installRuntimeUpdate({home=os.homedir(),platform=process.platform,apply=true,cliPath,nodePath,sourceMode=false}={}) {
96
+ if(sourceMode)return {status:'disabled',reason:'source_checkout',label:UPDATE_LABEL};
97
+ if(platform!=='darwin')return {status:'unsupported',label:UPDATE_LABEL};
98
+ const cli=cliPath||path.join(home,'.local/bin/webhelm');
99
+ if(!fs.existsSync(cli))return {status:'skipped',reason:'WebHelm runtime launcher missing',label:UPDATE_LABEL};
100
+ const dest=path.join(home,'Library/LaunchAgents',`${UPDATE_LABEL}.plist`);
101
+ const content=runtimeUpdateDefinition(home,{cliPath:cli,nodePath});
102
+ fs.mkdirSync(path.dirname(dest),{recursive:true});
103
+ fs.mkdirSync(path.join(home,'.config/webhelm/runtime'),{recursive:true,mode:0o700});
104
+ if(fs.existsSync(dest)&&!fs.readFileSync(dest,'utf8').includes(`<string>${UPDATE_LABEL}</string>`))
105
+ throw Error(`Refusing to replace unrelated LaunchAgent: ${dest}`);
106
+ const updated=!fs.existsSync(dest)||fs.readFileSync(dest,'utf8')!==content;
107
+ if(updated){const tmp=dest+`.${process.pid}.tmp`;fs.writeFileSync(tmp,content,{mode:0o600});fs.renameSync(tmp,dest);}
108
+ if(!apply)return {status:'staged',path:dest,updated,label:UPDATE_LABEL};
109
+ const service=`gui/${process.getuid()}/${UPDATE_LABEL}`;
110
+ try {
111
+ execFileSync('launchctl',['print',service],{timeout:5000,stdio:'ignore'});
112
+ if(updated){
113
+ execFileSync('launchctl',['bootout',service],{timeout:5000,stdio:'ignore'});
114
+ execFileSync('launchctl',['bootstrap',`gui/${process.getuid()}`,dest],{timeout:5000,stdio:'ignore'});
115
+ }
116
+ return {status:'active',path:dest,updated,label:UPDATE_LABEL};
117
+ }catch{
118
+ try{execFileSync('launchctl',['bootstrap',`gui/${process.getuid()}`,dest],{timeout:5000,stdio:'ignore'});
119
+ return {status:'active',path:dest,updated,label:UPDATE_LABEL};}
120
+ catch(error){return {status:'staged_not_loaded',path:dest,label:UPDATE_LABEL,reason:error.message};}
121
+ }
122
+ }
123
+
124
+ export function currentRuntimePath(home=os.homedir()) {
125
+ return path.join(home,'.local/share/webhelm/runtime-current');
126
+ }
127
+
128
+ // Atomic pointer swap: version directories remain immutable, so a running
129
+ // daemon or CLI can finish on its original files while future invocations
130
+ // start from the new version. Never replace a user-owned directory.
131
+ export function activateRuntime(stagedPath,{home=os.homedir()}={}) {
132
+ const current=currentRuntimePath(home);
133
+ if(!fs.existsSync(path.join(stagedPath,'bin/webhelm.mjs')))throw Error('Missing staged WebHelm Runtime CLI');
134
+ if(fs.existsSync(current)&&!fs.lstatSync(current).isSymbolicLink())
135
+ throw Error(`Refusing to replace unmanaged Runtime directory: ${current}`);
136
+ if(fs.existsSync(current)&&fs.realpathSync(current)===fs.realpathSync(stagedPath))return {path:current,updated:false};
137
+ fs.mkdirSync(path.dirname(current),{recursive:true,mode:0o700});
138
+ const temp=`${current}.${process.pid}.${Date.now()}.tmp`;
139
+ fs.symlinkSync(stagedPath,temp,'dir');
140
+ try{fs.renameSync(temp,current);}finally{if(fs.existsSync(temp))fs.unlinkSync(temp);}
141
+ return {path:current,updated:true};
142
+ }
@@ -36,6 +36,29 @@ function ownedLeaseTabIds() {
36
36
  const pending = new Map();
37
37
  let socket, nextId = 1, browserWs, connected = false, reconnecting = false, shuttingDown = false;
38
38
  let chatgptQueue, managedChrome;
39
+ let upgradePending=false, upgradeTimeout=null, activeRequests=0, pendingSessionStarts=0;
40
+ function releaseUpgrade() {
41
+ clearTimeout(upgradeTimeout); upgradeTimeout=null;
42
+ if(!upgradePending)return;
43
+ upgradePending=false;
44
+ if(chatgptQueue && process.env.WEBHELM_CHATGPT_QUEUE_PAUSED!=='1'){
45
+ chatgptQueue.started=false;
46
+ chatgptQueue.start();
47
+ }
48
+ }
49
+ async function prepareUpgrade() {
50
+ if(upgradePending)return {ok:true,deferred:true,reason:'already_preparing'};
51
+ // The test and gate run within one event-loop turn, before any awaited work.
52
+ if(activeRequests!==1 || sessions.size || pendingSessionStarts || pendingLeaseTabIds.size ||
53
+ controlPollActive || getChatGPTQueue().active.size)
54
+ return {ok:true,deferred:true,reason:'daemon_busy',session_count:sessions.size};
55
+ upgradePending=true;
56
+ await chatgptQueue.stopScheduler(); // No active worker may cross this gate.
57
+ upgradeTimeout=setTimeout(releaseUpgrade,60000);
58
+ upgradeTimeout.unref?.();
59
+ return {ok:true,ready:true,pid:process.pid,version:PACKAGE_VERSION};
60
+ }
61
+
39
62
  let connectingBrowser=null;
40
63
  const delay = ms => new Promise(r => setTimeout(r, ms));
41
64
 
@@ -393,6 +416,9 @@ async function extensionCallSerialized(_session,method,args={}) {
393
416
 
394
417
  function jsonSafe(value){try{JSON.stringify(value);return {value}}catch{return {value_repr:String(value)}}}
395
418
  async function createSession(req={}) {
419
+ if(upgradePending)throw Error('WebHelm Runtime is upgrading; retry Session start');
420
+ pendingSessionStarts++;
421
+ try {
396
422
  const browser=await connectBrowser();
397
423
  const sid=crypto.randomBytes(8).toString('hex');
398
424
  const s={session_id:sid, workspace:req.workspace||await defaultWorkspaceName(), targetId:null,
@@ -430,6 +456,7 @@ async function createSession(req={}) {
430
456
  }else if(targetId)await browser.send('Target.closeTarget',{targetId}).catch(()=>{});
431
457
  throw error;
432
458
  }
459
+ } finally { pendingSessionStarts--; }
433
460
  }
434
461
 
435
462
  async function targetForUrl(url){for(let i=0;i<100;i++){const {targetInfos=[]}=await connectBrowser().then(b=>b.send('Target.getTargets'));const match=targetInfos.find(t=>t.type==='page'&&t.url===url);if(match)return match.targetId;await delay(50)}return null}
@@ -740,7 +767,7 @@ const siteKeepalive = createSiteKeepaliveScheduler({
740
767
  listSites:() => extensionCall(null,'workspace.control.site.list'),
741
768
  report:result => extensionCall(null,'workspace.control.site.report',result),
742
769
  canRun:async() => {
743
- if (shuttingDown) return false; // Low priority: use idle browser capacity only.
770
+ if (shuttingDown || upgradePending) return false; // Low priority: use idle browser capacity only.
744
771
  const capacity=await workspaceCapacity();
745
772
  return Number.isInteger(capacity.available) && capacity.available > 0;
746
773
  },
@@ -752,7 +779,20 @@ const siteKeepalive = createSiteKeepaliveScheduler({
752
779
  },
753
780
  });
754
781
 
755
- export async function handle(req){switch(req.op){case'ping':return {ok:true,pid:process.pid,version:PACKAGE_VERSION,queue_paused:process.env.WEBHELM_CHATGPT_QUEUE_PAUSED==='1',session_count:sessions.size,managed_chrome:managedChrome||{profile_dir:PROFILE_DIR, endpoint:process.env.WEBHELM_CDP_URL||'http://127.0.0.1:9222',reused:true},chrome_guard:managedChromeGuard.status()};case'guard-check':{let status=await managedChromeGuard.tick();for(let retry=0;retry<6 && status.status!=='healthy' && !status.skipped;retry++){await delay(800);status=await managedChromeGuard.tick();}if(status.status!=='healthy' && !status.skipped)throw Error(`WebHelm Chrome health degraded: ${status.error||status.status}`);return {ok:true,chrome_guard:status};}case'heartbeat':return heartbeatSession(req.session_id);case'list':return {session_count:sessions.size,sessions:[...sessions.values()].map(s=>({session_id:s.session_id,workspace:s.workspace,target_id:s.targetId,last_used_at:s.last_used_at}))};case'start':return createSession(req);case'exec':return execute(req);case'stop':return stopSession(req.session_id);case'stop-all':return stopAllSessions();case'stop-workspace':{if(typeof req.workspace!=='string'||!req.workspace.trim())throw Error('workspace required');return stopWorkspaceSessions(req.workspace)}case'capacity':return workspaceCapacity(req);case'workspace-create':case'workspace-configure':case'workspace-resize':case'workspace-delete':return workspaceOp(req);case'chatgpt-new-turn-enqueue':return getChatGPTQueue().enqueue(req.config);case'queue-list':return getChatGPTQueue().list();case'queue-cancel':return getChatGPTQueue().cancel(req.queue_id);case'platform-run':return runPlatform(req);default:throw Error(`unknown op: ${req.op}`)}}
782
+ export async function handle(req){
783
+ if(upgradePending && !['ping','upgrade-release','upgrade-commit',
784
+ 'chatgpt-new-turn-enqueue','queue-list','queue-cancel'].includes(req.op))
785
+ throw Error('WebHelm Runtime upgrade in progress; retry request');
786
+ switch(req.op){
787
+ case'upgrade-prepare':return prepareUpgrade();
788
+ case'upgrade-release':releaseUpgrade();return {ok:true,released:true};
789
+ case'upgrade-commit':{
790
+ if(!upgradePending)throw Error('Runtime upgrade has not been prepared');
791
+ clearTimeout(upgradeTimeout);upgradeTimeout=null;
792
+ setTimeout(()=>process.kill(process.pid,'SIGTERM'),150).unref();
793
+ return {ok:true,stopping:true,pid:process.pid};
794
+ }
795
+ case'ping':return {ok:true,pid:process.pid,version:PACKAGE_VERSION,queue_paused:process.env.WEBHELM_CHATGPT_QUEUE_PAUSED==='1',session_count:sessions.size,managed_chrome:managedChrome||{profile_dir:PROFILE_DIR, endpoint:process.env.WEBHELM_CDP_URL||'http://127.0.0.1:9222',reused:true},chrome_guard:managedChromeGuard.status()};case'guard-check':{let status=await managedChromeGuard.tick();for(let retry=0;retry<6 && status.status!=='healthy' && !status.skipped;retry++){await delay(800);status=await managedChromeGuard.tick();}if(status.status!=='healthy' && !status.skipped)throw Error(`WebHelm Chrome health degraded: ${status.error||status.status}`);return {ok:true,chrome_guard:status};}case'heartbeat':return heartbeatSession(req.session_id);case'list':return {session_count:sessions.size,sessions:[...sessions.values()].map(s=>({session_id:s.session_id,workspace:s.workspace,target_id:s.targetId,last_used_at:s.last_used_at}))};case'start':return createSession(req);case'exec':return execute(req);case'stop':return stopSession(req.session_id);case'stop-all':return stopAllSessions();case'stop-workspace':{if(typeof req.workspace!=='string'||!req.workspace.trim())throw Error('workspace required');return stopWorkspaceSessions(req.workspace)}case'capacity':return workspaceCapacity(req);case'workspace-create':case'workspace-configure':case'workspace-resize':case'workspace-delete':return workspaceOp(req);case'chatgpt-new-turn-enqueue':return getChatGPTQueue().enqueue(req.config);case'queue-list':return getChatGPTQueue().list();case'queue-cancel':return getChatGPTQueue().cancel(req.queue_id);case'platform-run':return runPlatform(req);default:throw Error(`unknown op: ${req.op}`)}}
756
796
  export function serve(conn) {
757
797
  let buffer = '', dispatched = false;
758
798
  conn.on('error',()=>{ /* A disconnected client must not crash the daemon. */ });
@@ -769,12 +809,13 @@ export function serve(conn) {
769
809
  if (newline < 0 || dispatched) return;
770
810
  dispatched=true;
771
811
  const raw = buffer.slice(0, newline);
812
+ activeRequests++;
772
813
  try {
773
814
  const reply = await handle(JSON.parse(raw));
774
815
  if(!conn.destroyed)conn.end(JSON.stringify(reply) + '\n');
775
816
  } catch (error) {
776
817
  if(!conn.destroyed)conn.end(JSON.stringify({ error: `${error.name}: ${error.message}` }) + '\n');
777
- }
818
+ } finally { activeRequests--; }
778
819
  });
779
820
  }
780
821