@tomflow/chatloop-extension 0.3.47 → 0.3.53
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 +23 -7
- package/bin/cli.mjs +2 -2
- package/bin/native-host.mjs +3 -6
- package/extension/actions/clean.js +4 -10
- package/extension/actions/common.js +24 -1
- package/extension/actions/continue.js +33 -66
- package/extension/actions/dom.js +2 -25
- package/extension/actions/handoff.js +30 -50
- package/extension/actions/start.js +36 -1
- package/extension/actions/text.js +2 -25
- package/extension/background.js +429 -479
- package/extension/loop/core.js +3 -16
- package/extension/loop/observer.js +129 -3
- package/extension/loop/resources.js +25 -15
- package/extension/manifest.json +1 -1
- package/extension/popup.html +0 -1
- package/extension/popup.js +1 -1
- package/lib/bridge.mjs +12 -16
- package/lib/session-file.mjs +21 -3
- package/package.json +1 -1
- package/extension/acceptance.js +0 -641
- package/extension/actions/clock.js +0 -29
- package/extension/clock.html +0 -4
- package/lib/mcp-tools.json +0 -26
package/extension/loop/core.js
CHANGED
|
@@ -23,20 +23,7 @@
|
|
|
23
23
|
if (standalone.length !== 1) return "UNKNOWN";
|
|
24
24
|
return match[1];
|
|
25
25
|
}
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
hash ^= text.charCodeAt(i);
|
|
30
|
-
hash = Math.imul(hash, 16777619);
|
|
31
|
-
}
|
|
32
|
-
return (hash >>> 0).toString(16) + ":" + text.length;
|
|
33
|
-
}
|
|
34
|
-
function decision(status, wasConfirming = false) {
|
|
35
|
-
if (status === "DONE") return "COMPLETED";
|
|
36
|
-
if (status === "BLOCKED") return "BLOCKED";
|
|
37
|
-
if (status === "CONTINUE") return "CONTINUE";
|
|
38
|
-
if (status === "HANDOFF") return "HANDOFF";
|
|
39
|
-
return wasConfirming ? "BLOCKED" : "CONFIRM";
|
|
40
|
-
}
|
|
41
|
-
globalThis.ChatLoopCoreV1 = Object.freeze({parseStatus, fingerprint, decision});
|
|
26
|
+
// Worker is the sole status consumer; observation fingerprints belong to
|
|
27
|
+
// observer.js and dispatch decisions belong to background.js.
|
|
28
|
+
globalThis.ChatLoopCoreV1 = Object.freeze({parseStatus});
|
|
42
29
|
})();
|
|
@@ -66,10 +66,37 @@
|
|
|
66
66
|
const userKey = messageId(lastUser, "user");
|
|
67
67
|
const assistantKey = messageId(lastAssistant, "assistant");
|
|
68
68
|
const historicAssistantKey = messageId(lastHistoricAssistant, "assistant");
|
|
69
|
+
// The immediately preceding assistant before a NEW user Turn is the
|
|
70
|
+
// only eligible confirmation anchor. Historical interactive cards do
|
|
71
|
+
// not block a later assistant Turn or authorize a new action.
|
|
72
|
+
const priorIndex = roles.findLastIndex((el, i) =>
|
|
73
|
+
i < userIndex && roleOf(el) === "assistant");
|
|
74
|
+
const priorAssistant = priorIndex >= 0 ? roles[priorIndex] : null;
|
|
75
|
+
const priorAssistantKey = messageId(priorAssistant, "assistant");
|
|
76
|
+
const priorUser = priorIndex > 0 ? roles.slice(0,priorIndex)
|
|
77
|
+
.filter(el=>roleOf(el)==="user").at(-1) : null;
|
|
78
|
+
const priorAssistantUserKey = messageId(priorUser,"user");
|
|
79
|
+
const directReplyAfterPriorAssistant = priorIndex>=0
|
|
80
|
+
&& !roles.slice(priorIndex+1,userIndex).some(el=>roleOf(el)==="user");
|
|
69
81
|
const scope = lastAssistant?.closest?.('[data-testid^="conversation-turn-"]')
|
|
70
82
|
|| lastAssistant?.closest?.('[data-talvt-turn-state]') || lastAssistant;
|
|
71
83
|
const reply = lastAssistant?.querySelector?.(".markdown") || lastAssistant;
|
|
72
84
|
const text = (reply?.innerText ?? reply?.textContent ?? "").trim();
|
|
85
|
+
// A Chat Loop confirmation is a REAL actionable choice surface in the
|
|
86
|
+
// latest assistant Turn, never a form elsewhere on the page. Disabled
|
|
87
|
+
// Submit still means pending: no user message has yet been submitted.
|
|
88
|
+
const controls = [...scope?.querySelectorAll?.(
|
|
89
|
+
'[role="radiogroup"],[role="radio"],input[type="radio"],' +
|
|
90
|
+
'select,[role="combobox"],textarea,[role="textbox"],' +
|
|
91
|
+
'input[type="checkbox"],[role="checkbox"]') || []];
|
|
92
|
+
const submit = [...scope?.querySelectorAll?.('button') || []].some(button =>
|
|
93
|
+
visible(button) && /(?:提交|确认|submit|confirm)/i.test(
|
|
94
|
+
(button.innerText || button.textContent ||
|
|
95
|
+
button.getAttribute?.("aria-label") || "").trim()));
|
|
96
|
+
const labels = (scope?.innerText || scope?.textContent || "").slice(-2000);
|
|
97
|
+
const pendingConfirmation = Boolean(lastAssistant && submit
|
|
98
|
+
&& controls.some(visible)
|
|
99
|
+
&& /(?:确认|修改|不通过|拒绝|自定义|approval|revise|reject|choice)/i.test(labels));
|
|
73
100
|
const stop = [...document.querySelectorAll(
|
|
74
101
|
'button[data-testid="stop-button"],button[aria-label="Stop generating"],' +
|
|
75
102
|
'button[aria-label="Stop"],button[aria-label="停止生成"],' +
|
|
@@ -132,7 +159,9 @@
|
|
|
132
159
|
const dialog = [...document.querySelectorAll(
|
|
133
160
|
'[role="dialog"][aria-modal="true"],dialog[open]')].some(visible);
|
|
134
161
|
const turnState = scope?.getAttribute?.("data-talvt-turn-state") || null;
|
|
135
|
-
return {path, userKey, assistantKey, historicAssistantKey,
|
|
162
|
+
return {path, userKey, assistantKey, historicAssistantKey, priorAssistantKey,
|
|
163
|
+
priorAssistantUserKey, directReplyAfterPriorAssistant,
|
|
164
|
+
pendingConfirmation, text,
|
|
136
165
|
hasUser: Boolean(lastUser), hasAssistant: Boolean(lastAssistant),
|
|
137
166
|
stop, busy, toolUnknown, turnState, composerReady, copyAction,
|
|
138
167
|
fatal, errorReason: securityChallenge ? "SECURITY_CHALLENGE"
|
|
@@ -143,7 +172,11 @@
|
|
|
143
172
|
state = {contract: CONTRACT, status, reason, page: snap.path || null,
|
|
144
173
|
userKey: snap.userKey || null, assistantKey: snap.assistantKey || null,
|
|
145
174
|
retryAvailable: status === "BLOCKED" && snap.retryAvailable === true,
|
|
146
|
-
eventCount: session.emittedCount, observedAt: Date.now()
|
|
175
|
+
eventCount: session.emittedCount, observedAt: Date.now(),
|
|
176
|
+
pendingConfirmation: snap.pendingConfirmation === true,
|
|
177
|
+
priorAssistantKey: snap.priorAssistantKey || null,
|
|
178
|
+
priorAssistantUserKey:snap.priorAssistantUserKey || null,
|
|
179
|
+
directReplyAfterPriorAssistant:snap.directReplyAfterPriorAssistant===true};
|
|
147
180
|
if (event) {
|
|
148
181
|
document.dispatchEvent(new CustomEvent("CHAT_LOOP_TURN_FINISHED_V1", {
|
|
149
182
|
detail: {contract: CONTRACT, page: snap.path,
|
|
@@ -155,7 +188,11 @@
|
|
|
155
188
|
void Promise.resolve(chrome.runtime.sendMessage({
|
|
156
189
|
type: "CHAT_LOOP_TURN_FINISHED_V1", page: snap.path,
|
|
157
190
|
userKey: snap.userKey, assistantKey: snap.assistantKey,
|
|
158
|
-
replyText: snap.text, startedAt: session.firstTurnAt || Date.now()
|
|
191
|
+
replyText: snap.text, startedAt: session.firstTurnAt || Date.now(),
|
|
192
|
+
pendingConfirmation: snap.pendingConfirmation === true,
|
|
193
|
+
priorAssistantKey: snap.priorAssistantKey || null,
|
|
194
|
+
priorAssistantUserKey:snap.priorAssistantUserKey || null,
|
|
195
|
+
directReplyAfterPriorAssistant:snap.directReplyAfterPriorAssistant===true
|
|
159
196
|
})).catch(() => {});
|
|
160
197
|
}
|
|
161
198
|
}
|
|
@@ -416,6 +453,95 @@
|
|
|
416
453
|
userKey: observation.userKey});
|
|
417
454
|
return false;
|
|
418
455
|
}
|
|
456
|
+
if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
|
|
457
|
+
// Read-only, fail-closed two-stage approval proof for same-Chat adoption.
|
|
458
|
+
// An explicit model assertion or a copied task Context is never evidence.
|
|
459
|
+
const path = conversationPath();
|
|
460
|
+
const mains = [...document.querySelectorAll("main")].filter(visible);
|
|
461
|
+
const fail = reason => reply({contract: CONTRACT, status:"UNVERIFIED",reason});
|
|
462
|
+
if (!path || mains.length !== 1) {
|
|
463
|
+
fail("APPROVAL_CHAT_UNVERIFIED");return false;
|
|
464
|
+
}
|
|
465
|
+
const main=mains[0];
|
|
466
|
+
const legacy=[...main.querySelectorAll(
|
|
467
|
+
'[data-message-author-role="user"],[data-message-author-role="assistant"]')];
|
|
468
|
+
const nodes=legacy.length?legacy:[...main.querySelectorAll(
|
|
469
|
+
'[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')];
|
|
470
|
+
const role=node=>node.getAttribute("data-message-author-role")
|
|
471
|
+
||node.getAttribute("data-chatgpt-search-unit-key")?.split(":").at(-1);
|
|
472
|
+
const rows=nodes.map(el=>({el,role:role(el)}))
|
|
473
|
+
.filter(x=>["user","assistant"].includes(x.role));
|
|
474
|
+
const textOf=x=>(x.el.querySelector?.(".markdown")?.innerText
|
|
475
|
+
||x.el.innerText||x.el.textContent||"").trim();
|
|
476
|
+
const confirms=(value,type)=>{
|
|
477
|
+
const line=value.replace(/\s+/g,"").trim();
|
|
478
|
+
if (!line || line.length>100) return false;
|
|
479
|
+
// Only an affirmative standalone user action. Do NOT accept
|
|
480
|
+
// "我确认方案 P1,但测试先不要做" or copied/embedded approvals.
|
|
481
|
+
const target=type==="R"
|
|
482
|
+
? "(?:这份|当前|本版|上述)?(?:需求(?:R[1-9][0-9]*)?|R[1-9][0-9]*)"
|
|
483
|
+
: "(?:这份|当前|本版|上述)?(?:方案(?:与|及|和)?计划|实施计划|方案|计划|P[1-9][0-9]*)(?:P[1-9][0-9]*)?";
|
|
484
|
+
return new RegExp("^(?:我)?(?:已经|已)?(?:确认|同意|批准)"+target+"[。.!!]?$","i")
|
|
485
|
+
.test(line);
|
|
486
|
+
};
|
|
487
|
+
const lastUser=rows.findLastIndex(x=>x.role==="user");
|
|
488
|
+
if(lastUser<3 || rows[lastUser-1].role!=="assistant") {
|
|
489
|
+
fail("APPROVAL_SEQUENCE_UNVERIFIED");return false;
|
|
490
|
+
}
|
|
491
|
+
const pUser=rows[lastUser],pAssistant=rows[lastUser-1];
|
|
492
|
+
if(!confirms(textOf(pUser),"P")
|
|
493
|
+
|| !/(?:方案|计划)/.test(textOf(pAssistant))
|
|
494
|
+
|| !/\bP[1-9][0-9]*\b/i.test(textOf(pAssistant))) {
|
|
495
|
+
fail("APPROVAL_PLAN_MISSING");return false;
|
|
496
|
+
}
|
|
497
|
+
const pVersion=textOf(pAssistant).match(/\bP[1-9][0-9]*\b/i)?.[0].toUpperCase();
|
|
498
|
+
const pUserVersion=textOf(pUser).match(/\bP[1-9][0-9]*\b/i)?.[0].toUpperCase();
|
|
499
|
+
if(pUserVersion && pVersion!==pUserVersion){
|
|
500
|
+
fail("APPROVAL_PLAN_VERSION_MISMATCH");return false;
|
|
501
|
+
}
|
|
502
|
+
const rIndex=rows.slice(0,lastUser-1).findLastIndex(x=>x.role==="user"
|
|
503
|
+
&&confirms(textOf(x),"R"));
|
|
504
|
+
if(rIndex<1 ||rows[rIndex-1].role!=="assistant"){
|
|
505
|
+
fail("APPROVAL_REQUIREMENTS_MISSING");return false;
|
|
506
|
+
}
|
|
507
|
+
const rAssistant=rows[rIndex-1],rUser=rows[rIndex];
|
|
508
|
+
if(!/(?:需求|范围|验收)/.test(textOf(rAssistant))
|
|
509
|
+
|| !/\bR[1-9][0-9]*\b/i.test(textOf(rAssistant))) {
|
|
510
|
+
fail("APPROVAL_REQUIREMENTS_MISSING");return false;
|
|
511
|
+
}
|
|
512
|
+
const rVersion=textOf(rAssistant).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
|
|
513
|
+
const rUserVersion=textOf(rUser).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
|
|
514
|
+
const referencedR=textOf(pAssistant).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
|
|
515
|
+
if(!referencedR || referencedR!==rVersion){
|
|
516
|
+
fail("APPROVAL_PLAN_REQUIREMENT_MISMATCH");return false;
|
|
517
|
+
}
|
|
518
|
+
if(rUserVersion && rVersion!==rUserVersion){
|
|
519
|
+
fail("APPROVAL_REQUIREMENTS_VERSION_MISMATCH");return false;
|
|
520
|
+
}
|
|
521
|
+
const userKey=messageId(pUser.el,"user");
|
|
522
|
+
const snap=inspect();
|
|
523
|
+
// Normally the model calls Start during its P-confirmation Turn.
|
|
524
|
+
// A fresh, explicitly scoped native Start intent can also adopt AFTER
|
|
525
|
+
// that assistant Turn ends (e.g. MCP schema was stale in the same Chat).
|
|
526
|
+
// Only the exact current Chat ID, last R/P approval user identity and
|
|
527
|
+
// completed assistant reply qualify. A historical unscoped idle Chat
|
|
528
|
+
// must never become an Owner just because R/P messages are visible.
|
|
529
|
+
const explicitChatId=typeof message.explicitChatId==="string"
|
|
530
|
+
? message.explicitChatId.toLowerCase():null;
|
|
531
|
+
const currentId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
|
|
532
|
+
const scopedIdle=Boolean(explicitChatId && explicitChatId===currentId
|
|
533
|
+
&&!snap.stop&&!snap.busy&&snap.assistantKey
|
|
534
|
+
&&snap.composerReady&&snap.copyAction&&snap.text
|
|
535
|
+
&&!snap.pendingConfirmation);
|
|
536
|
+
if(!userKey ||snap.path!==path||snap.userKey!==userKey
|
|
537
|
+
||!(snap.stop||snap.busy||scopedIdle)
|
|
538
|
+
||snap.fatal||snap.dialog||snap.toolUnknown){
|
|
539
|
+
fail("APPROVAL_LAST_TURN_UNVERIFIED");return false;
|
|
540
|
+
}
|
|
541
|
+
reply({contract:CONTRACT,status:"VERIFIED",page:path,
|
|
542
|
+
userKey,rVersion,pVersion,priorAssistantKey:messageId(pAssistant.el,"assistant")});
|
|
543
|
+
return false;
|
|
544
|
+
}
|
|
419
545
|
if (message?.type === "CHAT_LOOP_TURN_VERIFY_V1") {
|
|
420
546
|
// Explicit manual Action: only a fresh read-only completed-Turn candidate.
|
|
421
547
|
// This does not emit a completion event or write anything to the page.
|
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
const KEY = 'chat-loop.resources.v1';
|
|
5
5
|
const ACTION_LIMIT = 3; // Includes machine Eye, Start, manual and timed Actions.
|
|
6
6
|
const CHAT_LIMIT = 2; // One owner plus at most one Handoff successor.
|
|
7
|
-
const AUDIT_TTL = 60_000;
|
|
7
|
+
const AUDIT_TTL = 60_000; // Reap obsolete audit pages from installed older Extension versions.
|
|
8
8
|
const READ_TTL = 180_000;
|
|
9
9
|
const TERMINAL_TTL = 30_000;
|
|
10
10
|
const READ_ONLY = new Set(['status','text','dom','screenshot','reload']);
|
|
11
11
|
const ACTIONS = new Set(['start','continue','handoff','status','text','dom',
|
|
12
|
-
'screenshot','reload','clean'
|
|
12
|
+
'screenshot','reload','clean']);
|
|
13
13
|
const validId = s => /^[a-f0-9]{32}$/.test(s || '');
|
|
14
14
|
const validTabId = s => /^[1-9][0-9]*$/.test(s || '');
|
|
15
15
|
const extensionBase = () => chrome.runtime.getURL('');
|
|
@@ -20,15 +20,8 @@
|
|
|
20
20
|
if (u.protocol !== 'chrome-extension:' || !tab.url.startsWith(extensionBase())
|
|
21
21
|
|| u.host !== new URL(extensionBase()).host) return null;
|
|
22
22
|
if (u.pathname === '/popup.html' && u.search === '?audit=1')
|
|
23
|
-
return {kind:'audit'};
|
|
24
|
-
|
|
25
|
-
const name=[...u.searchParams.keys()][0],value=u.searchParams.get(name);
|
|
26
|
-
const noId=new Set(['newTest','cleanup','cleanupVerified','cleanupStaleMachine']);
|
|
27
|
-
const tabId=new Set(['cleanupTestHome','cleanupFailedStartHome','cleanupBlockedE2E']);
|
|
28
|
-
if ((noId.has(name)&&value==='1') || (tabId.has(name)&&validTabId(value)))
|
|
29
|
-
return {kind:'manual',name:'acceptance'};
|
|
30
|
-
}
|
|
31
|
-
const name = u.pathname.match(/^\/(start|continue|handoff|status|text|dom|screenshot|reload|clean|clock)\.html$/)?.[1];
|
|
23
|
+
return {kind:'audit'}; // Legacy page reaping only; old audit UI is not executable.
|
|
24
|
+
const name = u.pathname.match(/^\/([a-z]+)\.html$/)?.[1];
|
|
32
25
|
if (!ACTIONS.has(name)) return null;
|
|
33
26
|
if (u.searchParams.size === 1 && validId(u.searchParams.get('requestId')))
|
|
34
27
|
return {kind:READ_ONLY.has(name) || ['continue','handoff'].includes(name)
|
|
@@ -178,11 +171,12 @@
|
|
|
178
171
|
:{ok:true,actionCount,chatCount};
|
|
179
172
|
}
|
|
180
173
|
async function registerAction(tab) {
|
|
181
|
-
|
|
174
|
+
const info=classify(tab);
|
|
175
|
+
if (!info) return false;
|
|
182
176
|
const state=await load();
|
|
183
177
|
if (!state.entries.some(e=>e.id===tab.id)) {
|
|
184
178
|
state.entries.push({id:tab.id,url:tab.url,kind:'action',
|
|
185
|
-
type:
|
|
179
|
+
type:info.kind,firstSeenAt:Date.now(),owned:true});
|
|
186
180
|
state.created++;
|
|
187
181
|
// Fast actions can finish before the next alarm/reconciliation. Count
|
|
188
182
|
// their observed creation in peak metrics even if no later scan sees them.
|
|
@@ -208,11 +202,27 @@
|
|
|
208
202
|
await save(state);
|
|
209
203
|
return true;
|
|
210
204
|
}
|
|
205
|
+
async function adoptChat(tab,run) {
|
|
206
|
+
if(!Number.isInteger(tab?.id)||typeof tab.url!=="string"
|
|
207
|
+
|| !/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(tab.url)
|
|
208
|
+
||!run?.sessionId||run.phase!=="PENDING"||run.adoptTabId!==tab.id)
|
|
209
|
+
return false;
|
|
210
|
+
const state=await load();
|
|
211
|
+
if(state.entries.some(e=>e.id===tab.id))return false; // Existing Owner, even terminal, is not silently replaced.
|
|
212
|
+
state.entries.push({id:tab.id,url:tab.url,kind:"chat",
|
|
213
|
+
sessionId:run.sessionId,firstSeenAt:Date.now(),confirmed:true,
|
|
214
|
+
adopted:true,testOwned:false});
|
|
215
|
+
state.created++;
|
|
216
|
+
state.peakChats=Math.max(state.peakChats,
|
|
217
|
+
state.entries.filter(e=>e.kind==="chat").length);
|
|
218
|
+
await save(state);
|
|
219
|
+
return true;
|
|
220
|
+
}
|
|
211
221
|
async function confirmChat(id,sessionId,url) {
|
|
212
222
|
const state=await load();
|
|
213
223
|
const entry=state.entries.find(e=>e.id===id&&e.kind==='chat'
|
|
214
224
|
&&e.sessionId===sessionId);
|
|
215
|
-
if (!entry || !/^https:\/\/chatgpt\.com\/c\/[0-9a-f-]{12,}$/i.test(url)) return;
|
|
225
|
+
if (!entry || !/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(url)) return;
|
|
216
226
|
entry.url=url;entry.confirmed=true;
|
|
217
227
|
await save(state);
|
|
218
228
|
}
|
|
@@ -224,5 +234,5 @@
|
|
|
224
234
|
await save(state);
|
|
225
235
|
}
|
|
226
236
|
globalThis.ChatLoopResourcesV1=Object.freeze({reconcile,admit,registerAction,
|
|
227
|
-
registerChat,confirmChat,terminal,KEY,ACTION_LIMIT,CHAT_LIMIT});
|
|
237
|
+
registerChat,adoptChat,confirmChat,terminal,KEY,ACTION_LIMIT,CHAT_LIMIT});
|
|
228
238
|
})();
|
package/extension/manifest.json
CHANGED
package/extension/popup.html
CHANGED
package/extension/popup.js
CHANGED
|
@@ -55,7 +55,7 @@ async function showActionState() {
|
|
|
55
55
|
const key = "chat-loop.action.run.v1";
|
|
56
56
|
const run = (await chrome.storage.local.get(key))[key];
|
|
57
57
|
const allowed = ["phase", "action", "reason", "tabId", "page", "sourceTabId", "sourcePage",
|
|
58
|
-
"userKey", "assistantKey", "newUserKey", "
|
|
58
|
+
"userKey", "assistantKey", "newUserKey", "startedAt",
|
|
59
59
|
"sessionId", "projectId", "generation",
|
|
60
60
|
"deadlineAt", "handoffPending", "handoffPendingAt", "attemptedNewTabId"];
|
|
61
61
|
const summary = {version: chrome.runtime.getManifest().version};
|
package/lib/bridge.mjs
CHANGED
|
@@ -9,6 +9,7 @@ const ID = /^[a-f0-9]{32}$/;
|
|
|
9
9
|
const MAX_TEXT = 8 * 1024 * 1024;
|
|
10
10
|
const MAX_PNG = 24 * 1024 * 1024;
|
|
11
11
|
const TTL_MS = 20 * 60 * 1000;
|
|
12
|
+
const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
|
|
12
13
|
export const configFile = () => join(homedir(), '.chat-loop', 'extension', 'config.json');
|
|
13
14
|
export const tempRoot = () => join(tmpdir(), 'chatloop-extension-' + (process.getuid?.() ?? process.env.USERNAME ?? 'user'));
|
|
14
15
|
export function privateDir(path) {
|
|
@@ -23,19 +24,23 @@ export function requestDir(id) {
|
|
|
23
24
|
if(typeof id!=='string'||!ID.test(id))throw Object.assign(Error('Invalid request ID'),{code:'INVALID_REQUEST_ID'});
|
|
24
25
|
return join(tempRoot(),id);
|
|
25
26
|
}
|
|
26
|
-
|
|
27
|
+
function validateIntent(action, intent) {
|
|
27
28
|
if(action==='start'){
|
|
28
29
|
if(!intent||typeof intent!=='object'||Array.isArray(intent)
|
|
29
|
-
||Object.keys(intent).some(k=>!['projectId','prompt','confirmed','replaceBlockedSessionId'].includes(k))
|
|
30
|
+
||Object.keys(intent).some(k=>!['projectId','prompt','confirmed','replaceBlockedSessionId','mode','chatUrl'].includes(k))
|
|
30
31
|
||!(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/).test(intent.projectId||'')
|
|
31
|
-
||intent.confirmed!==true
|
|
32
|
+
||intent.confirmed!==true || (intent.mode!==undefined && intent.mode!=='adopt')
|
|
32
33
|
|| (intent.replaceBlockedSessionId!==undefined
|
|
33
34
|
&& !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.replaceBlockedSessionId))
|
|
34
|
-
||
|
|
35
|
-
|
|
36
|
-
|
|
35
|
+
||(intent.chatUrl!==undefined
|
|
36
|
+
&& (intent.mode!=='adopt'||typeof intent.chatUrl!=='string'||!CHAT_URL.test(intent.chatUrl)))
|
|
37
|
+
||(intent.mode==='adopt'
|
|
38
|
+
? Object.hasOwn(intent,'prompt')
|
|
39
|
+
: typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
|
|
40
|
+
||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)))
|
|
37
41
|
throw Object.assign(Error('Explicit confirmed task and project required'),{code:'INVALID_START_INTENT'});
|
|
38
|
-
return {projectId:intent.projectId,
|
|
42
|
+
return {projectId:intent.projectId,confirmed:true,
|
|
43
|
+
...(intent.mode==='adopt'?{mode:'adopt',...(intent.chatUrl?{chatUrl:intent.chatUrl}:{})}:{prompt:intent.prompt}),
|
|
39
44
|
...(intent.replaceBlockedSessionId?{replaceBlockedSessionId:intent.replaceBlockedSessionId}:{})};
|
|
40
45
|
}
|
|
41
46
|
if(action==='clean'){
|
|
@@ -138,15 +143,6 @@ export function readResult(id) {
|
|
|
138
143
|
privateDir(requestDir(id));
|
|
139
144
|
return JSON.parse(readFileSync(p,'utf8'));
|
|
140
145
|
}
|
|
141
|
-
// Read-only cleanup proof. Only an aged, durably FAILED machine request
|
|
142
|
-
// can qualify; never expose the nonce, original intent, or result contents.
|
|
143
|
-
export function staleFailureConfirmed(id,action) {
|
|
144
|
-
if(!ACTIONS.includes(action))return false;
|
|
145
|
-
const result=readResult(id);
|
|
146
|
-
return !!(result && result.id===id && result.action===action
|
|
147
|
-
&& result.status==='FAILED' && Number.isSafeInteger(result.at)
|
|
148
|
-
&& result.at<=Date.now()-TTL_MS);
|
|
149
|
-
}
|
|
150
146
|
export function cleanup(){
|
|
151
147
|
const root=tempRoot();
|
|
152
148
|
if(!existsSync(root))return;
|
package/lib/session-file.mjs
CHANGED
|
@@ -8,7 +8,7 @@ import {randomUUID} from 'node:crypto';
|
|
|
8
8
|
const ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
9
9
|
const CHAT=/^[0-9a-f-]{12,}$/i;
|
|
10
10
|
const PROJECT=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
11
|
-
const PHASE=new Set(['STARTING','RESERVED','PENDING','WAITING_REPLY','
|
|
11
|
+
const PHASE=new Set(['STARTING','RESERVED','PENDING','WAITING_REPLY','DONE','BLOCKED']);
|
|
12
12
|
const fail=code=>Object.assign(Error(code),{code});
|
|
13
13
|
export const sessionPath=()=>join(homedir(),'.chat-loop','session','active-session.json');
|
|
14
14
|
const ensurePrivate=dir=>{
|
|
@@ -47,13 +47,28 @@ export function readSession(){
|
|
|
47
47
|
try{return validate(JSON.parse(readFileSync(file,'utf8')));}
|
|
48
48
|
catch(e){if(e.code)throw e;throw fail('SESSION_FILE_CORRUPT');}
|
|
49
49
|
}
|
|
50
|
-
export function writeSession(input,replaceBlockedSessionId=null){
|
|
50
|
+
export function writeSession(input,replaceBlockedSessionId=null,resumeBlockedSessionId=null,resumeBlockedUpdatedAt=null){
|
|
51
51
|
const next=validate(input),file=sessionPath(),dir=dirname(file),lock=file+'.lock';
|
|
52
52
|
ensurePrivate(dir);
|
|
53
53
|
let fd;
|
|
54
54
|
try{fd=openSync(lock,'wx',0o600);}catch{throw fail('SESSION_CONCURRENT_UPDATE');}
|
|
55
55
|
try{
|
|
56
56
|
const old=readSession();
|
|
57
|
+
if(resumeBlockedSessionId){
|
|
58
|
+
// A BLOCKED session is terminal except for an exact-same-owner,
|
|
59
|
+
// same-Chat, same-generation, one-shot recovery CAS. No new Chat,
|
|
60
|
+
// task, project, approval or Handoff may be smuggled into recovery.
|
|
61
|
+
if(replaceBlockedSessionId || !old || old.phase!=='BLOCKED'
|
|
62
|
+
||resumeBlockedUpdatedAt!==null&&old.updatedAt!==resumeBlockedUpdatedAt
|
|
63
|
+
||old.sessionId!==resumeBlockedSessionId
|
|
64
|
+
||next.sessionId!==old.sessionId
|
|
65
|
+
||next.projectId!==old.projectId
|
|
66
|
+
||next.generation!==old.generation
|
|
67
|
+
||next.activeChatId!==old.activeChatId
|
|
68
|
+
||next.activeChatUrl!==old.activeChatUrl
|
|
69
|
+
||next.phase!=='RESERVED')
|
|
70
|
+
throw fail('SESSION_RECOVERY_MISMATCH');
|
|
71
|
+
}
|
|
57
72
|
if(replaceBlockedSessionId && (!old||old.sessionId!==next.sessionId
|
|
58
73
|
&& (old.phase!=='BLOCKED'||old.sessionId!==replaceBlockedSessionId)))
|
|
59
74
|
throw fail('SESSION_REPLACEMENT_MISMATCH');
|
|
@@ -62,9 +77,12 @@ export function writeSession(input,replaceBlockedSessionId=null){
|
|
|
62
77
|
&& replaceBlockedSessionId===old.sessionId && next.projectId!==old.projectId))
|
|
63
78
|
throw fail('SESSION_ALREADY_ACTIVE');
|
|
64
79
|
if(old&&old.sessionId===next.sessionId){
|
|
80
|
+
if(next.projectId!==old.projectId)throw fail('SESSION_PROJECT_CHANGED');
|
|
65
81
|
if(next.generation<old.generation)throw fail('SESSION_STALE_GENERATION');
|
|
66
82
|
if(old.phase==='DONE'&&next.phase!=='DONE'||old.phase==='BLOCKED'
|
|
67
|
-
&& !['BLOCKED','DONE'].includes(next.phase)
|
|
83
|
+
&& !['BLOCKED','DONE'].includes(next.phase)
|
|
84
|
+
&&!(resumeBlockedSessionId===old.sessionId
|
|
85
|
+
&&next.phase==='RESERVED'))
|
|
68
86
|
throw fail('SESSION_TERMINAL_LOCKED');
|
|
69
87
|
if(old.activeChatId!==null&&next.generation===old.generation&&
|
|
70
88
|
next.activeChatId!==null&&old.activeChatId!==next.activeChatId)
|