@tomflow/chatloop-extension 0.4.12 → 0.4.13

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/bin/cli.mjs CHANGED
@@ -127,15 +127,23 @@ if(help!==null){
127
127
  const data=await execute(args);
128
128
  emit('RESULT',command,{ok:true,value:data});
129
129
  }catch(e){
130
- emit('RESULT',command,{ok:false,error:{code:e.code||'UNKNOWN_RESULT',message:e.message}});
130
+ const code=typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
131
+ ?e.code:'UNKNOWN_RESULT';
132
+ // Preserve the versioned CLI error shape but never publish arbitrary
133
+ // native/OS error messages or absolute paths through stdout.
134
+ emit('RESULT',command,{ok:false,error:{code,message:code}});
131
135
  process.exitCode=1;
132
136
  }
133
137
  }
134
138
  // After the CLI reply is produced, allow bounded observation delivery.
135
139
  // This never changes its result or retries its business side effect.
136
- const audit=await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(5000);
137
- if(audit?.status!=='OK'){
138
- // Sanitized counters only; the already-emitted RESULT is authoritative.
139
- process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
140
- component:'extension.cli',...audit})+'\n');
140
+ try{
141
+ const audit=await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(5000);
142
+ if(audit?.status!=='OK'){
143
+ // The already-emitted RESULT remains authoritative even if Trace stalls.
144
+ process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
145
+ component:'extension.cli',...audit})+'\n');
146
+ }
147
+ }catch{
148
+ // Soft telemetry must not change the CLI exit code after its business reply.
141
149
  }
@@ -8,13 +8,24 @@ const hostContract=nativeHostApi();
8
8
  const {readRequest,finish,readSession,writeSession,registeredContext,
9
9
  nativeContextControl,nativeApiObservation,observeNativeOperation}=hostContract;
10
10
  const MAX_INPUT=48*1024*1024;
11
+ let replied=false;
11
12
  const write=obj=>{
13
+ // One Native Messaging process may return exactly one business frame.
14
+ // A later observer/drain failure must not append a contradictory result.
15
+ if(replied)return;
12
16
  const b=Buffer.from(JSON.stringify(obj)),len=Buffer.alloc(4);
13
- len.writeUInt32LE(b.length);process.stdout.write(Buffer.concat([len,b]));
17
+ len.writeUInt32LE(b.length);
18
+ replied=true;
19
+ process.stdout.write(Buffer.concat([len,b]));
14
20
  };
15
21
  let buf=Buffer.alloc(0),handled=false,observationOnly=false;
16
22
  process.stdin.on('data',async chunk=>{
17
23
  if(handled)return;
24
+ // Bound accumulated bytes before Buffer.concat allocates. A claimed small
25
+ // frame length cannot justify unbounded piped input or retained memory.
26
+ if(buf.length+chunk.length>MAX_INPUT+4){
27
+ handled=true;write({status:'FAILED',code:'MESSAGE_TOO_LARGE'});return;
28
+ }
18
29
  buf=Buffer.concat([buf,chunk]);
19
30
  if(buf.length<4)return;
20
31
  const n=buf.readUInt32LE();
@@ -93,16 +104,24 @@ process.stdin.on('data',async chunk=>{
93
104
  }catch{/* Non-authoritative parent cannot modify Native business outcome. */}
94
105
  await observeNativeOperation(m.op,dispatch,parent);
95
106
  }
96
- }catch(e){write({status:'FAILED',code:e.code||'NATIVE_HOST_ERROR'});}
107
+ }catch(e){
108
+ const code=typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
109
+ ?e.code:'NATIVE_HOST_ERROR';
110
+ write({status:'FAILED',code});
111
+ }
97
112
  finally{
98
113
  // Observation-only requests cannot recursively generate Native audit.
99
114
  // Never delay their Writer receipt for an unrelated drain timeout.
100
115
  if(!observationOnly){
101
- const audit=await hostContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(4200);
102
- if(audit?.status!=='OK'){
103
- // The business reply is already written and remains authoritative.
104
- process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
105
- component:'extension.native',...audit})+'\n');
116
+ try{
117
+ const audit=await hostContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(4200);
118
+ if(audit?.status!=='OK'){
119
+ // Never expose audit internals or change an already-written reply.
120
+ process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
121
+ component:'extension.native',...audit})+'\n');
122
+ }
123
+ }catch{
124
+ // A logging failure must not reject this one-shot Native handler.
106
125
  }
107
126
  }
108
127
  }
@@ -106,9 +106,11 @@ async function run(){
106
106
  }catch(e){
107
107
  if(machine&&receipt?.nonce){
108
108
  try{
109
+ const rawCode=e?.code||e?.message;
110
+ const code=typeof rawCode==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
111
+ ?rawCode:'CLEAN_UNVERIFIED';
109
112
  const saved=await chrome.runtime.sendNativeMessage(host,{
110
- op:'complete',id:reqId,nonce:receipt.nonce,action,status:'FAILED',
111
- code:String(e.message||'CLEAN_UNVERIFIED').slice(0,120)});
113
+ op:'complete',id:reqId,nonce:receipt.nonce,action,status:'FAILED',code});
112
114
  if(saved?.status==='SAVED'&&saved.id===reqId){
113
115
  await chrome.tabs.remove(own.id).catch(()=>{});
114
116
  }
@@ -117,4 +119,5 @@ async function run(){
117
119
  throw e;
118
120
  }
119
121
  }
120
- run().catch(e=>show('BLOCKED',e.message||'CLEAN_FAILED'));
122
+ run().catch(e=>show('BLOCKED',
123
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(e?.message||'')?e.message:'CLEAN_FAILED'));
@@ -126,9 +126,12 @@ function copyText(value) {
126
126
  const req=await chrome.runtime.sendNativeMessage(nativeHost,
127
127
  {op:"acquire",id:machineId,action});
128
128
  if(req?.status==="OK") {
129
+ const rawCode=error?.code||error?.message;
130
+ const code=typeof rawCode==='string'
131
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
132
+ ?rawCode:'ACTION_FAILED';
129
133
  const saved = await chrome.runtime.sendNativeMessage(nativeHost,{
130
- op:"complete",id:machineId,nonce:req.nonce,action,status:"FAILED",
131
- code:String(error?.message||"ACTION_FAILED").slice(0,120)
134
+ op:"complete",id:machineId,nonce:req.nonce,action,status:"FAILED",code
132
135
  });
133
136
  // Machine errors already have a durable CLI receipt. They must not
134
137
  // accumulate as abandoned tabs; manual/unverified errors remain open.
@@ -2,6 +2,11 @@
2
2
  // The background schedules an Action page; this page alone performs the DOM mutation.
3
3
  const statusNode = document.getElementById("status");
4
4
  const detailsNode = document.getElementById("details");
5
+ const actionErrorCode=(error,fallback='SEND_ERROR')=>{
6
+ const code=error?.code||error?.message;
7
+ return typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
8
+ ?code:fallback;
9
+ };
5
10
  function show(status, details) {
6
11
  statusNode.textContent = status;
7
12
  detailsNode.textContent = details;
@@ -139,7 +144,11 @@ async function sendOnce(target, text) {
139
144
  await new Promise(resolve => setTimeout(resolve, 250));
140
145
  }
141
146
  throw Error("SEND_UNVERIFIED"); // Side effect may exist: block, don't retry.
142
- } catch (error) {return {status: "UNVERIFIED", reason: error.message || "SEND_ERROR"};}
147
+ } catch (error) {
148
+ const code=error?.code||error?.message;
149
+ return {status:"UNVERIFIED",reason:
150
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:"SEND_ERROR"};
151
+ }
143
152
  },
144
153
  args: [target, text]
145
154
  });
@@ -197,7 +206,11 @@ async function retryNativeOnce(target) {
197
206
  if (!latest) return {status: 'RETRY_CLICKED'};
198
207
  }
199
208
  throw Error("NATIVE_RETRY_NOT_ACKNOWLEDGED");
200
- } catch(error) {return {status:'UNVERIFIED',reason:error.message||'RETRY_FAILED'};}
209
+ } catch(error) {
210
+ const code=error?.code||error?.message;
211
+ return {status:'UNVERIFIED',reason:
212
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'RETRY_FAILED'};
213
+ }
201
214
  }, args: [target]
202
215
  });
