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
|
@@ -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
|
-
}
|
|
@@ -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
|
-
}
|