webhelm 1.0.48 → 1.0.49
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 +1 -1
- 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/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
|
+
}
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
// Browser-side upload source for the existing WebHelm owned Session.
|
|
2
|
-
// Pure string generation; JSON encoding protects filenames and selector quotes.
|
|
3
|
-
const SELECTOR_JS = "(() => ['#upload-files','#upload-media','input[name=\"upload-media\"]','input[type=\"file\"]'].find(s=>document.querySelector(s))||null)()";
|
|
4
|
-
const OPEN_JS = "(() => {const b=[...document.querySelectorAll('button')].find(b=>(b.getAttribute('aria-label')||'').trim()==='Add files and more');if(b)b.click();return !!b;})()";
|
|
5
|
-
const STATE_JS = "(() => ({names:[...document.querySelectorAll('button[aria-label^=\"Remove \"]')].map(b=>(b.getAttribute('aria-label')||'').replace(/^Remove file\\s+\\d+:\\s*/,'').replace(/^Remove\\s+/,'')),pending:[...document.querySelectorAll('[role=\"progressbar\"],[aria-busy=\"true\"],[data-state=\"loading\"]')].some(e=>e.getClientRects().length>0)}))()";
|
|
6
|
-
|
|
7
|
-
export function attachmentUploadScript(paths) {
|
|
8
|
-
if (!Array.isArray(paths) || !paths.length) return "({ready:true})";
|
|
9
|
-
return [
|
|
10
|
-
"return await (async()=>{",
|
|
11
|
-
"const files="+JSON.stringify(paths)+";",
|
|
12
|
-
"const locate=()=>js("+JSON.stringify(SELECTOR_JS)+");",
|
|
13
|
-
"let input=await locate();",
|
|
14
|
-
"if(!input){",
|
|
15
|
-
" await js("+JSON.stringify(OPEN_JS)+");",
|
|
16
|
-
" for(let i=0;i<40&&!input;i++){await sleep(150);input=await locate();}",
|
|
17
|
-
"}",
|
|
18
|
-
"if(!input)throw Error('ChatGPT file input unavailable');",
|
|
19
|
-
"const names=[];",
|
|
20
|
-
"for(const file of files){",
|
|
21
|
-
" await upload_file(input,file);",
|
|
22
|
-
" const name=file.split('/').pop();names.push(name);",
|
|
23
|
-
" const expected=names.filter(n=>n===name).length;",
|
|
24
|
-
" let ready=false;",
|
|
25
|
-
" for(let i=0;i<480;i++){",
|
|
26
|
-
" const state=await js("+JSON.stringify(STATE_JS)+");",
|
|
27
|
-
" if(!state.pending&&state.names.filter(n=>n===name).length>=expected){ready=true;break;}",
|
|
28
|
-
" await sleep(250);",
|
|
29
|
-
" }",
|
|
30
|
-
" if(!ready)throw Error('ChatGPT attachment upload not confirmed: '+name);",
|
|
31
|
-
"}",
|
|
32
|
-
"return {ready:true,names};",
|
|
33
|
-
"})()",
|
|
34
|
-
].join("\n");
|
|
35
|
-
}
|
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import { appendFile, mkdir } from "node:fs/promises";
|
|
2
|
-
import { dirname, join } from "node:path";
|
|
3
|
-
import { homedir } from "node:os";
|
|
4
|
-
import { randomUUID } from "node:crypto";
|
|
5
|
-
const patterns = [
|
|
6
|
-
[
|
|
7
|
-
"conversation_too_long",
|
|
8
|
-
/conversation_too_long|conversation is too long to continue|conversation too long/i,
|
|
9
|
-
],
|
|
10
|
-
[
|
|
11
|
-
"thread_load_failed",
|
|
12
|
-
/thread_load_failed|could not load this chatgpt conversation|failed to load conversation/i,
|
|
13
|
-
],
|
|
14
|
-
[
|
|
15
|
-
"authentication_required",
|
|
16
|
-
/login required|log in to chatgpt|session expired|sign in to chatgpt/i,
|
|
17
|
-
],
|
|
18
|
-
["rate_limited", /rate.limit|too many requests|http 429|usage limit/i],
|
|
19
|
-
[
|
|
20
|
-
"invalid_thread_id",
|
|
21
|
-
/invalid thread.id|thread.id is required|malformed thread/i,
|
|
22
|
-
],
|
|
23
|
-
["thread_redirect_mismatch", /thread redirect mismatch/i],
|
|
24
|
-
[
|
|
25
|
-
"conversation_busy",
|
|
26
|
-
/conversation is busy|turn completion.*not observed ready/i,
|
|
27
|
-
],
|
|
28
|
-
[
|
|
29
|
-
"send_not_ready",
|
|
30
|
-
/lifecycle continuation readiness was not observed ready|send button.*disabled/i,
|
|
31
|
-
],
|
|
32
|
-
["composer_not_found", /composer.*not observed ready|composer.*not found/i],
|
|
33
|
-
["composer_input_failed", /composer rejected|input failed|prompt.*mismatch/i],
|
|
34
|
-
["send_click_failed", /send button changed before|send button.*click/i],
|
|
35
|
-
[
|
|
36
|
-
"submission_unverified",
|
|
37
|
-
/submission.*not observed|post.submit.*unverified|cleared composer/i,
|
|
38
|
-
],
|
|
39
|
-
["thread_creation_failed", /did not assign a durable thread id/i],
|
|
40
|
-
["project_not_found", /project not found/i],
|
|
41
|
-
["project_access_denied", /project.*access denied|permission.*project/i],
|
|
42
|
-
["attachment_failed", /attachment.*failed|upload.*failed/i],
|
|
43
|
-
[
|
|
44
|
-
"attachment_processing_timeout",
|
|
45
|
-
/attachment.*timeout|attachment.*not observed ready/i,
|
|
46
|
-
],
|
|
47
|
-
["session_unavailable", /unknown session|session not found|session.*closed/i],
|
|
48
|
-
[
|
|
49
|
-
"browser_unavailable",
|
|
50
|
-
/chrome.*unavailable|cdp.*disconnect|daemon.*unreachable/i,
|
|
51
|
-
],
|
|
52
|
-
["execution_timeout", /timed out|timeout|runtime.evaluate/i],
|
|
53
|
-
];
|
|
54
|
-
export function classify(error) {
|
|
55
|
-
const raw = String(error || "");
|
|
56
|
-
const code = patterns.find(([, re]) => re.test(raw))?.[0] ||
|
|
57
|
-
"delivery_failed";
|
|
58
|
-
const messages = {
|
|
59
|
-
send_not_ready: "Prompt entered, but Send button did not become ready",
|
|
60
|
-
thread_load_failed: "ChatGPT conversation could not be loaded",
|
|
61
|
-
conversation_too_long: "Conversation is too long to continue",
|
|
62
|
-
submission_unverified: "Submission could not be confirmed",
|
|
63
|
-
};
|
|
64
|
-
return {
|
|
65
|
-
ok: false,
|
|
66
|
-
code,
|
|
67
|
-
message: messages[code] ||
|
|
68
|
-
code.replaceAll("_", " ").replace(/^./, (c) => c.toUpperCase()),
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
export async function normalizeFailure(
|
|
72
|
-
result,
|
|
73
|
-
action,
|
|
74
|
-
{
|
|
75
|
-
logPath = join(
|
|
76
|
-
homedir(),
|
|
77
|
-
".config/webhelm/runtime/chatgpt-delivery-errors.jsonl",
|
|
78
|
-
),
|
|
79
|
-
} = {},
|
|
80
|
-
) {
|
|
81
|
-
if (result?.ok !== false) return result;
|
|
82
|
-
const raw = String(result.stderr || result.error || "");
|
|
83
|
-
const diagnostic_id = randomUUID().replaceAll("-", "");
|
|
84
|
-
try {
|
|
85
|
-
await mkdir(dirname(logPath), { recursive: true });
|
|
86
|
-
await appendFile(
|
|
87
|
-
logPath,
|
|
88
|
-
JSON.stringify({ diagnostic_id, action, error: raw }) + "\n",
|
|
89
|
-
);
|
|
90
|
-
} catch {}
|
|
91
|
-
const normalized = classify(raw);
|
|
92
|
-
if ("cleanup" in result) normalized.cleanup = result.cleanup;
|
|
93
|
-
return normalized;
|
|
94
|
-
}
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
export const PROMPT_FILE_THRESHOLD = 2000;
|
|
2
|
-
export const PROMPT_FILE_MESSAGE = 'Read prompt.md and execute the task in that file.';
|
|
3
|
-
|
|
4
|
-
// Optional caller-supplied per-request constraints. No service-specific tags,
|
|
5
|
-
// response IDs, or protocol parsing belong in WebHelm.
|
|
6
|
-
export function enforcementContext(value = '') {
|
|
7
|
-
if (value === undefined || value === null || value === '') return '';
|
|
8
|
-
if (typeof value !== 'string' || !value.trim() || value.length > 1500 ||
|
|
9
|
-
value.includes('</top-instructions>')) {
|
|
10
|
-
throw new TypeError('enforcement_context must be a non-empty string of at most 1500 characters without closing tag');
|
|
11
|
-
}
|
|
12
|
-
return `<top-instructions>\n${value}\n</top-instructions>`;
|
|
13
|
-
}
|
|
14
|
-
export function fullDeliveryMessage(message, context = '') {
|
|
15
|
-
const header = enforcementContext(context);
|
|
16
|
-
return (header ? header+'\n\n' : '') + message;
|
|
17
|
-
}
|
|
18
|
-
export function requiresPromptFile(message, context = '') {
|
|
19
|
-
return fullDeliveryMessage(message, context).length > PROMPT_FILE_THRESHOLD;
|
|
20
|
-
}
|
|
21
|
-
export function deliveryMessage(message, context = '') {
|
|
22
|
-
const full = fullDeliveryMessage(message, context);
|
|
23
|
-
if (full.length <= PROMPT_FILE_THRESHOLD) return full;
|
|
24
|
-
const header = enforcementContext(context);
|
|
25
|
-
if (!header) return PROMPT_FILE_MESSAGE;
|
|
26
|
-
const short = header+'\n\n'+PROMPT_FILE_MESSAGE;
|
|
27
|
-
if (short.length > PROMPT_FILE_THRESHOLD) throw new TypeError('enforcement_context exceeds the short message limit');
|
|
28
|
-
return short;
|
|
29
|
-
}
|
|
30
|
-
export function targetUrl(projectId, threadId, message, enforcement_context = '') {
|
|
31
|
-
if (!threadId || !message) {
|
|
32
|
-
throw new Error("thread_id and message are required");
|
|
33
|
-
}
|
|
34
|
-
return "https://chatgpt.com/c/" + encodeURIComponent(threadId) +
|
|
35
|
-
"?" + new URLSearchParams({ prompt: deliveryMessage(message, enforcement_context) });
|
|
36
|
-
}
|
|
37
|
-
export const PROBE_JS = `(() => {
|
|
38
|
-
const visible = e => !!e && !!e.getClientRects().length && getComputedStyle(e).visibility !== 'hidden';
|
|
39
|
-
const body = (document.body?.innerText || '').toLowerCase();
|
|
40
|
-
if (body.includes('could not load this chatgpt conversation'))
|
|
41
|
-
return {state: 'BLOCKED', error: 'thread_load_failed'};
|
|
42
|
-
if (body.includes('log in to chatgpt') || body.includes('sign in to chatgpt'))
|
|
43
|
-
return {state: 'BLOCKED', error: 'authentication_required'};
|
|
44
|
-
const stop = [...document.querySelectorAll('button')].some(b => {
|
|
45
|
-
if (!visible(b)) return false;
|
|
46
|
-
const label = (b.getAttribute('aria-label') || '').trim().toLowerCase();
|
|
47
|
-
const title = (b.getAttribute('title') || '').trim().toLowerCase();
|
|
48
|
-
const testId = (b.getAttribute('data-testid') || '').trim().toLowerCase();
|
|
49
|
-
return ['stop generating', 'stop answering', 'stop response', 'stop'].includes(label) ||
|
|
50
|
-
['stop generating', 'stop answering'].includes(title) ||
|
|
51
|
-
['stop-button', 'stop-generating-button'].includes(testId);
|
|
52
|
-
});
|
|
53
|
-
if (stop) return {state: 'RUNNING', stop_visible: true};
|
|
54
|
-
const e = [...document.querySelectorAll('#prompt-textarea,[contenteditable="true"][data-lexical-editor="true"],[role="textbox"][contenteditable="true"],textarea')].find(visible);
|
|
55
|
-
const editable = e?.getAttribute?.('contenteditable') === 'true';
|
|
56
|
-
// ProseMirror uses <p> for each visual line, including empty lines.
|
|
57
|
-
// e.textContent and, in some Chrome builds, e.innerText omit those line
|
|
58
|
-
// boundaries, so a correctly prefilled multiline prompt never matches.
|
|
59
|
-
const paragraphs = editable ? [...e.children] : [];
|
|
60
|
-
const composerText = editable && paragraphs.length && paragraphs.every(p => p.tagName === 'P')
|
|
61
|
-
? paragraphs.map(p => p.textContent || '').join('\\n')
|
|
62
|
-
: editable ? (e.innerText || e.textContent || '') : (e?.value || e?.textContent || e?.innerText || '');
|
|
63
|
-
return {state: visible(e) ? 'READY' : 'NOT_READY', stop_visible: false, composer_text: composerText};
|
|
64
|
-
})()`;
|
|
65
|
-
export function classifyProbe(observedUrl, expectedUrl, state) {
|
|
66
|
-
const actual = new URL(observedUrl), expected = new URL(expectedUrl);
|
|
67
|
-
const thread = url => {
|
|
68
|
-
const match = url.pathname.split('/c/')[1]?.split('/')[0] || null;
|
|
69
|
-
return match ? decodeURIComponent(match) : null;
|
|
70
|
-
};
|
|
71
|
-
if (actual.protocol !== "https:" || actual.host !== "chatgpt.com" ||
|
|
72
|
-
!thread(actual) || thread(actual) !== thread(expected)) return "BLOCKED";
|
|
73
|
-
if (["RUNNING", "BLOCKED"].includes(state?.state)) return state.state;
|
|
74
|
-
const prompt = expected.searchParams.get("prompt") || "";
|
|
75
|
-
const normalize = text => String(text || "").replace(/\s+/g, " ").trim();
|
|
76
|
-
if (actual.search && actual.searchParams.get("prompt") !== prompt) return "NOT_READY";
|
|
77
|
-
return state?.state === "READY" && normalize(state.composer_text) === normalize(prompt)
|
|
78
|
-
? "READY"
|
|
79
|
-
: "NOT_READY";
|
|
80
|
-
}
|