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
|
@@ -1,374 +0,0 @@
|
|
|
1
|
-
import { DatabaseSync } from "node:sqlite";
|
|
2
|
-
import { mkdirSync, mkdtempSync, writeFileSync, rmSync, existsSync, statSync } from "node:fs";
|
|
3
|
-
import { join, resolve, isAbsolute } from "node:path";
|
|
4
|
-
import { tmpdir } from "node:os";
|
|
5
|
-
import { attachmentUploadScript } from "./attachment-upload.mjs";
|
|
6
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
7
|
-
import { classifyProbe, PROBE_JS, targetUrl, deliveryMessage, requiresPromptFile, enforcementContext } from "./chatgpt-probe.mjs";
|
|
8
|
-
import { SEND_ENABLED_JS } from "./lifecycle-common.mjs";
|
|
9
|
-
import { submissionScript } from "./submission-script.mjs";
|
|
10
|
-
import { DurableQueueCore } from "../durable-queue-core.mjs";
|
|
11
|
-
|
|
12
|
-
const transitions = new Set([
|
|
13
|
-
"CHECKING>WAITING",
|
|
14
|
-
"CHECKING>SENDING",
|
|
15
|
-
"CHECKING>BLOCKED",
|
|
16
|
-
"SENDING>SENT",
|
|
17
|
-
"SENDING>WAITING",
|
|
18
|
-
"SENDING>UNCERTAIN",
|
|
19
|
-
"UNCERTAIN>SENT",
|
|
20
|
-
"UNCERTAIN>WAITING",
|
|
21
|
-
"BLOCKED>WAITING",
|
|
22
|
-
]);
|
|
23
|
-
|
|
24
|
-
// ChatGPT owns its legacy turns/merged_requests schema and all turn payload,
|
|
25
|
-
// idempotency, merge, FIFO partition, and recovery semantics.
|
|
26
|
-
const chatgptQueuePolicy = {
|
|
27
|
-
one(db, sql, ...args) { return db.prepare(sql).get(...args) || null; },
|
|
28
|
-
rows(db) { return db.prepare("SELECT * FROM turns ORDER BY seq").all(); },
|
|
29
|
-
enqueue(db, request = {}, now) {
|
|
30
|
-
const {thread_id, message, idempotency_key, idempotencyKey, project_id=null, mergeable=false, file=[], enforcement_context:rawContext=''} = request;
|
|
31
|
-
const enforcement_context=rawContext??'';
|
|
32
|
-
enforcementContext(enforcement_context);
|
|
33
|
-
if (!Array.isArray(file) || file.length > 4 ||
|
|
34
|
-
file.some(p => typeof p !== "string" || !isAbsolute(p) ||
|
|
35
|
-
!existsSync(p) || !statSync(p).isFile())) {
|
|
36
|
-
throw new TypeError("file must contain at most 4 existing absolute file paths");
|
|
37
|
-
}
|
|
38
|
-
if (file.length && mergeable) throw new TypeError("attachment turns cannot merge");
|
|
39
|
-
const filesJson = JSON.stringify(file);
|
|
40
|
-
const key=idempotency_key ?? idempotencyKey;
|
|
41
|
-
if (!thread_id || (!message && !file.length) || !key) throw new TypeError("thread_id, message, idempotency_key required");
|
|
42
|
-
if (typeof mergeable !== "boolean") throw new TypeError("mergeable must be a boolean");
|
|
43
|
-
const merged=this.one(db, "SELECT * FROM merged_requests WHERE idem_key=?", key);
|
|
44
|
-
if (merged) {
|
|
45
|
-
const row=this.one(db, "SELECT * FROM turns WHERE id=?", merged.queue_id);
|
|
46
|
-
if (merged.thread_id!==thread_id || merged.message!==message || merged.project_id!==project_id || filesJson!=="[]" || row.enforcement_context!==enforcement_context) throw new Error("idempotency key reused with different payload");
|
|
47
|
-
return {ok:true,status:"queued",queue_id:row.id,thread_id:row.thread_id,state:row.state};
|
|
48
|
-
}
|
|
49
|
-
const same=this.one(db, "SELECT * FROM turns WHERE idem_key=?", key);
|
|
50
|
-
if (same) {
|
|
51
|
-
if (same.thread_id!==thread_id || same.message!==message || same.project_id!==project_id || same.enforcement_context!==enforcement_context || (same.files_json||"[]")!==filesJson) throw new Error("idempotency key reused with different payload");
|
|
52
|
-
return {ok:true,status:"queued",queue_id:same.id,thread_id:same.thread_id,state:same.state};
|
|
53
|
-
}
|
|
54
|
-
const tail=mergeable ? this.one(db, "SELECT * FROM turns WHERE thread_id=? ORDER BY seq DESC LIMIT 1", thread_id) : null;
|
|
55
|
-
// WAITING denotes admitted work being retried; only QUEUED is cancellable
|
|
56
|
-
// and eligible for a new enqueue-time merge.
|
|
57
|
-
if (tail && tail.mergeable && tail.project_id===project_id && tail.enforcement_context===enforcement_context && tail.state==="QUEUED") {
|
|
58
|
-
db.prepare("INSERT OR IGNORE INTO merged_requests VALUES(?,?,?,?,?)").run(tail.idem_key,tail.project_id,thread_id,tail.message,tail.id);
|
|
59
|
-
db.prepare("INSERT INTO merged_requests VALUES(?,?,?,?,?)").run(key,project_id,thread_id,message,tail.id);
|
|
60
|
-
db.prepare("UPDATE turns SET message=message || ? WHERE id=?").run("\n"+message,tail.id);
|
|
61
|
-
const row=this.one(db, "SELECT * FROM turns WHERE id=?", tail.id);
|
|
62
|
-
return {ok:true,status:"queued",queue_id:row.id,thread_id:row.thread_id,state:row.state};
|
|
63
|
-
}
|
|
64
|
-
const id=randomUUID();
|
|
65
|
-
db.prepare("INSERT INTO turns(id,idem_key,project_id,thread_id,message,enforcement_context,state,next_check_at,created_at,mergeable,files_json) VALUES(?,?,?,?,?,?,'QUEUED',?,?,?,?)").run(id,key,project_id,thread_id,message,enforcement_context,now,now,mergeable?1:0,filesJson);
|
|
66
|
-
return {ok:true,status:"queued",queue_id:id,thread_id,state:"QUEUED"};
|
|
67
|
-
},
|
|
68
|
-
claim(db, owner, now, leaseSeconds) {
|
|
69
|
-
db.prepare("UPDATE turns SET state='UNCERTAIN',lease_owner=NULL,lease_until=NULL WHERE state='SENDING' AND lease_until<=?").run(now);
|
|
70
|
-
db.prepare("UPDATE turns SET state='WAITING',lease_owner=NULL,lease_until=NULL,next_check_at=? WHERE state='CHECKING' AND lease_until<=?").run(now,now);
|
|
71
|
-
// BLOCKED is a pre-send failure. Retry after cooldown so a transient
|
|
72
|
-
// login or redirect cannot permanently starve all later turns in a thread.
|
|
73
|
-
// UNCERTAIN remains excluded: that turn might already have been sent.
|
|
74
|
-
db.prepare("UPDATE turns SET state='WAITING',lease_owner=NULL,lease_until=NULL,next_check_at=? WHERE state='BLOCKED' AND next_check_at<=?").run(now,now);
|
|
75
|
-
const row=this.one(db, `SELECT t.* FROM turns t WHERE t.state IN ('QUEUED','WAITING') AND t.next_check_at<=? AND NOT EXISTS(SELECT 1 FROM turns older WHERE older.thread_id=t.thread_id AND older.seq<t.seq AND (older.state NOT IN ('SENT','CANCELLED') OR (older.state='SENT' AND older.next_check_at>?))) ORDER BY t.seq LIMIT 1`,now,now);
|
|
76
|
-
if (!row) return null;
|
|
77
|
-
db.prepare("UPDATE turns SET state='CHECKING',lease_owner=?,lease_until=?,attempts=attempts+1 WHERE id=?").run(owner,now+leaseSeconds,row.id);
|
|
78
|
-
return this.one(db, "SELECT * FROM turns WHERE id=?", row.id);
|
|
79
|
-
},
|
|
80
|
-
// A queue adapter registers a display description; Actions stay unaware of queues.
|
|
81
|
-
describe(row) {
|
|
82
|
-
const firstLine = row.message.split(/\r?\n/, 1)[0].replace(/\s+/g, ' ').trim();
|
|
83
|
-
const title = firstLine ? (firstLine.length > 52 ? `${firstLine.slice(0, 51)}…` : firstLine) : 'ChatGPT message';
|
|
84
|
-
const prefix = row.project_id ? `/g/${encodeURIComponent(row.project_id)}` : '';
|
|
85
|
-
return {platform:'ChatGPT', title, url:`https://chatgpt.com${prefix}/c/${encodeURIComponent(row.thread_id)}`};
|
|
86
|
-
},
|
|
87
|
-
cancel(db, id) {
|
|
88
|
-
const row=this.one(db, "SELECT * FROM turns WHERE id=?", id);
|
|
89
|
-
if (!row) return {ok:false,queue_id:id,error:"queue item not found"};
|
|
90
|
-
if (!["QUEUED","WAITING","BLOCKED","UNCERTAIN"].includes(row.state)) return {ok:false,queue_id:id,state:row.state,error:"cannot remove a running or completed item"};
|
|
91
|
-
db.prepare("UPDATE turns SET state='CANCELLED',lease_owner=NULL,lease_until=NULL WHERE id=? AND state IN ('QUEUED','WAITING','BLOCKED','UNCERTAIN')").run(id);
|
|
92
|
-
return {ok:true,queue_id:id,state:"CANCELLED"};
|
|
93
|
-
},
|
|
94
|
-
list(db) {
|
|
95
|
-
return {ok:true,items:this.rows(db).filter(row=>!["SENT","CANCELLED"].includes(row.state)).map(({id,thread_id,state,attempts,created_at,receipt})=>({id,queue_id:id,thread_id,state,attempts,created_at,receipt}))};
|
|
96
|
-
},
|
|
97
|
-
};
|
|
98
|
-
|
|
99
|
-
export class ChatGPTQueue extends DurableQueueCore {
|
|
100
|
-
constructor(
|
|
101
|
-
{
|
|
102
|
-
persistenceRoot,
|
|
103
|
-
startSession,
|
|
104
|
-
execSession,
|
|
105
|
-
stopSession,
|
|
106
|
-
intervalMs = 10000,
|
|
107
|
-
concurrency = 4,
|
|
108
|
-
leaseSeconds = 120,
|
|
109
|
-
now = () => Date.now() / 1000,
|
|
110
|
-
logger = () => {},
|
|
111
|
-
} = {},
|
|
112
|
-
) {
|
|
113
|
-
if (!persistenceRoot) throw new TypeError("persistenceRoot is required");
|
|
114
|
-
for (
|
|
115
|
-
const [name, fn] of Object.entries({
|
|
116
|
-
startSession,
|
|
117
|
-
execSession,
|
|
118
|
-
stopSession,
|
|
119
|
-
})
|
|
120
|
-
) {
|
|
121
|
-
if (typeof fn !== "function") {
|
|
122
|
-
throw new TypeError(`${name} callback is required`);
|
|
123
|
-
}
|
|
124
|
-
}
|
|
125
|
-
const root = resolve(persistenceRoot);
|
|
126
|
-
mkdirSync(root, { recursive: true });
|
|
127
|
-
const dbPath = join(root, "chatgpt-new-turn.sqlite3");
|
|
128
|
-
const db = new DatabaseSync(dbPath);
|
|
129
|
-
db.exec(
|
|
130
|
-
"PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA busy_timeout=5000",
|
|
131
|
-
);
|
|
132
|
-
db.exec(
|
|
133
|
-
`CREATE TABLE IF NOT EXISTS turns(seq INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT NOT NULL UNIQUE,idem_key TEXT NOT NULL UNIQUE,project_id TEXT,thread_id TEXT NOT NULL,message TEXT NOT NULL,state TEXT NOT NULL,lease_owner TEXT,lease_until REAL,next_check_at REAL NOT NULL,created_at REAL NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,receipt TEXT,mergeable INTEGER NOT NULL DEFAULT 0); CREATE INDEX IF NOT EXISTS turns_thread_order ON turns(thread_id,seq); CREATE TABLE IF NOT EXISTS merged_requests(idem_key TEXT PRIMARY KEY,project_id TEXT,thread_id TEXT NOT NULL,message TEXT NOT NULL,queue_id TEXT NOT NULL);`,
|
|
134
|
-
);
|
|
135
|
-
const columns = db.prepare("PRAGMA table_info(turns)").all().map(row=>row.name);
|
|
136
|
-
if (!columns.includes('files_json'))
|
|
137
|
-
db.exec("ALTER TABLE turns ADD COLUMN files_json TEXT NOT NULL DEFAULT '[]'");
|
|
138
|
-
if (!columns.includes('enforcement_context'))
|
|
139
|
-
db.exec("ALTER TABLE turns ADD COLUMN enforcement_context TEXT NOT NULL DEFAULT ''");
|
|
140
|
-
super(db, chatgptQueuePolicy, now, {
|
|
141
|
-
concurrency: Math.min(4, Math.max(1, Number(concurrency) || 4)), intervalMs,
|
|
142
|
-
});
|
|
143
|
-
this.root = root;
|
|
144
|
-
this.dbPath = dbPath;
|
|
145
|
-
this.db = db;
|
|
146
|
-
this.startSession = startSession;
|
|
147
|
-
this.execSession = execSession;
|
|
148
|
-
this.stopSession = stopSession;
|
|
149
|
-
this.leaseSeconds = leaseSeconds;
|
|
150
|
-
this.logger = logger;
|
|
151
|
-
this.sessions = new Map();
|
|
152
|
-
}
|
|
153
|
-
enqueue(request) {
|
|
154
|
-
const result = super.enqueue(request);
|
|
155
|
-
if (this.started) this._wake(0);
|
|
156
|
-
return result;
|
|
157
|
-
}
|
|
158
|
-
_one(sql, ...args) { return this.db.prepare(sql).get(...args) || null; }
|
|
159
|
-
claim(owner, now = this.now()) { return super.claim(owner, now, this.leaseSeconds); }
|
|
160
|
-
transition(
|
|
161
|
-
id,
|
|
162
|
-
owner,
|
|
163
|
-
source,
|
|
164
|
-
target,
|
|
165
|
-
{ now = this.now(), delay = 60, receipt = null } = {},
|
|
166
|
-
) {
|
|
167
|
-
if (!transitions.has(`${source}>${target}`)) {
|
|
168
|
-
throw new Error("invalid transition");
|
|
169
|
-
}
|
|
170
|
-
if (source === "UNCERTAIN" && !receipt) {
|
|
171
|
-
throw new Error("UNCERTAIN requires reconciliation evidence");
|
|
172
|
-
}
|
|
173
|
-
if (source === "BLOCKED" && !receipt) {
|
|
174
|
-
throw new Error("BLOCKED requires unblock evidence");
|
|
175
|
-
}
|
|
176
|
-
return this._transaction(() => {
|
|
177
|
-
const row = this._one("SELECT * FROM turns WHERE id=?", id);
|
|
178
|
-
if (!row || row.state !== source) throw new Error("stale state");
|
|
179
|
-
if (
|
|
180
|
-
["CHECKING", "SENDING"].includes(source) && row.lease_owner !== owner
|
|
181
|
-
) throw new Error("stale owner");
|
|
182
|
-
if (["CHECKING", "SENDING"].includes(source) && row.lease_until <= now) {
|
|
183
|
-
throw new Error("expired lease");
|
|
184
|
-
}
|
|
185
|
-
const release = ["WAITING", "SENT", "UNCERTAIN", "BLOCKED"].includes(
|
|
186
|
-
target,
|
|
187
|
-
);
|
|
188
|
-
this.db.prepare(
|
|
189
|
-
"UPDATE turns SET state=?,lease_owner=?,lease_until=?,next_check_at=?,receipt=? WHERE id=?",
|
|
190
|
-
).run(
|
|
191
|
-
target,
|
|
192
|
-
release ? null : owner,
|
|
193
|
-
release ? null : now + 120,
|
|
194
|
-
["WAITING", "SENT", "BLOCKED"].includes(target) ? now + delay : now,
|
|
195
|
-
receipt,
|
|
196
|
-
id,
|
|
197
|
-
);
|
|
198
|
-
});
|
|
199
|
-
}
|
|
200
|
-
inspect() { return this.list(); }
|
|
201
|
-
reconcile({ queue_id, evidence, accepted } = {}) {
|
|
202
|
-
if (!queue_id || !evidence || typeof accepted !== "boolean") {
|
|
203
|
-
throw new TypeError("queue_id, evidence and boolean accepted required");
|
|
204
|
-
}
|
|
205
|
-
this.transition(
|
|
206
|
-
queue_id,
|
|
207
|
-
"reconciler",
|
|
208
|
-
"UNCERTAIN",
|
|
209
|
-
accepted ? "SENT" : "WAITING",
|
|
210
|
-
{ receipt: evidence, delay: 0 },
|
|
211
|
-
);
|
|
212
|
-
if (this.started) this._wake(0);
|
|
213
|
-
return { ok: true, queue_id, state: accepted ? "SENT" : "WAITING" };
|
|
214
|
-
}
|
|
215
|
-
process(item) { return this._process(item); }
|
|
216
|
-
onDispatchError(error) { this.logger({event:"dispatcher_error",error:String(error)}); }
|
|
217
|
-
async _exec(sid, code) {
|
|
218
|
-
const response = await this.execSession(sid, code);
|
|
219
|
-
if (response?.ok === false) {
|
|
220
|
-
throw new Error(
|
|
221
|
-
response.error || response.stderr || "browser action failed",
|
|
222
|
-
);
|
|
223
|
-
}
|
|
224
|
-
return response?.value ?? response;
|
|
225
|
-
}
|
|
226
|
-
async _probe(item) {
|
|
227
|
-
const url = targetUrl(item.project_id, item.thread_id, item.message, item.enforcement_context);
|
|
228
|
-
const session = await this.startSession({ url });
|
|
229
|
-
const sid = session.session_id ?? session.sessionId;
|
|
230
|
-
if (!sid) throw new Error("session start returned no session_id");
|
|
231
|
-
this.sessions.set(item.id, sid);
|
|
232
|
-
const deadline = Date.now() + 45000;
|
|
233
|
-
let state = "NOT_READY";
|
|
234
|
-
while (Date.now() < deadline) {
|
|
235
|
-
const source =
|
|
236
|
-
`return await (async()=>{ const page=await page_info(); const state=await js(${
|
|
237
|
-
JSON.stringify(PROBE_JS)
|
|
238
|
-
}); if(state?.state==='READY' && !(await js(${
|
|
239
|
-
JSON.stringify(SEND_ENABLED_JS)
|
|
240
|
-
}))) state.state='NOT_READY'; return {url:page.url||'',state}; })()`;
|
|
241
|
-
const result = await this._exec(sid, source);
|
|
242
|
-
state = classifyProbe(result.url, url, result.state);
|
|
243
|
-
if (["READY", "RUNNING", "BLOCKED"].includes(state)) return state;
|
|
244
|
-
await new Promise((resolve) => setTimeout(resolve, 400));
|
|
245
|
-
}
|
|
246
|
-
return state;
|
|
247
|
-
}
|
|
248
|
-
async _send(item) {
|
|
249
|
-
const sid = this.sessions.get(item.id);
|
|
250
|
-
if (!sid) throw new Error("missing prepared browser session");
|
|
251
|
-
const attachments = JSON.parse(item.files_json || "[]");
|
|
252
|
-
let tempDir;
|
|
253
|
-
try {
|
|
254
|
-
if (requiresPromptFile(item.message,item.enforcement_context)) {
|
|
255
|
-
tempDir = mkdtempSync(join(tmpdir(), "webhelm-prompt-"));
|
|
256
|
-
const promptPath = join(tempDir, "prompt.md");
|
|
257
|
-
writeFileSync(promptPath, item.message, {encoding:"utf8",mode:0o600});
|
|
258
|
-
attachments.push(promptPath);
|
|
259
|
-
}
|
|
260
|
-
if (attachments.length) {
|
|
261
|
-
const upload = await this._exec(sid, attachmentUploadScript(attachments));
|
|
262
|
-
if (!upload?.ready) throw new Error("ChatGPT attachments not ready for Send");
|
|
263
|
-
}
|
|
264
|
-
return await this._exec(sid, submissionScript({...item, message:deliveryMessage(item.message,item.enforcement_context)}));
|
|
265
|
-
} finally {
|
|
266
|
-
if (tempDir) rmSync(tempDir, {recursive:true,force:true});
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
async _finish(id) {
|
|
270
|
-
const sid = this.sessions.get(id);
|
|
271
|
-
this.sessions.delete(id);
|
|
272
|
-
if (sid) {
|
|
273
|
-
try {
|
|
274
|
-
await this.stopSession(sid);
|
|
275
|
-
} catch (e) {
|
|
276
|
-
this.logger({ event: "stop_session_error", error: String(e) });
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
_safeDiagnostic(error) {
|
|
281
|
-
const raw = String(error);
|
|
282
|
-
const safe =
|
|
283
|
-
/^(?:workspace\.acquireIdentity|session_identity_timeout|chatgpt_queue_unavailable|daemon_retiring)(?::[A-Za-z0-9_.-]{1,32})?$/
|
|
284
|
-
.test(raw)
|
|
285
|
-
? raw
|
|
286
|
-
: "redacted";
|
|
287
|
-
const fingerprint = createHash("sha256").update(raw).digest("hex").slice(
|
|
288
|
-
0,
|
|
289
|
-
16,
|
|
290
|
-
);
|
|
291
|
-
return `${
|
|
292
|
-
error?.name || "Error"
|
|
293
|
-
};message=${safe};fingerprint=${fingerprint}`.slice(0, 480);
|
|
294
|
-
}
|
|
295
|
-
async _process(item) {
|
|
296
|
-
const owner = item.lease_owner;
|
|
297
|
-
try {
|
|
298
|
-
const state = await this._probe(item);
|
|
299
|
-
if (state === "RUNNING") {
|
|
300
|
-
this.transition(item.id, owner, "CHECKING", "WAITING", {
|
|
301
|
-
delay: this.intervalMs / 1000,
|
|
302
|
-
receipt: "stop_visible",
|
|
303
|
-
});
|
|
304
|
-
return;
|
|
305
|
-
}
|
|
306
|
-
if (state === "BLOCKED") {
|
|
307
|
-
// Recheck pre-send failures with bounded exponential backoff (1m..1h).
|
|
308
|
-
const delay = Math.min(3600, 60 * (2 ** Math.min(6, Math.max(0, item.attempts - 1))));
|
|
309
|
-
this.transition(item.id, owner, "CHECKING", "BLOCKED", {
|
|
310
|
-
receipt: "page blocked", delay,
|
|
311
|
-
});
|
|
312
|
-
this.logger({event: "page_blocked", queue_id: item.id, attempts: item.attempts, retry_in_seconds: delay});
|
|
313
|
-
return;
|
|
314
|
-
}
|
|
315
|
-
if (state !== "READY") {
|
|
316
|
-
this.transition(item.id, owner, "CHECKING", "WAITING", {
|
|
317
|
-
delay: this.intervalMs / 1000,
|
|
318
|
-
receipt: `probe_${state.toLowerCase()}`,
|
|
319
|
-
});
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
this.transition(item.id, owner, "CHECKING", "SENDING");
|
|
323
|
-
const receipt = await this._send(item);
|
|
324
|
-
// These diagnostics are all returned before clicking Send. A safe retry
|
|
325
|
-
// must not block this thread forever as an ambiguous delivery.
|
|
326
|
-
if (["pre_send_gate_not_ready", "send_control_not_found", "thread_redirect_mismatch"]
|
|
327
|
-
.includes(receipt?.diagnostic)) {
|
|
328
|
-
this.transition(item.id, owner, "SENDING", "WAITING", {
|
|
329
|
-
delay: this.intervalMs / 1000,
|
|
330
|
-
receipt: receipt.diagnostic,
|
|
331
|
-
});
|
|
332
|
-
} else if (receipt?.verified_by === "stop-button-visible") {
|
|
333
|
-
// Post-click Stop confirms the reply started; no fixed 60s gap is needed.
|
|
334
|
-
// The next turn is re-probed; RUNNING still blocks overlapping sends.
|
|
335
|
-
this.transition(item.id, owner, "SENDING", "SENT", {
|
|
336
|
-
delay: 0, receipt: receipt.verified_by,
|
|
337
|
-
});
|
|
338
|
-
} else {
|
|
339
|
-
// After any unverified click, keep UNCERTAIN until a read-only check
|
|
340
|
-
// proves that the turn is present or absent; never send twice blindly.
|
|
341
|
-
this.transition(item.id, owner, "SENDING", "UNCERTAIN", {
|
|
342
|
-
receipt: receipt?.diagnostic || "missing_user_turn_receipt",
|
|
343
|
-
});
|
|
344
|
-
}
|
|
345
|
-
} catch (e) {
|
|
346
|
-
const diagnostic = this._safeDiagnostic(e),
|
|
347
|
-
current = this._one("SELECT * FROM turns WHERE id=?", item.id);
|
|
348
|
-
if (current?.state === "SENDING") {
|
|
349
|
-
this.transition(item.id, owner, "SENDING", "UNCERTAIN", {
|
|
350
|
-
receipt: diagnostic,
|
|
351
|
-
});
|
|
352
|
-
} else if (current?.state === "CHECKING") {
|
|
353
|
-
this.transition(item.id, owner, "CHECKING", "WAITING", {
|
|
354
|
-
delay: this.intervalMs / 1000,
|
|
355
|
-
receipt: `probe_error_${diagnostic}`,
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
} finally {
|
|
359
|
-
await this._finish(item.id);
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
async shutdown() {
|
|
363
|
-
if (this.closed) return;
|
|
364
|
-
await this.stopScheduler();
|
|
365
|
-
for (const id of [...this.sessions.keys()]) await this._finish(id);
|
|
366
|
-
this.db.close();
|
|
367
|
-
}
|
|
368
|
-
close() {
|
|
369
|
-
return this.shutdown();
|
|
370
|
-
}
|
|
371
|
-
}
|
|
372
|
-
export function createChatGPTQueue(options) {
|
|
373
|
-
return new ChatGPTQueue(options);
|
|
374
|
-
}
|
|
@@ -1,93 +0,0 @@
|
|
|
1
|
-
import { waitUntilStable } from "./readiness.mjs";
|
|
2
|
-
export const SEND_ENABLED_JS =
|
|
3
|
-
`(() => { const buttons=[...document.querySelectorAll('button[data-testid="send-button"],button[aria-label="Send prompt"],button[aria-label="Send"],form button[type="submit"]')]; const b=buttons.find(e=>e.getClientRects().length>0); return !!b && !b.disabled && b.getAttribute('aria-disabled') !== 'true'; })()`;
|
|
4
|
-
// Only post-click Stop visibility acknowledges queue submission.
|
|
5
|
-
// The same selector family is used to detect ongoing generation before a send.
|
|
6
|
-
export const STOP_VISIBLE_JS = `(() => {
|
|
7
|
-
const visible = b => !!b?.getClientRects().length && getComputedStyle(b).visibility !== 'hidden';
|
|
8
|
-
return [...document.querySelectorAll('button')].some(b => {
|
|
9
|
-
if (!visible(b)) return false;
|
|
10
|
-
const label=(b.getAttribute('aria-label')||'').trim().toLowerCase();
|
|
11
|
-
const title=(b.getAttribute('title')||'').trim().toLowerCase();
|
|
12
|
-
const testId=(b.getAttribute('data-testid')||'').trim().toLowerCase();
|
|
13
|
-
return ['stop generating','stop answering','stop response','stop'].includes(label) ||
|
|
14
|
-
['stop generating','stop answering'].includes(title) ||
|
|
15
|
-
['stop-button','stop-generating-button'].includes(testId);
|
|
16
|
-
});
|
|
17
|
-
})()`;
|
|
18
|
-
export const CLICK_SEND_JS =
|
|
19
|
-
`(() => { const visible=e=>!!e&&!!e.getClientRects().length; const running=[...document.querySelectorAll('button')].some(b=>{ if(!visible(b))return false; const l=(b.getAttribute('aria-label')||'').trim().toLowerCase(),t=(b.getAttribute('title')||'').trim().toLowerCase(),d=(b.getAttribute('data-testid')||'').trim().toLowerCase(); return ['stop generating','stop answering','stop response','stop'].includes(l)||['stop generating','stop answering'].includes(t)||['stop-button','stop-generating-button'].includes(d); }); if(running)return false; const b=document.querySelector('button[data-testid="send-button"],button[aria-label="Send prompt"],button[aria-label="Send"],form button[type="submit"]'); if(!b||b.disabled||b.getAttribute('aria-disabled')==='true')return false; b.click(); return true; })()`;
|
|
20
|
-
export function targetUrl(
|
|
21
|
-
{ project_id, thread_id, temporary = false, prompt } = {},
|
|
22
|
-
) {
|
|
23
|
-
if (temporary && (project_id || thread_id)) {
|
|
24
|
-
throw new Error(
|
|
25
|
-
"temporary cannot be combined with project_id or thread_id",
|
|
26
|
-
);
|
|
27
|
-
}
|
|
28
|
-
const enc = encodeURIComponent;
|
|
29
|
-
const base = temporary
|
|
30
|
-
? "https://chatgpt.com/"
|
|
31
|
-
: thread_id
|
|
32
|
-
? `https://chatgpt.com${project_id ? `/g/${enc(project_id)}` : ""}/c/${
|
|
33
|
-
enc(thread_id)
|
|
34
|
-
}`
|
|
35
|
-
: project_id
|
|
36
|
-
? `https://chatgpt.com/g/${enc(project_id)}/project`
|
|
37
|
-
: "https://chatgpt.com/";
|
|
38
|
-
const params = new URLSearchParams();
|
|
39
|
-
if (temporary) params.set("temporary-chat", "true");
|
|
40
|
-
if (prompt !== undefined) params.set("prompt", prompt);
|
|
41
|
-
return base + (params.size ? `?${params}` : "");
|
|
42
|
-
}
|
|
43
|
-
export function visibleDeliveryError(js) {
|
|
44
|
-
return js(
|
|
45
|
-
`(() => { const as=[...document.querySelectorAll('[role="alert"],[role="status"],[data-sonner-toast],[data-testid*="toast"],[class*="toast"],[class*="error-banner"]')]; for(const e of as){if(!e.getClientRects().length)continue; const t=(e.innerText||'').toLowerCase(); if(t.includes('this conversation is too long to continue')||t.includes('conversation is too long to continue'))return 'conversation_too_long'; if(t.includes('could not load this chatgpt conversation'))return 'thread_load_failed';} if((document.body?.innerText||'').toLowerCase().includes('could not load this chatgpt conversation'))return 'thread_load_failed'; return null; })()`,
|
|
46
|
-
);
|
|
47
|
-
}
|
|
48
|
-
export async function prefilledSubmit(helpers, prompt, { send = true } = {}) {
|
|
49
|
-
const { js } = helpers;
|
|
50
|
-
const sendEnabled = async () => !!(await js(SEND_ENABLED_JS));
|
|
51
|
-
try {
|
|
52
|
-
await waitUntilStable(
|
|
53
|
-
async () => ({ send: await sendEnabled() }),
|
|
54
|
-
(s) => s.send,
|
|
55
|
-
{
|
|
56
|
-
timeout: 15,
|
|
57
|
-
interval: 0.25,
|
|
58
|
-
stableSamples: 3,
|
|
59
|
-
phase: "prefilled Send readiness",
|
|
60
|
-
sleep: helpers.sleep,
|
|
61
|
-
},
|
|
62
|
-
);
|
|
63
|
-
} catch {
|
|
64
|
-
return send
|
|
65
|
-
? Promise.reject(
|
|
66
|
-
new Error("URL-prefilled Send button was not observed ready"),
|
|
67
|
-
)
|
|
68
|
-
: { send_enabled: false };
|
|
69
|
-
}
|
|
70
|
-
if (!send) return { send_enabled: true };
|
|
71
|
-
if (!(await js(CLICK_SEND_JS))) {
|
|
72
|
-
throw new Error("URL-prefilled Send became unavailable before click");
|
|
73
|
-
}
|
|
74
|
-
try {
|
|
75
|
-
await waitUntilStable(
|
|
76
|
-
async () => ({ send_disabled: !(await sendEnabled()) }),
|
|
77
|
-
(s) => s.send_disabled,
|
|
78
|
-
{
|
|
79
|
-
timeout: 30,
|
|
80
|
-
interval: 0.2,
|
|
81
|
-
stableSamples: 2,
|
|
82
|
-
phase: "post-click Send disabled",
|
|
83
|
-
sleep: helpers.sleep,
|
|
84
|
-
},
|
|
85
|
-
);
|
|
86
|
-
} catch {
|
|
87
|
-
const e = new Error("Send did not become disabled after click");
|
|
88
|
-
e.name = "SubmissionVerificationError";
|
|
89
|
-
e.diagnostic = { reason: "post_submit_send_state_unverified" };
|
|
90
|
-
throw e;
|
|
91
|
-
}
|
|
92
|
-
return { verified_by: "send-button-disabled", turn: { id: null } };
|
|
93
|
-
}
|
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
export class SubmissionVerificationError extends Error {
|
|
2
|
-
constructor(message, diagnostic = {}) {
|
|
3
|
-
super(`${message}: ${JSON.stringify(diagnostic)}`);
|
|
4
|
-
this.name = "SubmissionVerificationError";
|
|
5
|
-
this.diagnostic = diagnostic;
|
|
6
|
-
}
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
export function waitUntilStable(
|
|
10
|
-
readState,
|
|
11
|
-
ready,
|
|
12
|
-
{
|
|
13
|
-
timeout = 15,
|
|
14
|
-
interval = 0.25,
|
|
15
|
-
stableSamples = 2,
|
|
16
|
-
phase = "readiness",
|
|
17
|
-
sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
18
|
-
} = {},
|
|
19
|
-
) {
|
|
20
|
-
return (async () => {
|
|
21
|
-
const end = Date.now() + timeout * 1000;
|
|
22
|
-
let stable = 0, previous;
|
|
23
|
-
while (Date.now() < end) {
|
|
24
|
-
let state;
|
|
25
|
-
try {
|
|
26
|
-
state = await readState();
|
|
27
|
-
} catch {
|
|
28
|
-
stable = 0;
|
|
29
|
-
await sleep(interval * 1000);
|
|
30
|
-
continue;
|
|
31
|
-
}
|
|
32
|
-
if (ready(state)) {
|
|
33
|
-
const key = JSON.stringify(state);
|
|
34
|
-
if (key === previous) stable++;
|
|
35
|
-
else {
|
|
36
|
-
previous = key;
|
|
37
|
-
stable = 1;
|
|
38
|
-
}
|
|
39
|
-
if (stable >= stableSamples) return state;
|
|
40
|
-
} else {
|
|
41
|
-
stable = 0;
|
|
42
|
-
previous = undefined;
|
|
43
|
-
}
|
|
44
|
-
await sleep(interval * 1000);
|
|
45
|
-
}
|
|
46
|
-
throw new Error(`ChatGPT ${phase} was not observed ready`);
|
|
47
|
-
})();
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export function promptTextMatches(observed, expected) {
|
|
51
|
-
const norm = (value) =>
|
|
52
|
-
String(value || "").replace(/\s+/g, " ").replace(/>\s+/g, ">").replace(
|
|
53
|
-
/\s+</g,
|
|
54
|
-
"<",
|
|
55
|
-
).trim();
|
|
56
|
-
const a = norm(observed), b = norm(expected);
|
|
57
|
-
if (a.includes(b)) return true;
|
|
58
|
-
if (!b) return !a;
|
|
59
|
-
const span = Math.min(256, Math.max(48, Math.floor(b.length / 8)));
|
|
60
|
-
return a.length >= Math.floor(b.length * 0.9) &&
|
|
61
|
-
a.includes(b.slice(0, span)) && a.includes(b.slice(-span));
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export function sendReady(state, { prompt, attachments = [] } = {}) {
|
|
65
|
-
const button = state?.send;
|
|
66
|
-
const enabled = typeof button === "object" ? !!button.enabled : !!button;
|
|
67
|
-
if (!enabled) return false;
|
|
68
|
-
if (prompt !== undefined && !promptTextMatches(state.text || "", prompt)) {
|
|
69
|
-
return false;
|
|
70
|
-
}
|
|
71
|
-
const names = Array.isArray(state.attachments?.names)
|
|
72
|
-
? state.attachments.names
|
|
73
|
-
: [];
|
|
74
|
-
return attachments.every((name) => names.includes(name));
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export function submissionReceipt(
|
|
78
|
-
turns,
|
|
79
|
-
beforeCount,
|
|
80
|
-
prompt,
|
|
81
|
-
composerText,
|
|
82
|
-
{ allowComposerCleared = false } = {},
|
|
83
|
-
) {
|
|
84
|
-
for (const turn of turns.slice(beforeCount)) {
|
|
85
|
-
if (promptTextMatches(turn.text, prompt)) {
|
|
86
|
-
return { verified_by: "user-turn", turn };
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
if (allowComposerCleared && !String(composerText || "").trim()) {
|
|
90
|
-
return {
|
|
91
|
-
verified_by: "composer-cleared",
|
|
92
|
-
turn: { id: null, text: prompt },
|
|
93
|
-
};
|
|
94
|
-
}
|
|
95
|
-
return null;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export function submissionFailureDiagnostic(
|
|
99
|
-
turns,
|
|
100
|
-
beforeCount,
|
|
101
|
-
prompt,
|
|
102
|
-
composerText,
|
|
103
|
-
uiBefore,
|
|
104
|
-
uiAfter,
|
|
105
|
-
) {
|
|
106
|
-
return {
|
|
107
|
-
accepted: false,
|
|
108
|
-
reason: "no_accepted_user_turn",
|
|
109
|
-
user_turn_matched: false,
|
|
110
|
-
before_user_turn_count: beforeCount,
|
|
111
|
-
user_turn_count: turns.length,
|
|
112
|
-
composer_populated: !!String(composerText || "").trim(),
|
|
113
|
-
composer_text_length: String(composerText || "").trim().length,
|
|
114
|
-
ui_changed: uiBefore == null || uiAfter == null
|
|
115
|
-
? null
|
|
116
|
-
: JSON.stringify(uiBefore) !== JSON.stringify(uiAfter),
|
|
117
|
-
ui_before: uiBefore,
|
|
118
|
-
ui_after: uiAfter,
|
|
119
|
-
};
|
|
120
|
-
}
|
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { PROBE_JS } from "./chatgpt-probe.mjs";
|
|
2
|
-
import { SEND_ENABLED_JS, STOP_VISIBLE_JS } from "./lifecycle-common.mjs";
|
|
3
|
-
|
|
4
|
-
/** Source executed inside a caller-owned WebHelm Session, never a separate tab. */
|
|
5
|
-
export function submissionScript(item) {
|
|
6
|
-
const selectorJS = "(() => { const selector=\'button[aria-label=\"Send\"],button[data-testid=\"send-button\"],button[aria-label=\"Send prompt\"],form button[type=\"submit\"]\'; for(const b of document.querySelectorAll(\'[data-webhelm-queue-send]\'))b.removeAttribute(\'data-webhelm-queue-send\'); for(const b of document.querySelectorAll(selector)){if(!b.getClientRects().length||b.disabled||b.getAttribute(\'aria-disabled\')===\'true\')continue;b.setAttribute(\'data-webhelm-queue-send\',\'1\');return \'[data-webhelm-queue-send=\"1\"]\';} return null; })()";
|
|
7
|
-
return [
|
|
8
|
-
"return await (async()=>{",
|
|
9
|
-
"const gate=await js("+JSON.stringify(PROBE_JS)+");",
|
|
10
|
-
"const actualId=await js("+JSON.stringify("location.pathname.split('/c/')[1]?.split('/')[0]||''")+");",
|
|
11
|
-
"if(actualId!=="+JSON.stringify(item.thread_id)+
|
|
12
|
-
")return {diagnostic:'thread_redirect_mismatch'};",
|
|
13
|
-
"if(gate?.state!=='READY'||!(await js("+JSON.stringify(SEND_ENABLED_JS)+")))",
|
|
14
|
-
" return {diagnostic:'pre_send_gate_not_ready'};",
|
|
15
|
-
"if((gate.composer_text||'').replace(/\\s+/g,' ').trim()!=="+
|
|
16
|
-
JSON.stringify(item.message.replace(/\s+/g,' ').trim())+")",
|
|
17
|
-
|
|
18
|
-
" return {diagnostic:'pre_send_gate_not_ready'};",
|
|
19
|
-
"const selector=await js("+JSON.stringify(selectorJS)+");",
|
|
20
|
-
"if(!selector)return {diagnostic:'send_control_not_found'};",
|
|
21
|
-
"await click(selector);",
|
|
22
|
-
// Stay below the WebHelm 30-second Session exec deadline on a missing Stop.
|
|
23
|
-
"for(let i=0;i<60;i++){",
|
|
24
|
-
" if(await js("+JSON.stringify(STOP_VISIBLE_JS)+"))",
|
|
25
|
-
" return {verified_by:'stop-button-visible'};",
|
|
26
|
-
" await sleep(250);",
|
|
27
|
-
"}",
|
|
28
|
-
"return {diagnostic:'post_submit_stop_not_observed_no_resend'};",
|
|
29
|
-
"})()",
|
|
30
|
-
].join("\n");
|
|
31
|
-
}
|