webhelm 1.0.48 → 1.0.50
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 +5 -5
- package/package.json +4 -2
- package/runtime/actions-repo.mjs +33 -0
- package/runtime/cli-help.mjs +5 -5
- package/runtime/cli.mjs +12 -35
- package/runtime/extension/manifest.json +1 -1
- package/runtime/extension/popup-data.mjs +8 -11
- package/runtime/extension/popup.html +1 -1
- package/runtime/extension/popup.mjs +7 -7
- package/runtime/node-daemon.mjs +33 -33
- package/runtime/platform-delivery-queue.mjs +248 -0
- package/runtime/platforms.mjs +20 -1
- package/runtime/queue-registry.mjs +162 -0
- package/scripts/chatgpt-three-mvps.mjs +192 -0
- package/runtime/chatgpt/attachment-upload.mjs +0 -35
- package/runtime/chatgpt/chatgpt-delivery-errors.mjs +0 -94
- package/runtime/chatgpt/chatgpt-probe.mjs +0 -80
- package/runtime/chatgpt/chatgpt-queue.mjs +0 -374
- package/runtime/chatgpt/lifecycle-common.mjs +0 -93
- package/runtime/chatgpt/readiness.mjs +0 -120
- package/runtime/chatgpt/submission-script.mjs +0 -31
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
2
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
3
|
+
import { mkdirSync } from 'node:fs';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { DurableQueueCore } from './durable-queue-core.mjs';
|
|
6
|
+
|
|
7
|
+
function canonical(value) {
|
|
8
|
+
if (Array.isArray(value)) return value.map(canonical);
|
|
9
|
+
if (value && typeof value === 'object') return Object.fromEntries(
|
|
10
|
+
Object.keys(value).sort().map(key => [key, canonical(value[key])]),
|
|
11
|
+
);
|
|
12
|
+
return value;
|
|
13
|
+
}
|
|
14
|
+
export function fingerprint(config) {
|
|
15
|
+
return createHash('sha256').update(JSON.stringify(canonical(config))).digest('hex');
|
|
16
|
+
}
|
|
17
|
+
function normalize(config) {
|
|
18
|
+
if (!config || typeof config !== 'object' || Array.isArray(config)) throw TypeError('queue action config must be an object');
|
|
19
|
+
const value = {...config};
|
|
20
|
+
if (typeof value.idempotency_key !== 'string' || !value.idempotency_key.trim()) throw TypeError('idempotency_key required');
|
|
21
|
+
if (value.mergeable !== undefined && typeof value.mergeable !== 'boolean') throw TypeError('mergeable must be boolean');
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
function requiredString(value, name) {
|
|
25
|
+
if (typeof value !== 'string' || !value.trim()) throw TypeError(`${name} must return a nonempty string`);
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
function display(policy, config) {
|
|
29
|
+
const title = requiredString(policy.title(config), 'title');
|
|
30
|
+
const group = requiredString(policy.group(config), 'group');
|
|
31
|
+
let url = null;
|
|
32
|
+
if (typeof policy.url === 'function') {
|
|
33
|
+
url = policy.url(config);
|
|
34
|
+
const parsed = new URL(url);
|
|
35
|
+
if (parsed.protocol !== 'https:' || parsed.username || parsed.password || parsed.search || parsed.hash)
|
|
36
|
+
throw TypeError('queue url must be HTTPS without credentials, query or fragment');
|
|
37
|
+
}
|
|
38
|
+
return {title,group,url};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Queue-neutral persistence: every policy runs in its own SQLite database.
|
|
42
|
+
// No browser/site rules live in this adapter.
|
|
43
|
+
const dbPolicy = {
|
|
44
|
+
rows(db) { return db.prepare('SELECT * FROM items ORDER BY seq').all(); },
|
|
45
|
+
enqueue(db, request, now) {
|
|
46
|
+
const config = normalize(request);
|
|
47
|
+
const key = config.idempotency_key;
|
|
48
|
+
const hash = fingerprint(config);
|
|
49
|
+
const same = db.prepare('SELECT queue_id,payload_hash FROM request_keys WHERE idem_key=?').get(key);
|
|
50
|
+
if (same) {
|
|
51
|
+
if (same.payload_hash !== hash) throw Error('idempotency key reused with different payload');
|
|
52
|
+
const row = db.prepare('SELECT id,state,group_key FROM items WHERE id=?').get(same.queue_id);
|
|
53
|
+
if (!row) throw Error('orphaned idempotency reference');
|
|
54
|
+
return {ok:true,status:'queued',queue_id:row.id,state:row.state,group:row.group_key};
|
|
55
|
+
}
|
|
56
|
+
const meta = display(this.definition, config);
|
|
57
|
+
const tail = db.prepare('SELECT * FROM items WHERE group_key=? ORDER BY seq DESC LIMIT 1').get(meta.group);
|
|
58
|
+
if (tail && config.mergeable === true && ['QUEUED','WAITING'].includes(tail.state) &&
|
|
59
|
+
tail.lease_owner === null && typeof this.definition.merge === 'function') {
|
|
60
|
+
const previous = JSON.parse(tail.payload_json);
|
|
61
|
+
if (previous.mergeable === true) {
|
|
62
|
+
const merged = this.definition.merge(previous, config);
|
|
63
|
+
if (merged !== null && merged !== undefined) {
|
|
64
|
+
if (!merged || typeof merged !== 'object' || Array.isArray(merged)) throw TypeError('merge must return config or null');
|
|
65
|
+
const mergedMeta = display(this.definition, merged);
|
|
66
|
+
if (mergedMeta.group !== meta.group) throw Error('merge must preserve group');
|
|
67
|
+
if (merged.idempotency_key!==previous.idempotency_key) throw Error('merge must preserve original idempotency key');
|
|
68
|
+
if (merged.mergeable!==true) throw Error('merge must preserve mergeable eligibility');
|
|
69
|
+
db.prepare('UPDATE items SET payload_json=?,title=?,url=? WHERE id=?')
|
|
70
|
+
.run(JSON.stringify(merged),mergedMeta.title,mergedMeta.url,tail.id);
|
|
71
|
+
db.prepare('INSERT INTO request_keys(idem_key,queue_id,payload_hash) VALUES(?,?,?)').run(key,tail.id,hash);
|
|
72
|
+
return {ok:true,status:'queued',queue_id:tail.id,state:tail.state,group:meta.group};
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const id = randomUUID();
|
|
77
|
+
db.prepare(`INSERT INTO items(id,group_key,payload_json,title,url,state,next_check_at,created_at)
|
|
78
|
+
VALUES(?,?,?,?,?,'QUEUED',?,?)`)
|
|
79
|
+
.run(id,meta.group,JSON.stringify(config),meta.title,meta.url,now,now);
|
|
80
|
+
db.prepare('INSERT INTO request_keys(idem_key,queue_id,payload_hash) VALUES(?,?,?)').run(key,id,hash);
|
|
81
|
+
return {ok:true,status:'queued',queue_id:id,state:'QUEUED',group:meta.group};
|
|
82
|
+
},
|
|
83
|
+
claim(db, owner, now, leaseSeconds) {
|
|
84
|
+
db.prepare("UPDATE items SET state='FAILED',lease_owner=NULL,lease_until=NULL,receipt=COALESCE(receipt,'send_interrupted') WHERE state='SENDING' AND lease_until<=?").run(now);
|
|
85
|
+
db.prepare("UPDATE items SET state='WAITING',lease_owner=NULL,lease_until=NULL,next_check_at=? WHERE state='CHECKING' AND lease_until<=?").run(now,now);
|
|
86
|
+
const row = db.prepare(`SELECT item.* FROM items item WHERE item.state IN ('QUEUED','WAITING') AND item.next_check_at<=?
|
|
87
|
+
AND NOT EXISTS (SELECT 1 FROM items older WHERE older.group_key=item.group_key AND older.seq<item.seq
|
|
88
|
+
AND (older.state NOT IN ('SENT','FAILED','CANCELLED') OR (older.state='SENT' AND older.next_check_at>?)))
|
|
89
|
+
ORDER BY item.seq LIMIT 1`).get(now,now);
|
|
90
|
+
if (!row) return null;
|
|
91
|
+
db.prepare("UPDATE items SET state='CHECKING',lease_owner=?,lease_until=?,attempts=attempts+1 WHERE id=?")
|
|
92
|
+
.run(owner,now+leaseSeconds,row.id);
|
|
93
|
+
return db.prepare('SELECT * FROM items WHERE id=?').get(row.id);
|
|
94
|
+
},
|
|
95
|
+
cancel(db, id) {
|
|
96
|
+
const row = db.prepare('SELECT state FROM items WHERE id=?').get(id);
|
|
97
|
+
if (!row) return {ok:false,queue_id:id,error:'queue item not found'};
|
|
98
|
+
if (!['QUEUED','WAITING'].includes(row.state)) return {ok:false,queue_id:id,state:row.state,error:'cannot remove a running or completed item'};
|
|
99
|
+
db.prepare("UPDATE items SET state='CANCELLED' WHERE id=? AND state IN ('QUEUED','WAITING') AND lease_owner IS NULL").run(id);
|
|
100
|
+
return {ok:true,queue_id:id,state:'CANCELLED'};
|
|
101
|
+
},
|
|
102
|
+
list(db) {
|
|
103
|
+
const items = db.prepare("SELECT * FROM items WHERE state NOT IN ('SENT','CANCELLED') ORDER BY seq").all();
|
|
104
|
+
return {ok:true,items:items.map(row => ({id:row.id,queue_id:row.id,group:row.group_key,
|
|
105
|
+
state:row.state,attempts:row.attempts,created_at:row.created_at,
|
|
106
|
+
receipt:row.receipt,title:row.title,url:row.url}))};
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
export class PlatformDeliveryQueue extends DurableQueueCore {
|
|
111
|
+
constructor({platform,queue,definition,persistenceRoot,startSession,stopSession,runAction,
|
|
112
|
+
intervalMs,concurrency,leaseSeconds=600,now=()=>Date.now()/1000,logger=()=>{}}) {
|
|
113
|
+
if (!/^[a-z0-9-]+$/.test(platform) || !/^[a-z0-9-]+$/.test(queue)) throw TypeError('invalid queue identity');
|
|
114
|
+
const dir=join(persistenceRoot,'queues',platform);
|
|
115
|
+
mkdirSync(dir,{recursive:true});
|
|
116
|
+
const dbPath=join(dir,`${queue}.sqlite3`);
|
|
117
|
+
const db=new DatabaseSync(dbPath);
|
|
118
|
+
db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000');
|
|
119
|
+
db.exec(`CREATE TABLE IF NOT EXISTS items(
|
|
120
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL, group_key TEXT NOT NULL,
|
|
121
|
+
payload_json TEXT NOT NULL, title TEXT NOT NULL, url TEXT, state TEXT NOT NULL,
|
|
122
|
+
lease_owner TEXT, lease_until REAL, next_check_at REAL NOT NULL, created_at REAL NOT NULL,
|
|
123
|
+
attempts INTEGER NOT NULL DEFAULT 0, receipt TEXT);
|
|
124
|
+
CREATE INDEX IF NOT EXISTS queue_group_fifo ON items(group_key,seq);
|
|
125
|
+
CREATE TABLE IF NOT EXISTS request_keys(idem_key TEXT PRIMARY KEY,queue_id TEXT NOT NULL,payload_hash TEXT NOT NULL);`);
|
|
126
|
+
const adapter=Object.create(dbPolicy);
|
|
127
|
+
super(db,adapter,now,{concurrency:concurrency??definition.concurrency??1,intervalMs:intervalMs??definition.intervalMs??10000});
|
|
128
|
+
adapter.definition=definition;
|
|
129
|
+
this.definition=definition;
|
|
130
|
+
this.platform=platform;
|
|
131
|
+
this.queue=queue;
|
|
132
|
+
this.dbPath=dbPath;
|
|
133
|
+
this.startSession=startSession;
|
|
134
|
+
this.stopSession=stopSession;
|
|
135
|
+
this.runAction=runAction;
|
|
136
|
+
this.leaseSeconds=leaseSeconds;
|
|
137
|
+
this.logger=logger;
|
|
138
|
+
this.enabled=true;
|
|
139
|
+
this.databaseClosed=false;
|
|
140
|
+
}
|
|
141
|
+
setDefinition(definition) {
|
|
142
|
+
this.definition=definition;
|
|
143
|
+
this.policy.definition=definition;
|
|
144
|
+
this.concurrency=Math.max(1,Math.min(32,definition.concurrency??1));
|
|
145
|
+
this.intervalMs=definition.intervalMs??10000;
|
|
146
|
+
this.enabled=true;
|
|
147
|
+
if (this.started) this._wake(0);
|
|
148
|
+
}
|
|
149
|
+
enqueue(config) {
|
|
150
|
+
if (!this.enabled) throw Error('queue registration not active');
|
|
151
|
+
const result=super.enqueue(config);
|
|
152
|
+
if (this.started) this._wake(0);
|
|
153
|
+
return {...result,platform:this.platform,queue:this.queue};
|
|
154
|
+
}
|
|
155
|
+
claim(owner, now=this.now()) {
|
|
156
|
+
if (!this.enabled) return null;
|
|
157
|
+
return super.claim(owner,now,this.leaseSeconds);
|
|
158
|
+
}
|
|
159
|
+
list() {
|
|
160
|
+
const result=super.list();
|
|
161
|
+
return {...result,items:result.items.map(item=>{
|
|
162
|
+
const row=this.db.prepare('SELECT payload_json FROM items WHERE id=?').get(item.id);
|
|
163
|
+
let title=item.title,url=item.url;
|
|
164
|
+
try {
|
|
165
|
+
const config=JSON.parse(row.payload_json);
|
|
166
|
+
const displayValue=display(this.definition,config);
|
|
167
|
+
title=displayValue.title;url=displayValue.url;
|
|
168
|
+
} catch { /* Preserve the previously validated display data. */ }
|
|
169
|
+
return {...item,title,url,platform:this.platform,queue:this.queue};
|
|
170
|
+
})};
|
|
171
|
+
}
|
|
172
|
+
has(id) { return Boolean(this.db.prepare('SELECT 1 FROM items WHERE id=?').get(id)); }
|
|
173
|
+
transition(id,owner,from,to,{delay=0,receipt=null}={}) {
|
|
174
|
+
const now=this.now();
|
|
175
|
+
return this._transaction(()=>{
|
|
176
|
+
const row=this.db.prepare('SELECT state,lease_owner,lease_until FROM items WHERE id=?').get(id);
|
|
177
|
+
if (!row || row.state!==from || row.lease_owner!==owner || row.lease_until<=now) throw Error('stale queue lease');
|
|
178
|
+
this.db.prepare('UPDATE items SET state=?,lease_owner=?,lease_until=?,next_check_at=?,receipt=? WHERE id=?')
|
|
179
|
+
.run(to,['SENT','FAILED','WAITING'].includes(to)?null:owner,
|
|
180
|
+
['SENT','FAILED','WAITING'].includes(to)?null:now+this.leaseSeconds,
|
|
181
|
+
now+delay,receipt,id);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
process(item) { return this._process(item); }
|
|
185
|
+
onDispatchError(error) { this.logger({event:'queue_dispatch_error',platform:this.platform,queue:this.queue,error:String(error)}); }
|
|
186
|
+
async _process(item) {
|
|
187
|
+
const definition=this.definition;
|
|
188
|
+
const config=JSON.parse(item.payload_json);
|
|
189
|
+
let sid;
|
|
190
|
+
// Renew a live worker lease while it is inside the browser Action Runner.
|
|
191
|
+
// A slow but active Action must not unblock a second send in the same group.
|
|
192
|
+
const heartbeat=setInterval(()=>{
|
|
193
|
+
try {
|
|
194
|
+
this.db.prepare(`UPDATE items SET lease_until=? WHERE id=? AND lease_owner=? AND state IN ('CHECKING','SENDING')`)
|
|
195
|
+
.run(this.now()+this.leaseSeconds,item.id,item.lease_owner);
|
|
196
|
+
} catch(error) { this.onDispatchError(error); }
|
|
197
|
+
},Math.min(30000,Math.max(1000,this.leaseSeconds*250)));
|
|
198
|
+
heartbeat.unref?.();
|
|
199
|
+
try {
|
|
200
|
+
const started=await this.startSession({url:item.url||'about:blank',workspace:'WebHelm'});
|
|
201
|
+
sid=started.session_id??started.sessionId;
|
|
202
|
+
if (!sid) throw Error('queue Session creation did not return session_id');
|
|
203
|
+
const checked=await this.runAction({platform:this.platform,action:definition.validate,config,session_id:sid});
|
|
204
|
+
if (checked?.result?.ok !== true) {
|
|
205
|
+
// A failed read-only gate must not silently drop its FIFO head.
|
|
206
|
+
this.transition(item.id,item.lease_owner,'CHECKING','WAITING',{
|
|
207
|
+
delay:this.intervalMs/1000,receipt:'validate_error',
|
|
208
|
+
});
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const value=checked.result.value;
|
|
212
|
+
const ready=checked?.result?.ok === true && (value === true || value?.ready === true || value?.status === 'ready');
|
|
213
|
+
if (!ready) {
|
|
214
|
+
this.transition(item.id,item.lease_owner,'CHECKING','WAITING',{
|
|
215
|
+
delay:this.intervalMs/1000,
|
|
216
|
+
receipt:'not_ready',
|
|
217
|
+
});
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
this.transition(item.id,item.lease_owner,'CHECKING','SENDING');
|
|
221
|
+
const outcome=await this.runAction({platform:this.platform,action:definition.action,
|
|
222
|
+
config:typeof definition.execute==='function'?definition.execute(config):config,session_id:sid});
|
|
223
|
+
if (outcome?.result?.ok!==true ||
|
|
224
|
+
(typeof definition.success==='function' && definition.success(outcome.result.value)!==true))
|
|
225
|
+
throw Error('action_failed');
|
|
226
|
+
this.transition(item.id,item.lease_owner,'SENDING','SENT',{
|
|
227
|
+
delay:this.intervalMs/1000,receipt:outcome.result.value?.verified_by || 'action_completed',
|
|
228
|
+
});
|
|
229
|
+
} catch(error) {
|
|
230
|
+
const diagnostic='Error;fingerprint='+createHash('sha256').update(String(error)).digest('hex').slice(0,16);
|
|
231
|
+
try {
|
|
232
|
+
const row=this.db.prepare('SELECT state FROM items WHERE id=?').get(item.id);
|
|
233
|
+
if (row?.state==='SENDING') this.transition(item.id,item.lease_owner,'SENDING','FAILED',{receipt:diagnostic});
|
|
234
|
+
else if (row?.state==='CHECKING') this.transition(item.id,item.lease_owner,'CHECKING','WAITING',{delay:this.intervalMs/1000,receipt:diagnostic});
|
|
235
|
+
} catch(transitionError) { this.onDispatchError(transitionError); }
|
|
236
|
+
} finally {
|
|
237
|
+
clearInterval(heartbeat);
|
|
238
|
+
if (sid) try { await this.stopSession(sid); }
|
|
239
|
+
catch(error) { this.logger({event:'queue_session_release_failed',platform:this.platform,error:String(error)}); }
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
async shutdown() {
|
|
243
|
+
if (this.databaseClosed) return;
|
|
244
|
+
await this.stopScheduler();
|
|
245
|
+
this.db.close();
|
|
246
|
+
this.databaseClosed=true;
|
|
247
|
+
}
|
|
248
|
+
}
|
package/runtime/platforms.mjs
CHANGED
|
@@ -39,7 +39,7 @@ export function platformProfile(platform) {
|
|
|
39
39
|
export function actionPath(platform, action) {
|
|
40
40
|
const manifest = platformManifest(platform);
|
|
41
41
|
const name = namePart(action.replaceAll('_', '-'));
|
|
42
|
-
const relative = manifest.actions?.[name];
|
|
42
|
+
const relative = manifest.actions?.[action] || manifest.actions?.[name];
|
|
43
43
|
if (typeof relative !== 'string' || !/^actions\/[\w-]+\.mjs$/.test(relative)) {
|
|
44
44
|
throw new Error(`unknown or non-Node platform action ${platform}/${name}`);
|
|
45
45
|
}
|
|
@@ -87,3 +87,22 @@ export async function invokePlatformAction(platform, action, { helpers, config,
|
|
|
87
87
|
if (typeof runner !== 'function') throw new Error(`Node action does not export a run function: ${platform}/${action}`);
|
|
88
88
|
return runner({ helpers, config, log });
|
|
89
89
|
}
|
|
90
|
+
|
|
91
|
+
/** Find the queue whose policy dispatches an Action. Never infer registration from
|
|
92
|
+
* a manifest key; the daemon watches the same queues/ directory. */
|
|
93
|
+
export async function queueForAction(platform, action) {
|
|
94
|
+
const dir=path.join(PLATFORMS,namePart(platform),'queues');
|
|
95
|
+
if (!fs.existsSync(dir)) return null;
|
|
96
|
+
let match=null;
|
|
97
|
+
for (const entry of fs.readdirSync(dir,{withFileTypes:true})) {
|
|
98
|
+
if (!entry.isFile() || !/^[a-z0-9-]+\.mjs$/.test(entry.name)) continue;
|
|
99
|
+
const file=path.join(dir,entry.name);
|
|
100
|
+
const stat=fs.statSync(file);
|
|
101
|
+
const module=await import(pathToFileURL(file).href+`?version=${stat.mtimeMs}-${stat.size}`);
|
|
102
|
+
if (module.default?.action === action) {
|
|
103
|
+
if (match) throw Error(`multiple queues registered for ${platform}/${action}; enqueue by queue name`);
|
|
104
|
+
match=entry.name.slice(0,-4);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return match;
|
|
108
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import {watch, existsSync, readdirSync, readFileSync} from 'node:fs';
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {parse as parseYaml} from 'yaml';
|
|
4
|
+
import {join, resolve} from 'node:path';
|
|
5
|
+
import {pathToFileURL} from 'node:url';
|
|
6
|
+
import {PLATFORMS} from './platforms.mjs';
|
|
7
|
+
import {PlatformDeliveryQueue} from './platform-delivery-queue.mjs';
|
|
8
|
+
|
|
9
|
+
const validName=/^[a-z0-9][a-z0-9-]*$/;
|
|
10
|
+
function definitions(root) {
|
|
11
|
+
const files=new Map();
|
|
12
|
+
if (!existsSync(root)) return files;
|
|
13
|
+
for (const platform of readdirSync(root,{withFileTypes:true})) {
|
|
14
|
+
if (!platform.isDirectory() || !validName.test(platform.name)) continue;
|
|
15
|
+
const site=join(root,platform.name);
|
|
16
|
+
if (!existsSync(join(site,'manifest.yaml'))) continue;
|
|
17
|
+
const dir=join(site,'queues');
|
|
18
|
+
if (!existsSync(dir)) continue;
|
|
19
|
+
for (const entry of readdirSync(dir,{withFileTypes:true})) {
|
|
20
|
+
if (!entry.isFile() || !entry.name.endsWith('.mjs')) continue;
|
|
21
|
+
const queue=entry.name.slice(0,-4);
|
|
22
|
+
if (!validName.test(queue)) continue;
|
|
23
|
+
const file=join(dir,entry.name);
|
|
24
|
+
const hash=createHash('sha256').update(readFileSync(file)).digest('hex');
|
|
25
|
+
files.set(`${platform.name}/${queue}`,{platform:platform.name,queue,file,signature:hash});
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return files;
|
|
29
|
+
}
|
|
30
|
+
function validPolicy(definition, platform, root) {
|
|
31
|
+
if (!definition || typeof definition!=='object') throw TypeError('queue policy must export an object');
|
|
32
|
+
if (typeof definition.group!=='function' || typeof definition.title!=='function') throw TypeError('queue policy needs group(action) and title(action)');
|
|
33
|
+
if (typeof definition.action!=='string' || typeof definition.validate!=='string') throw TypeError('queue policy needs action and validate action names');
|
|
34
|
+
const manifest=parseYaml(readFileSync(join(root,platform,'manifest.yaml'),'utf8'));
|
|
35
|
+
if (manifest?.platform!==platform) throw Error('queue platform manifest mismatch');
|
|
36
|
+
for (const name of [definition.action,definition.validate]) {
|
|
37
|
+
const relative=manifest.actions?.[name];
|
|
38
|
+
if (typeof relative!=='string' || !/^actions\/[\w-]+\.mjs$/.test(relative) ||
|
|
39
|
+
!existsSync(join(root,platform,relative))) throw Error(`unknown or missing queue action: ${platform}/${name}`);
|
|
40
|
+
}
|
|
41
|
+
for (const name of ['merge','execute','url','success']) {
|
|
42
|
+
if (definition[name]!==undefined && typeof definition[name]!=='function') throw TypeError(`${name} must be a function`);
|
|
43
|
+
}
|
|
44
|
+
if (definition.concurrency!==undefined && (!Number.isInteger(definition.concurrency) || definition.concurrency<1 || definition.concurrency>32)) throw TypeError('concurrency must be 1..32');
|
|
45
|
+
if (definition.intervalMs!==undefined && (!Number.isInteger(definition.intervalMs) || definition.intervalMs<100 || definition.intervalMs>3600000)) throw TypeError('intervalMs must be 100..3600000');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class PlatformQueueRegistry {
|
|
49
|
+
constructor({platformsRoot=PLATFORMS,persistenceRoot,startSession,stopSession,runAction,
|
|
50
|
+
logger=()=>{},pollMs=10000,paused=false}={}) {
|
|
51
|
+
this.platformsRoot=resolve(platformsRoot);
|
|
52
|
+
this.persistenceRoot=persistenceRoot;
|
|
53
|
+
this.startSession=startSession;
|
|
54
|
+
this.stopSession=stopSession;
|
|
55
|
+
this.runAction=runAction;
|
|
56
|
+
this.logger=logger;
|
|
57
|
+
this.pollMs=pollMs;
|
|
58
|
+
this.paused=paused;
|
|
59
|
+
this.records=new Map();
|
|
60
|
+
this.watchers=new Map();
|
|
61
|
+
this.refreshing=Promise.resolve();
|
|
62
|
+
this.timer=null;
|
|
63
|
+
this.interval=null;
|
|
64
|
+
this.closed=false;
|
|
65
|
+
}
|
|
66
|
+
async refresh() {
|
|
67
|
+
this.refreshing=this.refreshing.catch(()=>{}).then(()=>this._refresh());
|
|
68
|
+
return this.refreshing;
|
|
69
|
+
}
|
|
70
|
+
async _refresh() {
|
|
71
|
+
if (this.closed) return;
|
|
72
|
+
const found=definitions(this.platformsRoot);
|
|
73
|
+
for (const [key,entry] of found) {
|
|
74
|
+
const existing=this.records.get(key);
|
|
75
|
+
if (existing && existing.signature===entry.signature) {
|
|
76
|
+
existing.instance.enabled=true;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
try {
|
|
80
|
+
const module=await import(pathToFileURL(entry.file).href+`?version=${encodeURIComponent(entry.signature)}`);
|
|
81
|
+
const definition=module.default;
|
|
82
|
+
validPolicy(definition,entry.platform,this.platformsRoot);
|
|
83
|
+
if (existing) {
|
|
84
|
+
existing.instance.setDefinition(definition);
|
|
85
|
+
existing.signature=entry.signature;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const instance=new PlatformDeliveryQueue({platform:entry.platform,queue:entry.queue,definition,
|
|
89
|
+
persistenceRoot:this.persistenceRoot,startSession:this.startSession,stopSession:this.stopSession,
|
|
90
|
+
runAction:this.runAction,logger:this.logger});
|
|
91
|
+
this.records.set(key,{instance,signature:entry.signature});
|
|
92
|
+
if (!this.paused) instance.start();
|
|
93
|
+
} catch(error) {
|
|
94
|
+
this.logger({event:'queue_policy_load_failed',key,error:String(error)});
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
for (const [key,record] of this.records) {
|
|
98
|
+
if (!found.has(key)) record.instance.enabled=false; // Preserve data; do not drop an in-flight worker.
|
|
99
|
+
}
|
|
100
|
+
this._syncWatchers();
|
|
101
|
+
}
|
|
102
|
+
_syncWatchers() {
|
|
103
|
+
const dirs=new Set([this.platformsRoot]);
|
|
104
|
+
if (existsSync(this.platformsRoot)) for (const item of readdirSync(this.platformsRoot,{withFileTypes:true})) {
|
|
105
|
+
if (!item.isDirectory()) continue;
|
|
106
|
+
const dir=join(this.platformsRoot,item.name);
|
|
107
|
+
dirs.add(dir);
|
|
108
|
+
if (existsSync(join(dir,'queues'))) dirs.add(join(dir,'queues'));
|
|
109
|
+
}
|
|
110
|
+
for (const [dir,watcher] of this.watchers) if (!dirs.has(dir)) {
|
|
111
|
+
watcher.close();this.watchers.delete(dir);
|
|
112
|
+
}
|
|
113
|
+
for (const dir of dirs) {
|
|
114
|
+
if (this.watchers.has(dir) || !existsSync(dir)) continue;
|
|
115
|
+
try {
|
|
116
|
+
const watcher=watch(dir,()=>this._scheduleRefresh());
|
|
117
|
+
watcher.on('error',error=>this.logger({event:'queue_watch_error',dir,error:String(error)}));
|
|
118
|
+
this.watchers.set(dir,watcher);
|
|
119
|
+
} catch(error) { this.logger({event:'queue_watch_error',dir,error:String(error)}); }
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
_scheduleRefresh() {
|
|
123
|
+
if (this.closed) return;
|
|
124
|
+
clearTimeout(this.timer);
|
|
125
|
+
this.timer=setTimeout(()=>this.refresh().catch(error=>this.logger({event:'queue_refresh_error',error:String(error)})),100);
|
|
126
|
+
this.timer.unref?.();
|
|
127
|
+
}
|
|
128
|
+
async start() {
|
|
129
|
+
await this.refresh();
|
|
130
|
+
this.interval=setInterval(()=>this._scheduleRefresh(),this.pollMs);
|
|
131
|
+
this.interval.unref?.();
|
|
132
|
+
return this;
|
|
133
|
+
}
|
|
134
|
+
setPaused(paused) {
|
|
135
|
+
this.paused=Boolean(paused);
|
|
136
|
+
for (const {instance} of this.records.values()) {
|
|
137
|
+
if (this.paused) { instance.started=false;clearTimeout(instance.wakeTimer); }
|
|
138
|
+
else {instance.started=false;instance.start();}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
get(platform,queue) {
|
|
142
|
+
const entry=this.records.get(`${platform}/${queue}`);
|
|
143
|
+
if (!entry || !entry.instance.enabled) throw Error(`queue not registered: ${platform}/${queue}`);
|
|
144
|
+
return entry.instance;
|
|
145
|
+
}
|
|
146
|
+
enqueue({platform,queue,config}) { return this.get(platform,queue).enqueue(config); }
|
|
147
|
+
list() { return {ok:true,items:[...this.records.values()].flatMap(({instance})=>instance.list().items)}; }
|
|
148
|
+
cancel(id) {
|
|
149
|
+
for (const {instance} of this.records.values()) if (instance.has(id)) return instance.cancel(id);
|
|
150
|
+
return {ok:false,queue_id:id,error:'queue item not found'};
|
|
151
|
+
}
|
|
152
|
+
activeCount() { return [...this.records.values()].reduce((sum,{instance})=>sum+instance.active.size,0); }
|
|
153
|
+
async stopScheduler() { this.paused=true;await Promise.all([...this.records.values()].map(({instance})=>instance.stopScheduler())); }
|
|
154
|
+
async shutdown() {
|
|
155
|
+
this.closed=true;
|
|
156
|
+
clearTimeout(this.timer);clearInterval(this.interval);
|
|
157
|
+
for (const watcher of this.watchers.values()) watcher.close();
|
|
158
|
+
this.watchers.clear();
|
|
159
|
+
await this.refreshing.catch(()=>{});
|
|
160
|
+
await Promise.all([...this.records.values()].map(({instance})=>instance.shutdown()));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Mandatory real-browser ChatGPT Actions release gate. Makes four deliberate
|
|
3
|
+
// external sends (one new-thread, one direct new-turn, two queued new-turns).
|
|
4
|
+
// Never executes during npm test; requires explicit opt-in and a signed-in
|
|
5
|
+
// owned Chrome Session. Queue messages use a brand-new test thread only.
|
|
6
|
+
import assert from 'node:assert/strict';
|
|
7
|
+
import {randomUUID} from 'node:crypto';
|
|
8
|
+
import {existsSync,mkdtempSync,mkdirSync,writeFileSync,readFileSync,rmSync} from 'node:fs';
|
|
9
|
+
import {tmpdir,homedir} from 'node:os';
|
|
10
|
+
import {join,resolve} from 'node:path';
|
|
11
|
+
import {fileURLToPath,pathToFileURL} from 'node:url';
|
|
12
|
+
import {DatabaseSync} from 'node:sqlite';
|
|
13
|
+
import {request} from '../runtime/node-daemon.mjs';
|
|
14
|
+
import {PlatformDeliveryQueue} from '../runtime/platform-delivery-queue.mjs';
|
|
15
|
+
import {RUNTIME_DIR} from '../runtime/config-paths.mjs';
|
|
16
|
+
|
|
17
|
+
if(process.env.WEBHELM_MVP_ALLOW_SEND!=='1') {
|
|
18
|
+
throw Error('REAL ChatGPT send test: export WEBHELM_MVP_ALLOW_SEND=1 to authorize four test messages');
|
|
19
|
+
}
|
|
20
|
+
const isolatedManual=process.argv.includes('--isolated-manual-queue');
|
|
21
|
+
const actionsRoot=resolve(process.env.WEBHELM_PLATFORM_DIR || join(homedir(),'.local/webhelm/platforms'));
|
|
22
|
+
const evidenceDir=resolve(process.env.WEBHELM_MVP_EVIDENCE_DIR || join(tmpdir(),'webhelm-chatgpt-mvp-evidence'));
|
|
23
|
+
mkdirSync(evidenceDir,{recursive:true});
|
|
24
|
+
const tag=`WEBHELM_MVP_${Date.now().toString(36).toUpperCase()}_${randomUUID().slice(0,8).toUpperCase()}`;
|
|
25
|
+
const evidenceFile=join(evidenceDir,`${tag}.json`);
|
|
26
|
+
const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
27
|
+
const evidence={tag,mode:isolatedManual?'isolated-real-browser-queue':'live-daemon-queue',
|
|
28
|
+
started_at:new Date().toISOString(),checks:[],session_ids:[],mvp1:null,mvp2:null,mvp3:null,pass:false};
|
|
29
|
+
const record=(name,data={})=>{
|
|
30
|
+
evidence.checks.push({at:new Date().toISOString(),name,...data});
|
|
31
|
+
writeFileSync(evidenceFile,JSON.stringify(evidence,null,2),{mode:0o600});
|
|
32
|
+
console.log(JSON.stringify({stage:name,...data}));
|
|
33
|
+
};
|
|
34
|
+
async function ipc(op,args={}) {
|
|
35
|
+
const value=await request({op,...args});
|
|
36
|
+
if(value?.error) throw Error(`${op} failed: ${value.error}`);
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
async function sessions() {
|
|
40
|
+
return (await ipc('list')).sessions||[];
|
|
41
|
+
}
|
|
42
|
+
const existing=new Set((await sessions()).map(x=>x.session_id));
|
|
43
|
+
const initial=await ipc('ping');
|
|
44
|
+
record('preflight',{daemon_pid:initial.pid,daemon_version:initial.version,
|
|
45
|
+
existing_sessions:[...(await sessions())].map(x=>x.workspace),
|
|
46
|
+
source:'real Chrome, same signed-in profile'});
|
|
47
|
+
if(!isolatedManual) {
|
|
48
|
+
const expectedVersion=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
|
|
49
|
+
if(initial.version!==expectedVersion)
|
|
50
|
+
throw Error(`native Queue MVP requires active daemon version ${expectedVersion}; running ${initial.version}; no messages sent`);
|
|
51
|
+
const listed=await ipc('queue-list');
|
|
52
|
+
if((listed.items||[]).some(x=>!x.queue || !x.platform)) {
|
|
53
|
+
throw Error('native 3-MVP queue requires new generic daemon; old Queue detected; no messages sent');
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
let sid=null,temporaryQueue=null,storeDir=null;
|
|
57
|
+
try {
|
|
58
|
+
const started=await ipc('start',{url:'https://chatgpt.com/',workspace:'WebHelm'});
|
|
59
|
+
sid=started.session_id;
|
|
60
|
+
assert.ok(sid,'failed to create owned real Chrome Session');
|
|
61
|
+
evidence.session_ids.push(sid);
|
|
62
|
+
record('session_started',{session_id:sid});
|
|
63
|
+
async function runDirect(action,config,session_id=sid) {
|
|
64
|
+
const value=await ipc('platform-run',{platform:'chatgpt',action,config,session_id,workspace:'WebHelm'});
|
|
65
|
+
const result=value?.result;
|
|
66
|
+
assert.equal(result?.ok,true,`${action} failed: ${JSON.stringify(result)}`);
|
|
67
|
+
assert.equal(result.value?.status,'submitted',`${action} missing submission receipt`);
|
|
68
|
+
return result.value;
|
|
69
|
+
}
|
|
70
|
+
const one=await runDirect('new-thread',{
|
|
71
|
+
message:`${tag}_MVP1_NEW_THREAD. This is an automated browser Actions acceptance test. Reply ${tag}_MVP1_ACK.`,
|
|
72
|
+
});
|
|
73
|
+
assert.ok(one.thread_id && one.thread_url,'new-thread must return a durable thread ID');
|
|
74
|
+
evidence.thread_id=one.thread_id;evidence.thread_url=one.thread_url;
|
|
75
|
+
evidence.mvp1={status:'PASS',thread_id:one.thread_id,verified_by:one.verified_by};
|
|
76
|
+
record('MVP1_PASS',evidence.mvp1);
|
|
77
|
+
const two=await runDirect('new-turn',{
|
|
78
|
+
thread_id:one.thread_id,
|
|
79
|
+
message:`${tag}_MVP2_DIRECT_TURN. Reply exactly ${tag}_MVP2_ACK.`,
|
|
80
|
+
});
|
|
81
|
+
assert.equal(two.thread_id,one.thread_id,'new-turn redirected to another thread');
|
|
82
|
+
assert.equal(two.verified_by,'send-clicked','new-turn must be confirmed by exactly one Send click');
|
|
83
|
+
evidence.mvp2={status:'PASS',thread_id:two.thread_id,verified_by:two.verified_by};
|
|
84
|
+
record('MVP2_PASS',evidence.mvp2);
|
|
85
|
+
await ipc('stop',{session_id:sid});
|
|
86
|
+
record('direct_session_released',{session_id:sid});
|
|
87
|
+
sid=null;
|
|
88
|
+
// Two distinct messages under one FIFO group; explicitly disable merge.
|
|
89
|
+
const payloads=['A','B'].map(suffix=>({
|
|
90
|
+
thread_id:one.thread_id,
|
|
91
|
+
message:`${tag}_MVP3_QUEUE_${suffix}. Reply exactly ${tag}_MVP3_${suffix}_ACK.`,
|
|
92
|
+
idempotency_key:`${tag}-mvp3-${suffix}`,mergeable:false,
|
|
93
|
+
}));
|
|
94
|
+
let enqueued;
|
|
95
|
+
if(isolatedManual) {
|
|
96
|
+
// This is the actual generic queue implementation (not a mocked worker)
|
|
97
|
+
// delivering through the existing real daemon. Isolated on a disposable
|
|
98
|
+
// SQLite database, never reading/claiming the old ChatGPT queue #281/#282.
|
|
99
|
+
// It is NOT a substitute for the live daemon queue-enqueue RPC cutover.
|
|
100
|
+
storeDir=mkdtempSync(join(tmpdir(),'webhelm-mvp-manual-'));
|
|
101
|
+
const policy=(await import(pathToFileURL(join(actionsRoot,'chatgpt/queues/new-turn.mjs')).href)).default;
|
|
102
|
+
temporaryQueue=new PlatformDeliveryQueue({platform:'chatgpt',queue:'new-turn',definition:policy,
|
|
103
|
+
persistenceRoot:storeDir,
|
|
104
|
+
startSession:async ({url,workspace})=>{
|
|
105
|
+
const session=await ipc('start',{url,workspace});
|
|
106
|
+
if(session.session_id)evidence.session_ids.push(session.session_id);
|
|
107
|
+
return session;
|
|
108
|
+
},
|
|
109
|
+
stopSession:async session_id=>ipc('stop',{session_id}),
|
|
110
|
+
runAction:async ({platform,action,config,session_id})=>ipc('platform-run',{
|
|
111
|
+
platform,action:action==='validate_new_turn_ready' ? 'validate-new-turn-ready' : action,
|
|
112
|
+
config,session_id,workspace:'WebHelm',
|
|
113
|
+
}),
|
|
114
|
+
});
|
|
115
|
+
enqueued=payloads.map(x=>temporaryQueue.enqueue(x));
|
|
116
|
+
} else {
|
|
117
|
+
enqueued=[];
|
|
118
|
+
for(const config of payloads) enqueued.push(await ipc('queue-enqueue',{
|
|
119
|
+
platform:'chatgpt',queue:'new-turn',config,
|
|
120
|
+
}));
|
|
121
|
+
}
|
|
122
|
+
assert.equal(new Set(enqueued.map(x=>x.queue_id)).size,2,'two requests must not merge');
|
|
123
|
+
for(const outcome of enqueued) {
|
|
124
|
+
assert.equal(outcome.group,one.thread_id,'both actions must have same FIFO group');
|
|
125
|
+
}
|
|
126
|
+
record('MVP3_QUEUED',{queue_ids:enqueued.map(x=>x.queue_id),group:one.thread_id});
|
|
127
|
+
const dbPath=isolatedManual?temporaryQueue.dbPath:join(
|
|
128
|
+
process.env.WEBHELM_RUNTIME_DIR||RUNTIME_DIR,'queues/chatgpt/new-turn.sqlite3');
|
|
129
|
+
const deadline=Date.now()+180000;
|
|
130
|
+
const states=new Map();
|
|
131
|
+
const claimed=[];
|
|
132
|
+
while(Date.now()<deadline) {
|
|
133
|
+
if(isolatedManual) {
|
|
134
|
+
const next=temporaryQueue.claim(`mvp-worker-${randomUUID()}`);
|
|
135
|
+
if(next) {
|
|
136
|
+
claimed.push(next.id);
|
|
137
|
+
await temporaryQueue.process(next);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const db=isolatedManual?temporaryQueue.db:new DatabaseSync(dbPath,{readOnly:true});
|
|
141
|
+
try {
|
|
142
|
+
for(const id of enqueued.map(x=>x.queue_id)) {
|
|
143
|
+
const row=db.prepare('SELECT id,seq,group_key,state,receipt,attempts FROM items WHERE id=?').get(id);
|
|
144
|
+
if(row) states.set(id,row);
|
|
145
|
+
}
|
|
146
|
+
} finally {if(!isolatedManual)db.close();}
|
|
147
|
+
const rows=enqueued.map(x=>states.get(x.queue_id));
|
|
148
|
+
if(rows.some(x=>x?.state==='FAILED'||x?.state==='CANCELLED')) throw Error('MVP3 queue failure: '+JSON.stringify(rows));
|
|
149
|
+
if(rows.every(x=>x?.state==='SENT')) break;
|
|
150
|
+
await sleep(2000);
|
|
151
|
+
}
|
|
152
|
+
const a=states.get(enqueued[0].queue_id),b=states.get(enqueued[1].queue_id);
|
|
153
|
+
assert.ok(a&&b,'missing persisted queue receipts');
|
|
154
|
+
assert.equal(a.group_key,one.thread_id);
|
|
155
|
+
assert.equal(b.group_key,one.thread_id);
|
|
156
|
+
assert.ok(a.seq<b.seq,'FIFO seq order reversed');
|
|
157
|
+
assert.equal(a.state,'SENT','queue item A was not sent');
|
|
158
|
+
assert.equal(b.state,'SENT','queue item B was not sent');
|
|
159
|
+
assert.equal(a.receipt,'send-clicked');
|
|
160
|
+
assert.equal(b.receipt,'send-clicked');
|
|
161
|
+
if(isolatedManual)assert.deepEqual(claimed,enqueued.map(x=>x.queue_id),'queue processing order violated');
|
|
162
|
+
evidence.mvp3={status:'PASS',same_thread:one.thread_id,queue_ids:enqueued.map(x=>x.queue_id),
|
|
163
|
+
states:[a.state,b.state],receipts:[a.receipt,b.receipt],
|
|
164
|
+
ordered_seq:[a.seq,b.seq],isolated_harness:isolatedManual};
|
|
165
|
+
record('MVP3_PASS',evidence.mvp3);
|
|
166
|
+
// Let any returned-to-idle queue Session disappear before claiming cleanup.
|
|
167
|
+
for(let i=0;i<10;i++) {
|
|
168
|
+
const remaining=(await sessions()).filter(x=>!existing.has(x.session_id));
|
|
169
|
+
if(!remaining.length) break;
|
|
170
|
+
await sleep(1000);
|
|
171
|
+
}
|
|
172
|
+
const leftovers=(await sessions()).filter(x=>!existing.has(x.session_id));
|
|
173
|
+
assert.equal(leftovers.length,0,'owned Sessions not cleaned: '+JSON.stringify(leftovers));
|
|
174
|
+
evidence.pass=true;
|
|
175
|
+
record('ALL_3_MVPS_PASS',{thread_url:evidence.thread_url,real_browser:true,
|
|
176
|
+
live_daemon_queue:!isolatedManual});
|
|
177
|
+
} catch(error) {
|
|
178
|
+
evidence.error=String(error);
|
|
179
|
+
record('MVP_FAILED',{error:String(error)});
|
|
180
|
+
process.exitCode=1;
|
|
181
|
+
} finally {
|
|
182
|
+
if(sid) {
|
|
183
|
+
try {await ipc('stop',{session_id:sid});record('finally_stopped_session',{session_id:sid});}
|
|
184
|
+
catch(error) {record('session_release_error',{error:String(error)});process.exitCode=1;}
|
|
185
|
+
}
|
|
186
|
+
if(temporaryQueue) {
|
|
187
|
+
await temporaryQueue.shutdown();
|
|
188
|
+
// Store only sanitized evidence outside the repository, never prompts.
|
|
189
|
+
if(storeDir)rmSync(storeDir,{recursive:true,force:true});
|
|
190
|
+
}
|
|
191
|
+
record('finish',{pass:evidence.pass,evidence_file:evidenceFile});
|
|
192
|
+
}
|