@tomflow/chatloop-tools 0.9.44 → 0.9.46

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.
Files changed (74) hide show
  1. package/README.md +9 -2
  2. package/bin/cli.mjs +12 -5
  3. package/index.mjs +59 -12
  4. package/lib/adapters/mcp-child.mjs +142 -30
  5. package/lib/adapters/tunnel.mjs +22 -11
  6. package/lib/context-control-auth.mjs +0 -5
  7. package/lib/context-gateway.mjs +14 -1
  8. package/lib/control.mjs +27 -8
  9. package/lib/extension-cli-contract.mjs +5 -3
  10. package/lib/extension-proxy.mjs +80 -10
  11. package/lib/gateway.mjs +20 -8
  12. package/lib/release-health-checks.mjs +49 -12
  13. package/lib/release-owner-preflight.mjs +1 -2
  14. package/lib/release-upgrade.mjs +6 -2
  15. package/lib/release.mjs +27 -6
  16. package/lib/supervisor-observability.mjs +2 -2
  17. package/lib/supervisor-runtime.mjs +96 -33
  18. package/lib/trace-gateway.mjs +64 -42
  19. package/lib/tunnel.mjs +15 -5
  20. package/node_modules/@tomflow/chatloop-context/README.md +2 -2
  21. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +1 -1
  22. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +1 -1
  23. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +1 -1
  24. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +2 -7
  25. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +3 -1
  26. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +8 -3
  27. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +13 -7
  28. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +12 -8
  29. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +20 -3
  30. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +8 -4
  31. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +5 -3
  32. package/node_modules/@tomflow/chatloop-context/package.json +3 -3
  33. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +14 -6
  34. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +26 -7
  35. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +6 -3
  36. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +5 -2
  37. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +22 -4
  38. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +19 -4
  39. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +4 -2
  40. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +11 -3
  41. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +2 -1
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +11 -3
  43. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +10 -9
  44. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -1
  45. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +9 -3
  46. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +2 -2
  47. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +8 -10
  48. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +7 -2
  49. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +2 -1
  50. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +7 -1
  51. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +16 -5
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +5 -7
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +12 -3
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +35 -21
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +11 -6
  56. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +11 -3
  57. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +39 -5
  58. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +5 -1
  59. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +5 -1
  60. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +27 -3
  61. package/node_modules/@tomflow/chatloop-extension/package.json +2 -2
  62. package/node_modules/@tomflow/chatloop-trace/README.md +7 -2
  63. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +66 -36
  64. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +17 -4
  65. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +30 -6
  66. package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
  67. package/package.json +9 -9
  68. package/providers/context.mjs +5 -1
  69. package/providers/desktop.mjs +23 -6
  70. package/providers/document.mjs +5 -3
  71. package/providers/extension.mjs +6 -4
  72. package/providers/form.mjs +5 -3
  73. package/providers/runtime.mjs +14 -6
  74. package/providers/trace.mjs +3 -2
@@ -1,7 +1,7 @@
1
1
  // Authoritative single-handle Context SQLite Core. Domain methods compose here.
2
2
  // No Chrome Owner, second writer, or independently committed domain transaction.
3
3
  import {DatabaseSync} from 'node:sqlite';
4
- import {createHash, randomBytes, randomUUID} from 'node:crypto';
4
+ import {createHash, randomUUID} from 'node:crypto';
5
5
  import {mkdirSync,lstatSync,existsSync,chmodSync} from 'node:fs';
6
6
  import {dirname} from 'node:path';
7
7
 
@@ -25,7 +25,6 @@ const canonical=x=>x===null||typeof x!=='object'?JSON.stringify(x):
25
25
  Array.isArray(x)?'['+x.map(canonical).join(',')+']':
26
26
  '{'+Object.keys(x).sort().map(k=>JSON.stringify(k)+':'+canonical(x[k])).join(',')+'}';
27
27
  const digest=x=>createHash('sha256').update(typeof x==='string'?x:canonical(x)).digest('hex');
28
- export const issueRunCredential=()=>randomBytes(32).toString('hex');
29
28
  const runDigest=(epoch,projectId,taskId,runRef,credential)=>digest(['context-write-v1',epoch,projectId,taskId,runRef,credential]);
30
29
  const parse=x=>JSON.parse(x);
31
30
 