203
216
  return execution?.result || {status:'UNVERIFIED',reason:'RETRY_RESULT_UNKNOWN'};
@@ -307,7 +320,11 @@ async function run() {
307
320
  let result;
308
321
  try { result = permit.retryMode === "NATIVE"
309
322
  ? await retryNativeOnce(permit.target) : await sendOnce(permit.target, permit.text); }
310
- catch (error) { result = {status: "UNVERIFIED", reason: error.message || "SEND_ERROR"}; }
323
+ catch (error) {
324
+ result = {status:"UNVERIFIED",reason:actionErrorCode(error)};
325
+ }
326
+ if(result.status==='UNVERIFIED')
327
+ result.reason=actionErrorCode({code:result.reason});
311
328
  const final = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_RESULT_V1", ...request,
312
329
  result: result.status, reason: result.reason, newUserKey: result.newUserKey, newPage: result.newPage});
313
330
  if (!(result.status === "SENT_CONFIRMED" || permit.retryMode === "NATIVE"
@@ -319,4 +336,5 @@ async function run() {
319
336
  }
320
337
  (new URLSearchParams(location.search).has("requestId")
321
338
  ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("continue")) : run())
322
- .catch(error => show("BLOCKED", error.message || "ACTION_FAILED"));
339
+ .catch(error => show("BLOCKED",
340
+ actionErrorCode(error,"ACTION_FAILED")));
@@ -3,6 +3,11 @@
3
3
  const statusNode = document.getElementById("status");
4
4
  const detailsNode = document.getElementById("details");
5
5
  const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
6
+ const actionErrorCode=(error,fallback='HANDOFF_ERROR')=>{
7
+ const code=error?.code||error?.message;
8
+ return typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
9
+ ?code:fallback;
10
+ };
6
11
  function show(status, details) {
7
12
  statusNode.textContent = status;
8
13
  detailsNode.textContent = details;
@@ -178,7 +183,11 @@ async function sendHandoffOnce(tabId, text) {
178
183
  throw Error("HANDOFF_INPUT_CHANGED_BEFORE_SEND");
179
184
  button.click();
180
185
  return {clickedOnce: true};
181
- } catch (error) {return {clickedOnce: false, reason: error.message || "HANDOFF_SEND_ERROR"};}
186
+ } catch (error) {
187
+ const code=error?.code||error?.message;
188
+ return {clickedOnce:false,reason:
189
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'HANDOFF_SEND_ERROR'};
190
+ }
182
191
  }, args: [text]
183
192
  });
184
193
  if (dispatch?.result?.clickedOnce !== true) throw Error(dispatch?.result?.reason || "HANDOFF_SEND_UNVERIFIED");
@@ -354,7 +363,11 @@ async function run() {
354
363
  }
355
364
  result = await sendHandoffOnce(newTab.id,
356
365
  message + notice + checkpoint + resumeCapability + (permit.modelTurnNote || ""));
357
- } catch (error) {result = {status: "UNVERIFIED", reason: error.message || "HANDOFF_ERROR"};}
366
+ } catch (error) {
367
+ result = {status:"UNVERIFIED",reason:actionErrorCode(error)};
368
+ }
369
+ if(result.status!=="SENT_CONFIRMED")
370
+ result.reason=actionErrorCode({code:result.reason});
358
371
  const committed = await chrome.runtime.sendMessage({type: "CHAT_LOOP_ACTION_RESULT_V1", ...request,
359
372
  result: result.status, reason: result.reason,
360
373
  newUserKey: result.newUserKey, newTabId: result.newTabId ?? newTab?.id,
@@ -367,7 +380,8 @@ async function run() {
367
380
  if (old && old.id !== newTab?.id && old.id !== own.id
368
381
  && old.url === "https://chatgpt.com" + permit.target.page) {
369
382
  await chrome.tabs.remove(old.id).catch(error => {
370
- console.warn("OLD_CHAT_TAB_CLEANUP_UNVERIFIED", error?.message);
383
+ console.warn("OLD_CHAT_TAB_CLEANUP_UNVERIFIED",
384
+ actionErrorCode(error,"TAB_CLEANUP_UNVERIFIED"));
371
385
  });
372
386
  }
373
387
  show("SUCCESS", "新 Chat 已收到交接包;旧 Chat 标签已尝试安全清理。");
@@ -375,4 +389,5 @@ async function run() {
375
389
  }
376
390
  (new URLSearchParams(location.search).has("requestId")
377
391
  ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("handoff")) : run())
378
- .catch(error => show("BLOCKED", error.message || "HANDOFF_ACTION_FAILED"));
392
+ .catch(error => show("BLOCKED",
393
+ actionErrorCode(error,"HANDOFF_ACTION_FAILED")));
@@ -37,9 +37,11 @@ export async function queueModelIntent(action) {
37
37
  } catch(e) {
38
38
  // An already-queued intent is not retried. Native failure is diagnostic only.
39
39
  try {
40
+ const rawCode=e?.code||e?.message;
41
+ const code=typeof rawCode==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
42
+ ?rawCode:'INTENT_UNVERIFIED';
40
43
  const saved=await chrome.runtime.sendNativeMessage(host,{
41
- op:'complete',id,nonce:auth.nonce,action,status:'FAILED',
42
- code:String(e.message||'INTENT_UNVERIFIED').slice(0,120)
44
+ op:'complete',id,nonce:auth.nonce,action,status:'FAILED',code
43
45
  });
44
46
  // The CLI already has a durable failure receipt. Keep the page only
45
47
  // when that receipt could not be verified; never resubmit the intent.
@@ -111,7 +111,11 @@ async function sendFirst(id,text){
111
111
  throw Error('START_INPUT_CHANGED');
112
112
  send.click(); // Once only. Worker persisted PENDING before this point.
113
113
  return {clickedOnce:true};
114
- }catch(e){return {clickedOnce:false,reason:e.message||'START_INPUT_UNKNOWN'};}
114
+ }catch(e){
115
+ const code=e?.code||e?.message;
116
+ return {clickedOnce:false,reason:
117
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'START_INPUT_UNKNOWN'};
118
+ }
115
119
  },args:[text]});
116
120
  if(clicked?.result?.clickedOnce!==true)
117
121
  throw Error(clicked?.result?.reason||'START_CLICK_UNVERIFIED');
@@ -275,8 +279,11 @@ async function run(){
275
279
  ...(proof.traceParent?{traceParent:proof.traceParent}:{}),
276
280
  ...(failureCode?{failureCode}:{})}).catch(()=>{});
277
281
  }
282
+ const rawCode=e?.code||e?.message;
283
+ const code=typeof rawCode==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(rawCode)
284
+ ?rawCode:'START_UNVERIFIED';
278
285
  const failed=await chrome.runtime.sendNativeMessage(host,{op:'complete',id,nonce:proof.nonce,
279
- action:'start',status:'FAILED',code:String(e.message||'START_UNVERIFIED').slice(0,100)}).catch(()=>null);
286
+ action:'start',status:'FAILED',code}).catch(()=>null);
280
287
  // Only the Action page closes after its durable FAILED receipt; the
281
288
  // possibly-sent Chat and any unverified draft remain untouched.
282
289
  if(failed?.status==='SAVED' && failed.id===id)
@@ -284,4 +291,5 @@ async function run(){
284
291
  throw e; // Never auto-retry a possibly clicked first user Turn.
285
292
  }
286
293
  }
287
- void run().catch(e=>show('BLOCKED',e.message||'START_UNVERIFIED'));
294
+ void run().catch(e=>show('BLOCKED',
295
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(e?.message||'')?e.message:'START_UNVERIFIED'));
@@ -19,5 +19,6 @@ async function run(){
19
19
  }
20
20
  void run().catch(e=>{
21
21
  document.getElementById('status').textContent='UNVERIFIED';
22
- document.getElementById('details').textContent=e.message||'STATUS_UNKNOWN';
22
+ document.getElementById('details').textContent=
23
+ /^[A-Z][A-Z0-9_]{1,95}$/.test(e?.message||'')?e.message:'STATUS_UNKNOWN';
23
24
  });
@@ -10,9 +10,9 @@ function createOrderedApiObservationSender(deliver,{parallel=8,capacity=2048}={}
10
10
  function pump(){
11
11
  scheduled=false;
12
12
  while(running<parallel){
13
- const position=waiting.findIndex(({record})=>!active.has(record.callId));
13
+ const position=waiting.findIndex(({callId})=>!active.has(callId));
14
14
  if(position<0)return;
15
- const [{record,resolve}]=waiting.splice(position,1),id=record.callId;
15
+ const [{record,callId,resolve}]=waiting.splice(position,1),id=callId;
16
16
  running++;active.add(id);
17
17
  let success=false;
18
18
  Promise.resolve().then(()=>deliver(record)).then(result=>{
@@ -36,12 +36,20 @@ function createOrderedApiObservationSender(deliver,{parallel=8,capacity=2048}={}
36
36
  }
37
37
  function send(record){
38
38
  health.submitted++;
39
+ // A malformed telemetry record must not throw later inside an unhandled
40
+ // queueMicrotask or mutate its ordering key after being queued.
41
+ let callId;
42
+ try{callId=record?.callId}catch{}
43
+ if(typeof callId!=='string'||!callId||callId.length>128){
44
+ health.dropped++;health.lastFailureCode='OBSERVATION_INVALID';
45
+ return Promise.resolve(false);
46
+ }
39
47
  if(waiting.length>=capacity){
40
48
  health.dropped++;
41
49
  health.lastFailureCode='OBSERVATION_QUEUE_FULL';
42
50
  return Promise.resolve(false);
43
51
  }
44
- return new Promise(resolve=>{waiting.push({record,resolve});schedule()});
52
+ return new Promise(resolve=>{waiting.push({record,callId,resolve});schedule()});
45
53
  }
46
54
  return Object.freeze({send,
47
55
  health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
@@ -20,7 +20,7 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
20
20
  const line=value.replace(/\s+/g," ").trim();
21
21
  if(!line||line.length>500)return false;
22
22
  // Native R/P review controls send two explicit, task-scoped fields:
23
- // "TASK|R2-ISSUE:<uuid>|我确认 R2 v2。..." (and likewise P2).
23
+ // "TASK|Rn-ISSUE:<uuid>|我确认 Rn vN。" (and the Pn equivalent).
24
24
  // Accept only a matching kind+version from a genuine user message,
25
25
  // never arbitrary prose containing an approval quote or TEST_ONLY.
26
26
  const native=line.match(/^([A-Z][A-Z0-9._:-]{7,120})[||]\s*([RP][1-9][0-9]*)-ISSUE:([0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12})[||]\s*我确认\s+([RP][1-9][0-9]*)\s+v([1-9][0-9]*)[。.!!]\s*(.{0,320})$/i);
@@ -59,7 +59,7 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
59
59
  // must not choose a version; ambiguous prose is not approval evidence.
60
60
  const versionOf=(value,type)=>{
61
61
  // Real formal reviews may start with a status recap mentioning an
62
- // older P2 before the issued heading "P3 v3|正式修订方案".
62
+ // an older plan version before the current issued revision heading.
63
63
  // A unique, version-consistent line title outranks historical prose.
64
64
  const issued=[...value.matchAll(new RegExp("(?:^|\\n)\\s*(?:#{1,6}\\s*)?("+type+"[1-9][0-9]*)\\s+v([1-9][0-9]*)\\s*[||]", "gi"))]
65
65
  .filter(x=>Number(x[1].slice(1))===Number(x[2]))
@@ -78,7 +78,7 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
78
78
  }
79
79
  const pUser=rows[lastUser],pAssistant=rows[lastUser-1];
80
80
  // A plan document explicitly withheld in PLAN_DRAFT is not an issued
81
- // review. A user cannot make it effective by typing a P1 approval after
81
+ // review. A user cannot make it effective by typing a plan approval after
82
82
  // the assistant said the current plan was not presented for approval.
83
83
  if(/(?:当前阶段[::]\s*PLAN_DRAFT|(?:维持|保持|仍为|停留在)\s*PLAN_DRAFT|方案(?:草稿)?.{0,20}(?:尚未|未曾|没有)正式(?:发布|提交)|(?:暂不|不(?:予|会|再)?)展示.{0,12}提交方案评审)/i.test(textOf(pAssistant))){
84
84
  fail("APPROVAL_PLAN_NOT_ISSUED");return false;
@@ -95,9 +95,9 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
95
95
  }
96
96
  const rIndex=rows.slice(0,lastUser-1).findLastIndex(x=>x.role==="user"
97
97
  &&confirms(textOf(x),"R"));
98
- // Long chats virtualize old turns. A still-mounted native R2 user
99
- // approval at index 0 has its exact issued R2-ISSUE identity, even when
100
- // the original R2 assistant has scrolled out of the DOM window.
98
+ // Long chats virtualize old turns. A still-mounted native Rn user
99
+ // approval at index 0 retains its exact issue identity, even when
100
+ // the issuing assistant has scrolled out of the DOM window.
101
101
  // This fallback is ONLY for native issue-scoped approvals. The Native
102
102
  // Context Start lease independently verifies the effective R approval.
103
103
  const rUser=rIndex>=0?rows[rIndex]:null;
@@ -148,7 +148,8 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
148
148
  const next=versionOf(text,"R");
149
149
  return /需求|范围|验收/.test(text)&&next&&next!==rVersion;
150
150
  }
151
- // "修订 P3、保留 R2" is a plan update, NOT an R2 revocation.
151
+ // Updating a plan while retaining the approved requirement is NOT
152
+ // a requirement revocation.
152
153
  // Only an explicit requirement-targeted change invalidates this R.
153
154
  return /(?:撤销|取消|拒绝|不同意|不批准|修改|修订|变更)\s*(?:(?:当前|本次|这份|上述)\s*)?(?:需求|R[1-9][0-9]*)/i.test(text)
154
155
  || /\bR[1-9][0-9]*\b\s*(?:需求)?\s*(?:需要|应当|应该)?\s*(?:撤销|取消|拒绝|修改|修订|变更)/i.test(text);
@@ -165,8 +166,8 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
165
166
  fail("APPROVAL_REQUIREMENTS_VERSION_MISMATCH");return false;
166
167
  }
167
168
  // An explicit Chat URL may be adopted after the P-approval assistant
168
- // finishes, but that reply might instead have issued R2/P2. Such a
169
- // revision invalidates the earlier P1 approval even if the last user
169
+ // finishes, but that reply might instead have issued newer R/P
170
+ // revisions, invalidating an earlier P approval even if the last user
170
171
  // message is still the old standalone confirmation.
171
172
  const revisedAfterApproval=rows.slice(lastUser+1).some(x=>{
172
173
  if(x.role!=="assistant")return false;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.4.12",
4
+ "version": "0.4.13",
5
5
  "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -69,10 +69,16 @@ async function showActionState() {
69
69
  ? "最近发送动作:" + run.action + " · " + run.phase + (run.reason ? " · " + run.reason : "")
70
70
  : "尚无发送动作记录";
71
71
  }
72
- void showActionState().catch(() => {
73
- document.getElementById("action-state").textContent = "最近发送动作:状态无法确认,不要重复发送";
72
+ const stateUnavailable=()=>{
73
+ document.getElementById("action-state").textContent =
74
+ "最近发送动作:状态无法确认,不要重复发送";
75
+ };
76
+ void showActionState().catch(stateUnavailable);
77
+ chrome.storage.onChanged.addListener((changes,area)=>{
78
+ // Unrelated storage churn must not repeatedly reread the Owner projection.
79
+ if(area==='local'&&Object.hasOwn(changes,'chat-loop.action.run.v1'))
80
+ void showActionState().catch(stateUnavailable);
74
81
  });
75
- chrome.storage.onChanged.addListener(() => {void showActionState();});
76
82
 
77
83
  // User-clicked menu action only; bind to the single active ChatGPT tab.
78
84
  document.getElementById('clean-action').addEventListener('click',async()=>{
@@ -78,8 +78,8 @@ async function onResult(message, sender) {
78
78
  }
79
79
  // A model prompt is one-shot. Keep only a short receipt, not the prompt
80
80
  // body, after the Action has reached a confirmed or blocked terminal state.
81
- // The kickoff exception applies to ONE historical P3 reply only.
82
- // Remove it after this send attempt; subsequent Continue Turns must carry
81
+ // The Adopt kickoff exception applies only to the verified pre-Adopt
82
+ // assistant reply. Remove it after this send; later Turns must carry
83
83
  // ordinary independent terminal markers and never inherit the exception.
84
84
  if(run.recoveryMode==="ADOPT_KICKOFF")delete next.recoveryMode;
85
85
  if(run.modelIntent){
@@ -55,7 +55,7 @@ async function onTake(message, sender) {
55
55
  const snapshot=await chrome.runtime.sendNativeMessage(SESSION_HOST,{
56
56
  op:"context-control",command:"run.snapshot",args:{}}).catch(()=>null);
57
57
  const cp=snapshot?.result;
58
- if(snapshot?.status!=="OK" || cp.taskRevision!==h.taskRevision
58
+ if(snapshot?.status!=="OK" || !cp || cp.taskRevision!==h.taskRevision
59
59
  ||cp.bindingRevision!==h.bindingRevision ||cp.runRef!==null
60
60
  ||cp.checkpointId!==h.checkpointId ||cp.unknownEffectCount!==0){
61
61
  await saveRun({...run,phase:"BLOCKED",reason:"CONTEXT_RESTORE_SNAPSHOT_UNVERIFIED"});
@@ -191,9 +191,9 @@ async function onTake(message, sender) {
191
191
  ? {id:run.modelIntent.id,nextPrompt:run.modelIntent.nextPrompt} : null,
192
192
  text: run.action === "HANDOFF" ? run.handoffText || null
193
193
  : run.recoveryMode==="TOOL_PREFLIGHT_REPAIRED"
194
- ? "【Chat Loop 同 Chat 受控恢复】上一轮以 BLOCKED 结束;当前恢复已通过唯一 Owner、原 Chat 和 Native 身份核验,但不代表工程问题已自动解决。不要再次调用 Start、不要新建 Chat、不要重复 R/P 审批。首先核实原工作区真实状态、已执行副作用和当前 Tools 可调用能力,再依据原任务唯一检查点继续尚未完成的工作、测试与迭代;若仍有真实风险如实 BLOCKED,不要再次反复自恢复。本轮结束末行独立输出 [CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。"
194
+ ? "【Chat Loop 同 Chat 受控恢复】上一轮以 BLOCKED 结束;当前仅核实了唯一 Owner、原 Chat 和 Native 身份,不代表原任务阻断已解决。不要再次 Start、另建执行 Chat 或重复 R/P。先核实当前项目与任务事实、既有副作用、故障原因及 Tools 权限,再按唯一可信检查点处理可安全推进的工作;无法核实或相同阻断仍存在时报告 BLOCKED,不自行重复恢复或未知副作用。末行独立输出 [CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。"
195
195
  : run.recoveryMode==="ADOPT_KICKOFF"
196
- ? "【Chat Loop 原 Chat 已正式 Start/adopt】这是当前已批准 R2/P3 Task 的第一条受控执行消息,不是新的需求或审批。请从真实 Context 读取 Task、已批准的计划及 Stage03 QA 报告,完成剩余可安全的验收工作项;不得重做旧 H UNKNOWN 首发,不得新建执行 Chat,也不得重复 R/P。若所有批准的工作项确实满足 DONE,先按 SDK 正式提交 Task delivery(没有权限则不要伪造),再输出唯一 DONE 状态;存在安全的待做工作则输出 CONTINUE,关键身份/副作用不可信则输出 BLOCKED。末行独立输出 [CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。"
196
+ ? "【Chat Loop 原 Chat 已正式 Start/adopt】这是已批准任务的首个受控执行轮次,不是新的需求或审批。先核实当前 Project/Task、Context 写权、R/P 精确有效版本、已批准的 Pn 工作项和未知副作用;按现行计划执行,不套用其他项目的旧任务、文档或测试报告。不要新建执行 Chat,不得重复 R/P 或重试未知副作用。所有必需工作与验收证据齐全后,按 Context SDK 正式完成 Task,并在终态门禁成立后才报 DONE;有安全待办则 CONTINUE,身份、权限或副作用无法核实则 BLOCKED。末行独立输出 [CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。"
197
197
  : run.modelIntent?.action==="CONTINUE" ? (
198
198
  "【Chat Loop 续接来源】上一轮由模型登记的 Continue 请求 " + run.modelIntent.id
199
199
  + " 已被扩展唯一 Action 领取。\n"
@@ -202,17 +202,15 @@ async function onTake(message, sender) {
202
202
  + "执行前核对当前项目状态、既有用户授权和已完成副作用,不重做不明操作。"
203
203
  + "本轮完成后,末行只输出一个状态标记:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。")
204
204
  : CONTINUE_TEXT};
205
- // A single error contract applies to default, model-specified and repaired
206
- // Continue prompts; the Worker still obeys the model's terminal marker.
207
- if(run.action==="CONTINUE" && typeof permit.text==="string"){
208
- permit.text=ENGINEERING_FAILURE_NOTE+"\n\n"+permit.text;
209
- if(recoveredContext){
210
- permit.text += "\n\n【Chat Loop Context|HANDOFF_NOT_SENT 单次恢复写凭据】\n"
205
+ // Only the verified HANDOFF_NOT_SENT recovery may receive a write
206
+ // credential. Healthy continuation must not inherit engineering-specific
207
+ // failure instructions or unrelated historical Task details.
208
+ if(run.action==="CONTINUE" && typeof permit.text==="string" && recoveredContext){
209
+ permit.text += "\n\n【Chat Loop Context|HANDOFF_NOT_SENT 单次恢复写凭据】\n"
211
210
  +JSON.stringify({projectId:run.projectId,taskId:run.taskId,
212
211
  sessionId:run.sessionId,generation:run.generation||0,
213
212
  ...recoveredContext})+"\n请先按原 Session 核实 Context 与未知副作用,"
214
213
  +"此凭据仅用于当前任务 Context 写入;旧 Handoff 不得重新发送。";
215
- }
216
214
  }
217
215
  if (modelTurnToken && typeof permit.text === "string")
218
216
  permit.text += permit.modelTurnNote;
@@ -48,9 +48,14 @@ async function sessionStartPrepare(message,sender){
48
48
  return {status:'DENIED',code:'LOOP_ALREADY_ACTIVE'};
49
49
  const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,{op:'session-read'}).catch(()=>null);
50
50
  if(disk?.status!=='OK')return {status:'DENIED',code:'SESSION_STATE_UNVERIFIED'};
51
- if(matchingBlocked&&(!disk.session||disk.session.phase!=='BLOCKED'
52
- ||disk.session.sessionId!==replace||disk.session.projectId!==prior.projectId))
51
+ const ownerMatches=Boolean(prior?.sessionId&&disk.session
52
+ &&matchesNativeProjection(sessionProjection(prior),disk.session));
53
+ if(matchingBlocked&&!ownerMatches)
53
54
  return {status:'DENIED',code:'SESSION_REPLACEMENT_MISMATCH'};
55
+ // A terminal Worker record cannot authorize a new Start if a different
56
+ // durable Native Owner exists under the same Browser installation.
57
+ if(prior?.phase==='DONE'&&prior.sessionId&&disk.session&&!ownerMatches)
58
+ return {status:'DENIED',code:'SESSION_OWNER_MISMATCH'};
54
59
  // An abandoned Managed Context writer can outlive its Browser Owner.
55
60
  // Replacing the Native session without first verifying its terminal fence
56
61
  // would strand a live runRef (and an old write credential) in the Store.
@@ -142,7 +142,8 @@ async function onAdoptBaselineRepair(message,sender){
142
142
  return {status:'DENIED',code:'ADOPT_BASELINE_OBSERVER_UNVERIFIED'};
143
143
  await saveRun({...prior,phase:'RESERVED',
144
144
  reason:'ADOPT_BASELINE_RECOVERY',
145
- recoveryMode:'ADOPT_IDLE_BASELINE',recoveryAttempts:1});
145
+ recoveryMode:'ADOPT_IDLE_BASELINE',recoveryAttempts:1,
146
+ recoveryExpectedNativeAt:disk.session.updatedAt});
146
147
  const clean={...prior,phase:'WAITING_REPLY',reason:'ADOPTED_IDLE_BASELINE',
147
148
  recoveryAttempts:1,userKey:prior.newUserKey,assistantKey:prior.assistantKey};
148
149
  delete clean.recoveryMode;
@@ -43,7 +43,13 @@ async function sessionStartResult(message,sender){
43
43
  // Four-hour execution clock begins at confirmed enrollment, not at
44
44
  // the UI approval or potentially long Start readiness/preparation.
45
45
  const adoptedIdle=confirmed&&adopted&&!!run.adoptPostApprovalAssistantKey;
46
- const next={...run,phase:confirmed?'WAITING_REPLY':'BLOCKED',
46
+ const next={...run,
47
+ // Protect the crash window between a confirmed browser send and Native
48
+ // run.bind.initial. This marks the session as Context-governed, NOT as
49
+ // successfully bound; subsequent DONE/Continue must verify the real Store.
50
+ ...(confirmed&&run.contextLeaseRef
51
+ ?{contextManaged:{storeEpoch:run.contextStoreEpoch}}:{}),
52
+ phase:confirmed?'WAITING_REPLY':'BLOCKED',
47
53
  startedAt:confirmed?Date.now():run.startedAt,
48
54
  lastStartActionTabId:sender.tab.id,
49
55
  ...(adoptedIdle?{assistantKey:run.adoptPostApprovalAssistantKey,
@@ -4,10 +4,16 @@ const RUN_KEY = "chat-loop.action.run.v1";
4
4
  const SESSION_HOST = "com.tomflow.chatloop.extension";
5
5
  const ALARM_NAME = "chat-loop.turn-watch.v1";
6
6
  const DEADLINE_ALARM_NAME = "chat-loop.handoff-deadline.v1";
7
- const ENGINEERING_FAILURE_NOTE = "【故障边界】编译或测试失败应诊断修复,不是网页运行错误。MCP 初始化或连接临时失败时,先核查已启动进程与未知副作用;只有确认后续是安全只读操作,才可针对本次独立故障再安排一次跨轮复核并输出 CONTINUE。若同一故障复核仍无进展,或消息发送结果、Owner、审批、权限不可信,则 BLOCKED,绝不重复执行未知副作用。不同故障分别判断,不能沿用旧故障的重试次数。";
8
- const CONTINUE_TEXT = "继续当前任务,完成本轮后只在末行写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
7
+ const CONTINUE_TEXT = "继续当前已授权任务,先核实真实进度、权限和已发生副作用;UNKNOWN 只查原回执,不盲目重试,也不把续接视为新增授权。完成本轮后末行只写一个状态:[CHAT_LOOP_STATUS:CONTINUE]、[CHAT_LOOP_STATUS:DONE] 或 [CHAT_LOOP_STATUS:BLOCKED]。";
9
8
  const turnToolNote = token => "\n\n【Chat Loop 本轮工具凭证】只有本轮需要自定下一轮内容或提前交接时,才能调用 chat_loop_extension__continue / chat_loop_extension__handoff;参数 turnToken 填写 " + token + "。工具只登记意图,不等待本轮结束,不直接发送;请照常在本轮结束时输出 CONTINUE、DONE 或 BLOCKED 标记。不要在助手正文重复该凭证。";
10
9
  let queue = Promise.resolve();
10
+ // Business callbacks expose typed, bounded error codes only; raw messages can
11
+ // contain native paths, browser state or extension internals.
12
+ const safeWorkerErrorCode=(failure,fallback)=>{
13
+ const code=failure?.code||failure?.message;
14
+ return typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
15
+ ?code:fallback;
16
+ };
11
17
  const serial = fn => {
12
18
  const work = queue.then(fn);
13
19
  queue = work.catch(() => {});
@@ -84,6 +90,9 @@ async function saveRun(run) {
84
90
  const recoveryCommit=next.sessionId&&next.phase==="RESERVED"
85
91
  &&["TOOL_PREFLIGHT_REPAIRED","HANDOFF_NOT_SENT","ADOPT_IDLE_BASELINE"].includes(next.recoveryMode)
86
92
  &&next.recoveryAttempts>=1&&stored?.phase==="BLOCKED";
93
+ if(recoveryCommit&&(!Number.isSafeInteger(next.recoveryExpectedNativeAt)
94
+ ||next.recoveryExpectedNativeAt<=0))
95
+ throw Error('SESSION_RECOVERY_CAS_MISSING');
87
96
  const syncNative=async()=>{
88
97
  if(!next.sessionId)return;
89
98
  const record=sessionProjection(next);
@@ -92,9 +101,11 @@ async function saveRun(run) {
92
101
  ...(next.replacedBlockedSessionId&&!recoveryCommit&&next.phase==='STARTING'
93
102
  ?{replaceBlockedSessionId:next.replacedBlockedSessionId}:{}),
94
103
  ...(recoveryCommit?{resumeBlockedSessionId:next.sessionId,
95
- ...(next.recoveryExpectedNativeAt?{resumeBlockedUpdatedAt:next.recoveryExpectedNativeAt}:{})}:{})}).catch(()=>null);
96
- if(saved?.status!=="OK"||saved.session?.sessionId!==next.sessionId
97
- ||saved.session?.phase!==next.phase)
104
+ resumeBlockedUpdatedAt:next.recoveryExpectedNativeAt}:{})}).catch(()=>null);
105
+ // Native acknowledgment must match the whole immutable Owner pointer,
106
+ // not merely its sessionId and phase. updatedAt is CAS metadata, not
107
+ // part of this identity projection.
108
+ if(saved?.status!=="OK"||!matchesNativeProjection(record,saved.session))
98
109
  throw Error(saved?.code||"SESSION_PERSISTENCE_UNVERIFIED");
99
110
  };
100
111
  // A terminal BLOCKED session may resume only after native CAS first.
@@ -116,18 +116,17 @@ async function onManualPrepare(message, sender) {
116
116
  || !/目标/.test(summary) || !/已完成|进度/.test(summary)
117
117
  || !/下一步|待办/.test(summary)))
118
118
  return {status: "DENIED", code: "HANDOFF_PACKET_MISSING"};
119
+ let recoveryExpectedNativeAt=null;
119
120
  if(ownedRecovery){
120
121
  const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
121
122
  {op:"session-read"}).catch(()=>null);
122
- if(disk?.status!=="OK"||disk.session?.sessionId!==previous.sessionId
123
- ||disk.session.phase!=="BLOCKED"
124
- ||disk.session.projectId!==previous.projectId
125
- ||disk.session.generation!==(previous.generation||0)
126
- ||disk.session.activeChatId!==chatIdOf(tab.url)
123
+ if(disk?.status!=="OK"
124
+ ||!matchesNativeProjection(sessionProjection(previous),disk.session)
127
125
  ||resumeAt&&disk.session.updatedAt!==resumeAt
128
126
  ||contextAt&&disk.session.updatedAt!==contextAt
129
127
  ||legacyAt&&(!legacyUnsent||disk.session.updatedAt!==legacyAt))
130
128
  return {status:"DENIED",code:"BLOCKED_OWNER_PERSISTENCE_UNVERIFIED"};
129
+ recoveryExpectedNativeAt=disk.session.updatedAt;
131
130
  }
132
131
  const token = crypto.randomUUID();
133
132
  await saveRun({...(ownedRecovery?previous:{}),
@@ -137,8 +136,7 @@ async function onManualPrepare(message, sender) {
137
136
  manualActionTabId: sender.tab.id,
138
137
  ...(ownedRecovery?{recoveryMode:contextNotSent?"HANDOFF_NOT_SENT":"TOOL_PREFLIGHT_REPAIRED",
139
138
  recoveryAttempts:(previous.recoveryAttempts||0)+1,recoveryProtocol:1,
140
- ...(resumeAt||legacyUnsent||contextNotSent
141
- ?{recoveryExpectedNativeAt:contextAt||resumeAt||legacyAt}:{}),
139
+ recoveryExpectedNativeAt,
142
140
  ...(contextNotSent?{contextSourceMarker:"[CHAT_LOOP_STATUS:"+modelStatus+"]",
143
141
  contextRecoveryCredential:Array.from(crypto.getRandomValues(new Uint8Array(32)),
144
142
  x=>x.toString(16).padStart(2,"0")).join(""),
@@ -79,7 +79,7 @@ const onBrowserMessage=(message, sender, reply, dispatchParent=null) => {
79
79
  let result;
80
80
  try{result=await handle(type==='CHAT_LOOP_SESSION_STATUS_V1'
81
81
  ?{...message,auditDispatchParent:dispatchParent}:message,sender);}
82
- catch(error){result={status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'};}
82
+ catch(error){result={status:'BLOCKED',code:safeWorkerErrorCode(error,'SCHEDULER_ERROR')};}
83
83
  // A bounded diagnostic receipt, never permission or a second state store.
84
84
  // In particular a rejected manual recovery must be observable remotely.
85
85
  if(type==='CHAT_LOOP_ACTION_MANUAL_PREPARE_V1'){
@@ -89,7 +89,7 @@ const onBrowserMessage=(message, sender, reply, dispatchParent=null) => {
89
89
  code:/^[A-Z0-9_]{1,100}$/.test(result.code||'')?result.code:null,at:Date.now()}}});
90
90
  }
91
91
  return result;
92
- }).then(reply,error=>reply({status:'BLOCKED',code:error.message||'SCHEDULER_ERROR'}));
92
+ }).then(reply,error=>reply({status:'BLOCKED',code:safeWorkerErrorCode(error,'SCHEDULER_ERROR')}));
93
93
  return true;
94
94
  }
95
95
  if (type === 'CHAT_LOOP_POPUP_CLEAN_OPEN_V1') {
@@ -104,6 +104,7 @@ const onBrowserMessage=(message, sender, reply, dispatchParent=null) => {
104
104
  }
105
105
  if (type !== "CHAT_LOOP_EYE_RELOAD_V1") return false;
106
106
  const id = sender.tab?.id;
107
+ let acknowledged=false;
107
108
  void (async () => {
108
109
  try {
109
110
  if (!Number.isInteger(id)) throw Error("NO_ACTION_TAB");
@@ -113,6 +114,9 @@ const onBrowserMessage=(message, sender, reply, dispatchParent=null) => {
113
114
  (tab.url!==reloadBase &&
114
115
  !/^\?requestId=[a-f0-9]{32}$/.test(tab.url.slice(reloadBase.length))))
115
116
  throw Error("INVALID_RELOAD_SOURCE");
117
+ // Acknowledgement is deliberately not a verified reload result.
118
+ // Once sent, never issue a second contradictory callback.
119
+ acknowledged=true;
116
120
  reply({status: "ACCEPTED"});
117
121
  await chrome.tabs.remove(id);
118
122
  // Reload terminates pending MV3 Native Messaging Promises immediately.
@@ -129,7 +133,12 @@ const onBrowserMessage=(message, sender, reply, dispatchParent=null) => {
129
133
  }
130
134
  }catch{/* Audit cannot change the accepted business result. */}
131
135
  chrome.runtime.reload();
132
- } catch (error) {reply({status: "FAILED", code: error.message});}
136
+ } catch (error) {
137
+ if(!acknowledged)
138
+ reply({status: "FAILED", code: safeWorkerErrorCode(error,'RELOAD_UNVERIFIED')});
139
+ // After ACCEPTED, the caller retains ACCEPTED_UNVERIFIED and must
140
+ // recheck the same extension instance; no automatic replay.
141
+ }
133
142
  })();
134
143
  return true;
135
144
  };
@@ -1,5 +1,11 @@
1
1
  // Chat Loop Worker — scheduler. Imported in order by background.js; no independent Browser Owner.
2
2
  // Extension updates invalidate previous injected listeners. Reconnect only its own observers.
3
+ // A detached alarm/reconnect must settle its own failure, not create a
4
+ // second scheduler or implicitly repeat a browser Action.
5
+ const observeBackground=(work,scope)=>{
6
+ void work.catch(error=>console.warn('CHAT_LOOP_SCHEDULER_UNVERIFIED',
7
+ scope,safeWorkerErrorCode(error,'SCHEDULER_ERROR')));
8
+ };
3
9
  async function reconnectOpenChats() {
4
10
  const tabs = await chrome.tabs.query({url: "https://chatgpt.com/*"});
5
11
  for (const tab of tabs) {
@@ -30,9 +36,14 @@ async function reconnectOpenChats() {
30
36
  startedAt: owner.startedAt
31
37
  }).catch(() => null);
32
38
  if (res?.status !== "RESUMED" && res?.status !== "ALREADY_MONITORING")
33
- console.warn("Chat Loop pending Turn resume not yet verified:", res?.reason || res?.status);
39
+ console.warn("CHAT_LOOP_TURN_RESUME_UNVERIFIED",
40
+ safeWorkerErrorCode({code:res?.reason||res?.status},
41
+ "OBSERVER_RESUME_UNVERIFIED"));
34
42
  }
35
- } catch (error) {console.warn("Chat Loop observer reconnect unavailable:", error?.message);}
43
+ } catch (error) {
44
+ console.warn("CHAT_LOOP_OBSERVER_RECONNECT_UNVERIFIED",
45
+ safeWorkerErrorCode(error,"OBSERVER_RECONNECT_UNVERIFIED"));
46
+ }
36
47
  }
37
48
  }
38
49
  // MV3 background service workers can suspend, and hidden-page setInterval
@@ -85,47 +96,50 @@ async function watchActiveTurn() {
85
96
  // A human response can fail after the previous question was kept in
86
97
  // WAITING_REPLY. Do not let this become an indefinite silent wait.
87
98
  if(freshHuman && proof.status==="BLOCKED") {
88
- void serial(()=>onTurnBlocked({page:run.page,userKey:proof.userKey,
99
+ observeBackground(serial(()=>onTurnBlocked({page:run.page,userKey:proof.userKey,
89
100
  reason:proof.reason||"PAGE_ERROR"},
90
- {tab,url:tab.url}));
101
+ {tab,url:tab.url})),'HUMAN_TURN_RECOVERY');
91
102
  }
92
103
  // Alarm is still read-only. It may reconcile a verified page failure if
93
104
  // the observer's original notification was lost while Worker slept.
94
105
  if (run?.phase === "WAITING_REPLY" && run.tabId === tab.id
95
106
  && proof?.status === "BLOCKED" && ["PAGE_ERROR","CONTEXT_LIMIT","SECURITY_CHALLENGE"].includes(proof.reason)
96
107
  && proof.page === run.page && proof.userKey === run.newUserKey) {
97
- void serial(() => onTurnBlocked({page: run.page,
108
+ observeBackground(serial(() => onTurnBlocked({page: run.page,
98
109
  userKey: run.newUserKey, reason: proof.reason},
99
- {tab, url: tab.url}));
110
+ {tab, url: tab.url})),'TURN_FAILURE_RECOVERY');
100
111
  }
101
112
  } catch { /* Observer unavailable; never infer Turn completion. */ }
102
113
  }
103
114
  }
104
115
  chrome.alarms?.onAlarm?.addListener(alarm => {
105
- if (alarm?.name === ALARM_NAME) void watchActiveTurn();
116
+ if (alarm?.name === ALARM_NAME)
117
+ observeBackground(watchActiveTurn(),'TURN_WATCH_ALARM');
106
118
  if (alarm?.name === DEADLINE_ALARM_NAME)
107
- void serial(prepareHandoffIfDue);
119
+ observeBackground(serial(prepareHandoffIfDue),'HANDOFF_DEADLINE_ALARM');
108
120
  });
109
121
  chrome.runtime.onInstalled?.addListener(() => {
110
- void ensureAlarm();
111
- void serial(async()=>{await expireStaleAction();
112
- await resources.reconcile(await readRun()).catch(()=>{});});
113
- void reconnectOpenChats();
122
+ observeBackground(ensureAlarm(),'ALARM_SETUP');
123
+ observeBackground(serial(async()=>{await expireStaleAction();
124
+ await resources.reconcile(await readRun()).catch(()=>{});}),
125
+ 'INSTALL_RECONCILIATION');
126
+ observeBackground(reconnectOpenChats(),'CHAT_RECONNECT');
114
127
  });
115
128
  chrome.runtime.onStartup?.addListener(() => {
116
- void ensureAlarm();
117
- void serial(async()=>{await expireStaleAction();
118
- await resources.reconcile(await readRun()).catch(()=>{});});
119
- void reconnectOpenChats();
129
+ observeBackground(ensureAlarm(),'ALARM_SETUP');
130
+ observeBackground(serial(async()=>{await expireStaleAction();
131
+ await resources.reconcile(await readRun()).catch(()=>{});}),
132
+ 'INSTALL_RECONCILIATION');
133
+ observeBackground(reconnectOpenChats(),'CHAT_RECONNECT');
120
134
  });
121
- void ensureAlarm();
135
+ observeBackground(ensureAlarm(),'ALARM_SETUP');
122
136
  // Reconcile an elapsed deadline after MV3 Worker suspension/reload.
123
- void serial(async()=>{await expireStaleAction();
137
+ observeBackground(serial(async()=>{await expireStaleAction();
124
138
  await resources.reconcile(await readRun()).catch(()=>{});
125
- await prepareHandoffIfDue();});
139
+ await prepareHandoffIfDue();}),'STARTUP_RECONCILIATION');
126
140
  // A manual extension Reload does not necessarily fire onInstalled/onStartup.
127
141
  // Reattach the two idempotent read-only scripts to existing ChatGPT tabs.
128
- void reconnectOpenChats();
142
+ observeBackground(reconnectOpenChats(),'CHAT_RECONNECT');
129
143
  // User-clicked popup Clean must share the same Action quota as Worker actions.
130
144
  // The popup cannot create extra Chrome tabs directly.
131
145
  async function openPopupClean(message,sender) {
@@ -142,6 +156,6 @@ async function openPopupClean(message,sender) {
142
156
  +'?tabId='+target.id,windowId:target.windowId,active:true});
143
157
  return {status:'OK',actionTabId:action.id};
144
158
  } catch(error) {
145
- return {status:'BLOCKED',code:error?.message||'CLEAN_ACTION_UNVERIFIED'};
159
+ return {status:'BLOCKED',code:safeWorkerErrorCode(error,'CLEAN_ACTION_UNVERIFIED')};
146
160
  }
147
161
  }
@@ -23,6 +23,14 @@ async function onTurnFinished(message, sender) {
23
23
  return {status: "IGNORED", code: "ALREADY_HANDLED"};
24
24
  if (previous.phase !== "WAITING_REPLY")
25
25
  return {status: "IGNORED", code: "INVALID_PHASE"};
26
+ // Previous extension versions may have persisted a confirmed first send
27
+ // before recording whether its Context bind completed. Do not downgrade
28
+ // such an Owner to unmanaged execution on Worker restart or upgrade.
29
+ if(previous.contextLeaseRef&&!previous.contextManaged){
30
+ await saveRun({...previous,phase:'BLOCKED',
31
+ reason:'CONTEXT_INITIAL_BIND_UNVERIFIED'});
32
+ return {status:'BLOCKED',code:'CONTEXT_INITIAL_BIND_UNVERIFIED'};
33
+ }
26
34
  // A clicked ChatGPT choice creates a regular NEW user Turn. Its preceding
27
35
  // assistant must be the exact already-handled question from this Owner, with
28
36
  // no intervening user messages. This keeps the old identity boundary
@@ -169,7 +177,7 @@ async function onTurnFinished(message, sender) {
169
177
  return {status: "QUEUED", actionTabId: actionTab.id};
170
178
  } catch (error) {
171
179
  await saveRun({...recorded, phase: "BLOCKED", reason: "ACTION_PAGE_CREATE_FAILED"});
172
- return {status: "BLOCKED", code: error.message || "ACTION_PAGE_CREATE_FAILED"};
180
+ return {status: "BLOCKED", code: safeWorkerErrorCode(error,"ACTION_PAGE_CREATE_FAILED")};
173
181
  }
174
182
  }
175
183
  // Recover ONLY an interrupted pre-send reservation from the old Worker
@@ -185,11 +193,8 @@ async function repairUncommittedBlockedRecovery(){
185
193
  return run;
186
194
  const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
187
195
  {op:"session-read"}).catch(()=>null);
188
- if(disk?.status!=="OK"||disk.session?.phase!=="BLOCKED"
189
- ||disk.session.sessionId!==run.sessionId
190
- ||disk.session.projectId!==run.projectId
191
- ||disk.session.generation!==(run.generation||0)
192
- ||disk.session.activeChatId!==chatIdOf("https://chatgpt.com"+run.page))
196
+ if(disk?.status!=="OK"
197
+ ||!matchesNativeProjection(sessionProjection({...run,phase:"BLOCKED"}),disk.session))
193
198
  return run;
194
199
  const restored={...run,phase:"BLOCKED",reason:"BLOCKED",recoveryAttempts:0};
195
200
  for(const field of ["recoveryMode","recoverySourceAssistantKey","token",
@@ -10,9 +10,9 @@ export function createOrderedApiObservationSender(deliver,{parallel=8,capacity=2
10
10
  function pump(){
11
11
  scheduled=false;
12
12
  while(running<parallel){
13
- const position=waiting.findIndex(({record})=>!active.has(record.callId));
13
+ const position=waiting.findIndex(({callId})=>!active.has(callId));
14
14
  if(position<0)return;
15
- const [{record,resolve}]=waiting.splice(position,1),id=record.callId;
15
+ const [{record,callId,resolve}]=waiting.splice(position,1),id=callId;
16
16
  running++;active.add(id);
17
17
  let success=false;
18
18
  Promise.resolve().then(()=>deliver(record)).then(result=>{
@@ -36,12 +36,20 @@ export function createOrderedApiObservationSender(deliver,{parallel=8,capacity=2
36
36
  }
37
37
  function send(record){
38
38
  health.submitted++;
39
+ // A malformed telemetry record must not throw later inside an unhandled
40
+ // queueMicrotask or mutate its ordering key after being queued.
41
+ let callId;
42
+ try{callId=record?.callId}catch{}
43
+ if(typeof callId!=='string'||!callId||callId.length>128){
44
+ health.dropped++;health.lastFailureCode='OBSERVATION_INVALID';
45
+ return Promise.resolve(false);
46
+ }
39
47
  if(waiting.length>=capacity){
40
48
  health.dropped++;
41
49
  health.lastFailureCode='OBSERVATION_QUEUE_FULL';
42
50
  return Promise.resolve(false);
43
51
  }
44
- return new Promise(resolve=>{waiting.push({record,resolve});schedule()});
52
+ return new Promise(resolve=>{waiting.push({record,callId,resolve});schedule()});
45
53
  }
46
54
  return Object.freeze({send,
47
55
  health:()=>Object.freeze({...health,pending:waiting.length,inFlight:running})});
package/lib/bridge.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import {randomUUID} from 'node:crypto';
2
- import {existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync} from 'node:fs';
2
+ import {existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync} from 'node:fs';
3
3
  import {homedir, tmpdir} from 'node:os';
4
4
  import {join} from 'node:path';
5
5
 
@@ -174,7 +174,9 @@ export function finish({id,nonce,action,status,payload='',code=null}) {
174
174
  bytes=buf.length;
175
175
  if(filename)writeFileSync(join(dir,filename),buf,{flag:'wx',mode:0o600});
176
176
  }
177
- const rec={id,action,status,code:status==='FAILED'?(String(code||'ACTION_FAILED').slice(0,120)):null,
177
+ const failureCode=typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
178
+ ?code:'ACTION_FAILED';
179
+ const rec={id,action,status,code:status==='FAILED'?failureCode:null,
178
180
  path:filename?join(dir,filename):null,bytes,mimeType,at:Date.now(),
179
181
  verified:action!=='reload'};
180
182
  writeFileSync(resultPath+'.tmp',JSON.stringify(rec),{flag:'wx',mode:0o600});
@@ -182,11 +184,43 @@ export function finish({id,nonce,action,status,payload='',code=null}) {
182
184
  return rec;
183
185
  }
184
186
  export function readResult(id) {
185
- const p=join(requestDir(id),'result.json');
187
+ const dir=requestDir(id),p=join(dir,'result.json');
186
188
  if(!pathEntryExists(p))return null;
187
- privateDir(requestDir(id));
189
+ privateDir(dir);
188
190
  privateRecord(p,'UNTRUSTED_RESULT');
189
- return JSON.parse(readFileSync(p,'utf8'));
191
+ let rec;
192
+ try{rec=JSON.parse(readFileSync(p,'utf8'))}catch{
193
+ throw Object.assign(Error('Untrusted result'),{code:'UNTRUSTED_RESULT'});
194
+ }
195
+ const request=readRequest(id);
196
+ const expectedFile=request.action==='reload'?null:
197
+ request.action==='chat_screenshot'?'result.png':
198
+ request.action==='chat_dom'?'result.html':'result.txt';
199
+ const expectedMime=request.action==='chat_screenshot'?'image/png':
200
+ request.action==='chat_dom'?'text/html':'text/plain';
201
+ const invalid=()=>Object.assign(Error('Untrusted result'),{code:'UNTRUSTED_RESULT'});
202
+ if(!rec||typeof rec!=='object'||Array.isArray(rec)
203
+ ||Object.keys(rec).some(k=>!['id','action','status','code','path',
204
+ 'bytes','mimeType','at','verified'].includes(k))
205
+ ||rec.id!==id||rec.action!==request.action
206
+ ||!['OK','FAILED'].includes(rec.status)
207
+ ||rec.verified!==(request.action!=='reload')
208
+ ||!Number.isSafeInteger(rec.at)||rec.at<request.at||rec.at>request.expiresAt
209
+ ||!Number.isSafeInteger(rec.bytes)||rec.bytes<0
210
+ ||(rec.status==='FAILED'
211
+ ?rec.path!==null||rec.mimeType!==null||rec.bytes!==0
212
+ ||typeof rec.code!=='string'||!/^[A-Z][A-Z0-9_]{1,95}$/.test(rec.code)
213
+ :rec.code!==null||rec.mimeType!==expectedMime
214
+ ||rec.path!==(expectedFile?join(dir,expectedFile):null)
215
+ ||rec.bytes>(request.action==='chat_screenshot'?MAX_PNG:MAX_TEXT)))
216
+ throw invalid();
217
+ if(rec.status==='OK'&&expectedFile){
218
+ try{
219
+ privateRecord(rec.path,'UNTRUSTED_RESULT');
220
+ if(lstatSync(rec.path).size!==rec.bytes)throw invalid();
221
+ }catch{throw invalid()}
222
+ }
223
+ return rec;
190
224
  }
191
225
  export function cleanup(){
192
226
  const root=tempRoot();
@@ -61,7 +61,11 @@ export async function nativeContextControl(command,args){
61
61
  const reply=await ipc({...signed,action:'context-control',mac},6000);
62
62
  if(reply.contract!==hello.contract||reply.requestId!==signed.requestId)
63
63
  throw fail('CONTEXT_CONTROL_REPLY_INVALID');
64
- if(reply.status!=='OK')throw fail(reply.error?.code||'CONTEXT_CONTROL_FAILED');
64
+ if(reply.status!=='OK'){
65
+ const code=reply.error?.code;
66
+ throw fail(typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
67
+ ?code:'CONTEXT_CONTROL_FAILED');
68
+ }
65
69
  return reply.result;
66
70
  }
67
71
 
@@ -14,6 +14,7 @@ export function configureOwnerEvidence(api){
14
14
  const fail=code=>Object.assign(new Error(code),{code});
15
15
  const ensure=(ok,code)=>{if(!ok)throw fail(code)};
16
16
  const sha=raw=>createHash('sha256').update(raw).digest('hex');
17
+ const packageVersion=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
17
18
 
18
19
  function checkedNative(){
19
20
  const session=readSession();
@@ -38,7 +39,10 @@ function checkedExtensionIdle(){
38
39
  encoding:'utf8',timeout:14000,maxBuffer:524288,stdio:['ignore','pipe','pipe']});
39
40
  const rows=out.trim().split('\n').map(s=>JSON.parse(s));
40
41
  const result=rows.findLast(x=>x.event==='RESULT');
41
- ensure(result?.ok===true&&result.value?.verified===true
42
+ ensure(result?.contract==='chat-loop.extension-cli.v1'
43
+ &&result.command==='extension status'
44
+ &&result.providerVersion===packageVersion
45
+ &&result.ok===true&&result.value?.verified===true
42
46
  &&result.value?.truncated===false,'EXTENSION_STATUS_UNVERIFIED');
43
47
  const v=JSON.parse(result.value.content||'{}');
44
48
  ensure(v.status==='OK'&&v.state==='IDLE'
@@ -72,7 +72,9 @@ export function writeSession(input,replaceBlockedSessionId=null,resumeBlockedSes
72
72
  // same-Chat, same-generation, one-shot recovery CAS. No new Chat,
73
73
  // task, project, approval or Handoff may be smuggled into recovery.
74
74
  if(replaceBlockedSessionId || !old || old.phase!=='BLOCKED'
75
- ||resumeBlockedUpdatedAt!==null&&old.updatedAt!==resumeBlockedUpdatedAt
75
+ ||!Number.isSafeInteger(resumeBlockedUpdatedAt)
76
+ ||resumeBlockedUpdatedAt<=0
77
+ ||old.updatedAt!==resumeBlockedUpdatedAt
76
78
  ||old.sessionId!==resumeBlockedSessionId
77
79
  ||next.sessionId!==old.sessionId
78
80
  ||next.projectId!==old.projectId
@@ -94,6 +96,20 @@ export function writeSession(input,replaceBlockedSessionId=null,resumeBlockedSes
94
96
  if(next.projectId!==old.projectId)throw fail('SESSION_PROJECT_CHANGED');
95
97
  if(next.taskId!==old.taskId)throw fail('SESSION_TASK_CHANGED');
96
98
  if(next.generation<old.generation)throw fail('SESSION_STALE_GENERATION');
99
+ // One verified Handoff advances exactly one generation. A skipped
100
+ // generation cannot become a durable Owner identity.
101
+ if(next.generation>old.generation+1)throw fail('SESSION_GENERATION_GAP');
102
+ if(next.generation===old.generation+1
103
+ &&(old.activeChatId===null||next.activeChatId===null
104
+ ||next.activeChatId===old.activeChatId))
105
+ throw fail('SESSION_HANDOFF_IDENTITY_UNVERIFIED');
106
+ // A terminal session may be re-read or fenced, not reassigned to
107
+ // another Chat or generation under the same sessionId.
108
+ if(['DONE','BLOCKED'].includes(old.phase)
109
+ &&(next.generation!==old.generation
110
+ ||next.activeChatId!==old.activeChatId
111
+ ||next.activeChatUrl!==old.activeChatUrl))
112
+ throw fail('SESSION_TERMINAL_IDENTITY_CHANGED');
97
113
  if(old.phase==='DONE'&&next.phase!=='DONE'||old.phase==='BLOCKED'
98
114
  && !['BLOCKED','DONE'].includes(next.phase)
99
115
  &&!(resumeBlockedSessionId===old.sessionId
@@ -111,10 +127,18 @@ export function writeSession(input,replaceBlockedSessionId=null,resumeBlockedSes
111
127
  && ['sessionId','projectId','taskId','phase','generation',
112
128
  'activeChatId','activeChatUrl'].every(key=>old[key]===next[key]))
113
129
  return old;
130
+ // updatedAt is the Native recovery CAS value, not merely display time.
131
+ // Two Worker transitions can occur inside one millisecond. Every actual
132
+ // write must advance that version; an identical projection returned above
133
+ // deliberately keeps the previous value.
134
+ const committed=old&&next.updatedAt<=old.updatedAt
135
+ ?{...next,updatedAt:old.updatedAt+1}:next;
136
+ if(!Number.isSafeInteger(committed.updatedAt))
137
+ throw fail('SESSION_CLOCK_EXHAUSTED');
114
138
  const temp=join(dir,'.active-session-'+randomUUID()+'.tmp');
115
- try{writeFileSync(temp,JSON.stringify(next,null,2)+'\n',{flag:'wx',mode:0o600});
139
+ try{writeFileSync(temp,JSON.stringify(committed,null,2)+'\n',{flag:'wx',mode:0o600});
116
140
  renameSync(temp,file);
117
141
  }catch(e){try{unlinkSync(temp);}catch{}throw e;}
118
- return next;
142
+ return committed;
119
143
  }finally{closeSync(fd);unlinkSync(lock);}
120
144
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.12",
3
+ "version": "0.4.13",
4
4
  "type": "module",
5
5
  "description": "Chat Loop Extension package: nine formal Action pages and its own native CLI bridge",
6
6
  "bin": {
@@ -33,6 +33,6 @@
33
33
  ".": "./index.mjs"
34
34
  },
35
35
  "dependencies": {
36
- "@tomflow/chatloop-trace": "0.4.5"
36
+ "@tomflow/chatloop-trace": "0.4.6"
37
37
  }
38
38
  }