@@ -44,13 +43,18 @@ export function openContextProtocol(file,{authorizeInternal=()=>false,authorizeD
44
43
  else mkdirSync(dirname(file),{recursive:true,mode:0o700});
45
44
  const dir=lstatSync(dirname(file));
46
45
  assert(dir.isDirectory()&&!dir.isSymbolicLink()&&!(dir.mode&0o077),'STATE_DIRECTORY_UNTRUSTED');
47
- const existed=existsSync(file);
48
- if(!existed)assert(allowCreate===true&&!readOnly,'STORE_MISSING');
49
- else {
50
- const st=lstatSync(file);
51
- assert(st.isFile()&&!st.isSymbolicLink()&&!(st.mode&0o077)
52
- &&(!process.getuid||st.uid===process.getuid()),'STORE_FILE_UNTRUSTED');
46
+ // existsSync follows dangling symlinks. A dangling Store path is not
47
+ // an absent database, even when the operator explicitly allows creation.
48
+ let fileStat=null;
49
+ try{fileStat=lstatSync(file)}
50
+ catch(error){
51
+ if(error.code!=='ENOENT')throw fail('STORE_FILE_UNTRUSTED');
53
52
  }
53
+ const existed=fileStat!==null;
54
+ if(!existed)assert(allowCreate===true&&!readOnly,'STORE_MISSING');
55
+ else assert(fileStat.isFile()&&!fileStat.isSymbolicLink()
56
+ &&!(fileStat.mode&0o077)
57
+ &&(!process.getuid||fileStat.uid===process.getuid()),'STORE_FILE_UNTRUSTED');
54
58
  const db=new DatabaseSync(file,{timeout:3500,readOnly});
55
59
  // Check the existing schema BEFORE creating any application table or changing WAL.
56
60
  // Never silently adopt an unrelated DB or recreate an empty authority.
@@ -125,7 +125,17 @@ export function createTaskMethods(values) {
125
125
  const r=scope(a);expectedBusiness(r,a.expectedTaskRevision);
126
126
  assert(typeof a.userTurn==='string'&&a.userTurn.length>=8,'ACCEPTANCE_SOURCE_REQUIRED');
127
127
  const current=parse(r.context_json);
128
- assert(current.executionOutcome==='DONE','DELIVERY_NOT_DONE');
128
+ // REOPENED still retains the old DONE history but is not a new
129
+ // deliverable for acceptance until the repair is completed.
130
+ assert(current.executionOutcome==='DONE'&&current.stage==='DELIVERED',
131
+ 'DELIVERY_NOT_DONE');
132
+ // The user acceptance follows a committed terminal fence, not merely
133
+ // the model's DONE or an in-flight Context delivery.
134
+ assert(r.writable_ref===null&&r.pending_attempt===null,
135
+ 'TERMINAL_FENCE_REQUIRED');
136
+ // Record one independent decision per delivery. A rejection must
137
+ // proceed through an explicit user-authorized reopen and new delivery.
138
+ assert(current.acceptance==='AWAITING','ACCEPTANCE_ALREADY_RECORDED');
129
139
  const next={...current,acceptance:a.decision==='ACCEPT'?'ACCEPTED':'REJECTED',
130
140
  acceptanceFeedback:{userTurn:a.userTurn,sourceRole:'user',
131
141
  comment:typeof a.comment==='string'?a.comment.slice(0,2000):'',
@@ -140,9 +150,16 @@ export function createTaskMethods(values) {
140
150
  const r=scope(a);written(r,a);
141
151
  assert(typeof a.deliveryRef==='string'&&a.deliveryRef.length>=8,
142
152
  'DELIVERY_REF_REQUIRED');
143
- assert(unresolvedEffects(parse(r.context_json)).length===0,
153
+ const current=parse(r.context_json);
154
+ // A new requestId must not overwrite an already committed delivery.
155
+ // A user-authorized same-scope REOPENED run may deliver a repair.
156
+ assert(current.executionOutcome!=='DONE'
157
+ ||current.stage==='REOPENED'
158
+ &&current.reopenReason==='REPAIR_SAME_SCOPE',
159
+ 'TASK_ALREADY_DELIVERED');
160
+ assert(unresolvedEffects(current).length===0,
144
161
  'UNKNOWN_EFFECTS_UNRESOLVED');
145
- const next={...parse(r.context_json),stage:'DELIVERED',executionOutcome:'DONE',
162
+ const next={...current,stage:'DELIVERED',executionOutcome:'DONE',
146
163
  deliveryRef:a.deliveryRef,acceptance:'AWAITING',deliveredAt:Date.now()};
147
164
  saveTaskContext(a.projectId,a.taskId,next);
148
165
  return {status:'DELIVERED',taskRevision:r.business_revision+1};
@@ -3,7 +3,7 @@
3
3
  // neither path grants Browser Owner or carries forward R/P approvals.
4
4
  import {randomUUID,createHash} from 'node:crypto';
5
5
  import {DatabaseSync} from 'node:sqlite';
6
- import {existsSync,mkdtempSync,renameSync,rmSync,writeFileSync,
6
+ import {lstatSync,mkdtempSync,renameSync,rmSync,writeFileSync,
7
7
  readFileSync} from 'node:fs';
8
8
  import {join,dirname} from 'node:path';
9
9
  // This module declares ports; index.mjs is the only dependency assembler.
@@ -26,6 +26,10 @@ const scopedTables=['checkpoints','documents','issues','artifacts','receipts',
26
26
  'migrations','project_materials','permits','start_leases','tasks','projects'];
27
27
  const allTables=['meta',...scopedTables];
28
28
  const shaFile=file=>createHash('sha256').update(readFileSync(file)).digest('hex');
29
+ const occupied=file=>{
30
+ try{lstatSync(file);return true}
31
+ catch(error){if(error.code==='ENOENT')return false;throw error}
32
+ };
29
33
  function logicalDigest(db){
30
34
  const digest=createHash('sha256');
31
35
  for(const table of allTables){
@@ -74,7 +78,7 @@ async function extractProjectBranch({
74
78
  'PROJECT_VERSION_CONFLICT');
75
79
  privateFile(sourceDb);privateRoot(targetRoot);
76
80
  const target=join(targetRoot,projectId);
77
- ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
81
+ ensure(!occupied(target),'MIGRATION_TARGET_EXISTS');
78
82
  // Preflight may not initialize/repair/change the old Store in any way.
79
83
  const source=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
80
84
  authorizeData:()=>true,authorizeAdmin:()=>true});
@@ -204,7 +208,7 @@ async function extractProjectBranch({
204
208
  writeFileSync(manifest,JSON.stringify(receipt,null,2)+'\n',{flag:'wx',mode:0o600});
205
209
  ensure(readFileSync(manifest,'utf8').includes(receipt.sourceSnapshotHash),
206
210
  'MIGRATION_RECEIPT_UNVERIFIED');
207
- ensure(!existsSync(target),'MIGRATION_TARGET_EXISTS');
211
+ ensure(!occupied(target),'MIGRATION_TARGET_EXISTS');
208
212
  renameSync(stage,target);
209
213
  published=true;
210
214
  return {...receipt,projectDirectory:target};
@@ -233,7 +237,7 @@ export async function fenceLegacyProjectStore({
233
237
  privateFile(sourceDb);
234
238
  privateRoot(dirname(backupPath));
235
239
  privateRoot(dirname(sealManifestPath));
236
- ensure(!existsSync(backupPath)&&!existsSync(sealManifestPath),
240
+ ensure(!occupied(backupPath)&&!occupied(sealManifestPath),
237
241
  'CUTOVER_EVIDENCE_EXISTS');
238
242
  const reader=openContextProtocol(sourceDb,{readOnly:true,principalId:'local-operator',
239
243
  authorizeData:()=>true,authorizeAdmin:()=>true});
@@ -18,6 +18,7 @@ export function configureProjectStore(capabilities){
18
18
 
19
19
  const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
20
20
  const fail=code=>Object.assign(new Error(code),{code});
21
+ const owned=st=>!process.getuid||st.uid===process.getuid();
21
22
  // existsSync follows symlinks and reports a dangling link as absent. Inspect
22
23
  // the actual directory entry so every untrusted root/project/store fails closed.
23
24
  function entryOrMissing(path){
@@ -32,7 +33,7 @@ export function verifiedStoreFile(file,missingCode=null){
32
33
  if(missingCode)throw fail(missingCode);
33
34
  return false;
34
35
  }
35
- if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077))
36
+ if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)||!owned(st))
36
37
  throw fail('STORE_FILE_UNTRUSTED');
37
38
  return true;
38
39
  }
@@ -52,11 +53,12 @@ export function projectDatabase(projectId){
52
53
  const root=contextRoot();
53
54
  const rootEntry=entryOrMissing(root);
54
55
  if(rootEntry&&(!rootEntry.isDirectory()||rootEntry.isSymbolicLink()
55
- ||(rootEntry.mode&0o077)))throw fail('CONTEXT_ROOT_UNTRUSTED');
56
+ ||(rootEntry.mode&0o077)||!owned(rootEntry)))throw fail('CONTEXT_ROOT_UNTRUSTED');
56
57
  const dir=join(root,projectId);
57
58
  const projectEntry=entryOrMissing(dir);
58
59
  if(projectEntry&&(!projectEntry.isDirectory()||projectEntry.isSymbolicLink()
59
- ||(projectEntry.mode&0o077)))throw fail('PROJECT_DIRECTORY_UNTRUSTED');
60
+ ||(projectEntry.mode&0o077)||!owned(projectEntry)))
61
+ throw fail('PROJECT_DIRECTORY_UNTRUSTED');
60
62
  return join(dir,'context.sqlite');
61
63
  }
62
64
  // Real read-only SQLite discovery: never initializes a missing database or turns WAL on.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-context",
3
- "version": "0.6.12",
3
+ "version": "0.6.13",
4
4
  "type": "module",
5
5
  "description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
6
6
  "publishConfig": {
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "ps-list": "9.0.0",
37
- "@tomflow/chatloop-extension": "0.4.12",
38
- "@tomflow/chatloop-trace": "0.4.5"
37
+ "@tomflow/chatloop-extension": "0.4.13",
38
+ "@tomflow/chatloop-trace": "0.4.6"
39
39
  }
40
40
  }
@@ -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){