@tomflow/chatloop-extension 0.3.83 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -73
- package/actions.generated.mjs +11 -0
- package/bin/cli.mjs +22 -24
- package/bin/native-host.mjs +14 -5
- package/capabilities/chat_dom.mjs +1 -0
- package/capabilities/chat_screenshot.mjs +1 -0
- package/capabilities/chat_text.mjs +1 -0
- package/capabilities/clean.mjs +1 -0
- package/capabilities/continue.mjs +1 -0
- package/capabilities/handoff.mjs +1 -0
- package/capabilities/reload.mjs +1 -0
- package/capabilities/start.mjs +1 -0
- package/capabilities/status.mjs +1 -0
- package/extension/actions/common.js +14 -3
- package/extension/actions/continue.js +1 -1
- package/extension/actions/handoff.js +5 -3
- package/extension/actions/index.js +2 -0
- package/extension/actions/read-mode.js +9 -0
- package/extension/actions/start.js +1 -1
- package/extension/background.js +16 -2188
- package/extension/loop/action-catalog.generated.js +2 -0
- package/extension/loop/api-aspect.generated.js +192 -0
- package/extension/loop/core.js +81 -3
- package/extension/loop/index.js +34 -0
- package/extension/loop/observer-approval.js +227 -0
- package/extension/loop/observer-inspect.js +144 -0
- package/extension/loop/observer-poll.js +171 -0
- package/extension/loop/observer-recovery.js +109 -0
- package/extension/loop/observer.js +27 -630
- package/extension/loop/resources.js +8 -1
- package/extension/manifest.json +6 -2
- package/extension/worker/action-result.js +136 -0
- package/extension/worker/action-take.js +220 -0
- package/extension/worker/admission.js +122 -0
- package/extension/worker/adopt-prepare.js +155 -0
- package/extension/worker/adopt-recovery.js +185 -0
- package/extension/worker/adopt-result.js +120 -0
- package/extension/worker/bootstrap.js +172 -0
- package/extension/worker/manual.js +165 -0
- package/extension/worker/readiness.js +242 -0
- package/extension/worker/router.js +150 -0
- package/extension/worker/scheduler.js +147 -0
- package/extension/worker/turn-failure.js +197 -0
- package/extension/worker/turn-finished.js +200 -0
- package/index.mjs +62 -0
- package/lib/action-routing.mjs +18 -0
- package/lib/api-aspect.mjs +190 -0
- package/lib/bridge.mjs +26 -7
- package/lib/context-binding.mjs +6 -1
- package/lib/context-ipc.mjs +44 -2
- package/lib/owner-evidence.mjs +67 -0
- package/lib/session-file.mjs +20 -8
- package/package.json +13 -3
- package/scripts/build-actions.mjs +133 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// GENERATED by scripts/build-actions.mjs — do not edit.
|
|
2
|
+
globalThis.ChatLoopEyeCatalogV1=Object.freeze({"chat_text":{"page":"text.html","kind":"eye-read","readMode":"text"},"chat_dom":{"page":"dom.html","kind":"eye-read","readMode":"dom"},"chat_screenshot":{"page":"screenshot.html","kind":"eye-screenshot","readMode":null},"reload":{"page":"reload.html","kind":"eye-reload","readMode":null}});
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// Canonical AOP observer, generated into independently installable npm packages and MV3.
|
|
2
|
+
// Soft evidence only: no parameters, results, URLs, secrets or model content.
|
|
3
|
+
const SAFE=/^[a-zA-Z][a-zA-Z0-9_.:-]{0,126}$/;
|
|
4
|
+
const PACKAGE=/^@[a-z0-9][a-z0-9._-]{0,45}\/[a-z0-9][a-z0-9._-]{0,80}$/;
|
|
5
|
+
const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
6
|
+
const safe=(s,fallback='api.unknown')=>typeof s==='string'&&SAFE.test(s)?s:fallback;
|
|
7
|
+
const code=e=>typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
|
|
8
|
+
?e.code:'API_FAILED';
|
|
9
|
+
const uid=()=>{
|
|
10
|
+
try{return globalThis.crypto.randomUUID()}catch{
|
|
11
|
+
const hex='0123456789abcdef',h=n=>Array.from({length:n},
|
|
12
|
+
()=>hex[Math.floor(Math.random()*16)]).join('');
|
|
13
|
+
return h(8)+'-'+h(4)+'-4'+h(3)+'-a'+h(3)+'-'+h(12);
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
const schedule=typeof setImmediate==='function'?setImmediate:fn=>setTimeout(fn,0);
|
|
17
|
+
const clock=()=>typeof performance!=='undefined'&&typeof performance.now==='function'
|
|
18
|
+
?performance.now():Date.now();
|
|
19
|
+
const MAX_PENDING=4096,MAX_BATCH=128;
|
|
20
|
+
const CONTEXT_KEY=Symbol.for('chat-loop.observation.async-context.v1');
|
|
21
|
+
// Process-local correlation only, never an authorization or plugin registry.
|
|
22
|
+
const contextStore=()=>{
|
|
23
|
+
if(typeof process==='undefined'||typeof process.getBuiltinModule!=='function')return null;
|
|
24
|
+
try{
|
|
25
|
+
if(!process[CONTEXT_KEY]){
|
|
26
|
+
const {AsyncLocalStorage}=process.getBuiltinModule('node:async_hooks');
|
|
27
|
+
Object.defineProperty(process,CONTEXT_KEY,{
|
|
28
|
+
value:new AsyncLocalStorage(),enumerable:false,configurable:false
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return process[CONTEXT_KEY];
|
|
32
|
+
}catch{return null}
|
|
33
|
+
};
|
|
34
|
+
const validParent=v=>v&&UUID.test(v.traceId||'')&&UUID.test(v.spanId||'');
|
|
35
|
+
function currentApiTrace(){
|
|
36
|
+
try{
|
|
37
|
+
const local=contextStore()?.getStore();
|
|
38
|
+
if(validParent(local))return {traceId:local.traceId,spanId:local.spanId};
|
|
39
|
+
// Child-process context is sanitized correlation metadata, not trust.
|
|
40
|
+
const value=typeof process!=='undefined'?process.env?.CHAT_LOOP_API_PARENT:null;
|
|
41
|
+
if(typeof value!=='string'||value.length>180)return null;
|
|
42
|
+
const parsed=JSON.parse(value);
|
|
43
|
+
return validParent(parsed)?{traceId:parsed.traceId,spanId:parsed.spanId}:null;
|
|
44
|
+
}catch{return null}
|
|
45
|
+
}
|
|
46
|
+
function withApiTraceParent(parent,fn){
|
|
47
|
+
if(typeof fn!=='function')throw TypeError('API_TRACE_CALLBACK_REQUIRED');
|
|
48
|
+
if(!validParent(parent))throw TypeError('API_TRACE_PARENT_INVALID');
|
|
49
|
+
const storage=contextStore();
|
|
50
|
+
return storage?storage.run({traceId:parent.traceId,spanId:parent.spanId},fn):fn();
|
|
51
|
+
}
|
|
52
|
+
function createApiAspect(packageName,{sink}={}){
|
|
53
|
+
const packageId=typeof packageName==='string'&&PACKAGE.test(packageName)
|
|
54
|
+
?packageName:'unknown';
|
|
55
|
+
const queue=[],listeners=new Set(),
|
|
56
|
+
stats={emitted:0,delivered:0,dropped:0,sinkFailures:0};
|
|
57
|
+
let scheduled=false;
|
|
58
|
+
const output=typeof sink==='function'?sink:record=>{
|
|
59
|
+
if(listeners.size){
|
|
60
|
+
for(const listener of [...listeners]){
|
|
61
|
+
try{
|
|
62
|
+
const result=listener(record);
|
|
63
|
+
if(result&&typeof result.then==='function')
|
|
64
|
+
Promise.resolve(result).catch(()=>{stats.sinkFailures++});
|
|
65
|
+
}catch{stats.sinkFailures++}
|
|
66
|
+
}
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if(typeof process==='undefined'||!process.stderr?.write||
|
|
70
|
+
process.env.CHAT_LOOP_API_LOG_STDERR==='0')return;
|
|
71
|
+
process.stderr.write('CHAT_LOOP_API_LOG '+JSON.stringify(record)+'\n');
|
|
72
|
+
};
|
|
73
|
+
const flush=()=>{
|
|
74
|
+
scheduled=false;
|
|
75
|
+
for(let i=0;i<MAX_BATCH&&queue.length;i++){
|
|
76
|
+
const item=queue.shift();
|
|
77
|
+
try{
|
|
78
|
+
const result=output(item);
|
|
79
|
+
stats.delivered++;
|
|
80
|
+
if(result&&typeof result.then==='function')
|
|
81
|
+
Promise.resolve(result).catch(()=>{stats.sinkFailures++});
|
|
82
|
+
}catch{stats.sinkFailures++}
|
|
83
|
+
}
|
|
84
|
+
if(queue.length){scheduled=true;schedule(flush)}
|
|
85
|
+
};
|
|
86
|
+
const emit=event=>{
|
|
87
|
+
try{
|
|
88
|
+
if(queue.length>=MAX_PENDING){stats.dropped++;return}
|
|
89
|
+
queue.push(Object.freeze(event));stats.emitted++;
|
|
90
|
+
if(!scheduled){scheduled=true;schedule(flush)}
|
|
91
|
+
}catch{stats.dropped++}
|
|
92
|
+
};
|
|
93
|
+
function observe(name,fn,surface='sdk',options={}){
|
|
94
|
+
if(typeof fn!=='function')throw TypeError('API_ASPECT_TARGET_REQUIRED');
|
|
95
|
+
const api=safe(name),layer=safe(surface,'sdk');
|
|
96
|
+
return new Proxy(fn,{
|
|
97
|
+
get(target,key,receiver){
|
|
98
|
+
if(key===Symbol.for('chat-loop.api-observed.v1'))return true;
|
|
99
|
+
return Reflect.get(target,key,receiver);
|
|
100
|
+
},
|
|
101
|
+
apply(target,thisArg,args){
|
|
102
|
+
let started,base;
|
|
103
|
+
try{
|
|
104
|
+
// MCP requests are fresh user operations, not children of a
|
|
105
|
+
// long-lived CLI/server bootstrap event listener registration.
|
|
106
|
+
// Browser callbacks lack Node AsyncLocalStorage; a narrowly scoped
|
|
107
|
+
// explicit parent links the async reply to its actual dispatch span.
|
|
108
|
+
const explicit=validParent(options?.parent)?options.parent:null;
|
|
109
|
+
const callId=uid(),parent=explicit||(layer==='mcp'?null:currentApiTrace());
|
|
110
|
+
started=clock();
|
|
111
|
+
base={contract:'chat-loop.api-call.v1',package:packageId,
|
|
112
|
+
api,surface:layer,callId,
|
|
113
|
+
traceId:parent?.traceId||callId,spanId:callId,
|
|
114
|
+
parentSpanId:parent?.spanId||null};
|
|
115
|
+
}catch{/* Never fail a target due to tracing. */}
|
|
116
|
+
const mark=(phase,error)=>{
|
|
117
|
+
if(!base)return;
|
|
118
|
+
try{
|
|
119
|
+
emit({...base,phase,time:new Date().toISOString(),
|
|
120
|
+
durationMs:phase==='BEGIN'?null:Math.max(0,Math.round(clock()-started)),
|
|
121
|
+
errorCode:phase==='FAILED'?code(error):null});
|
|
122
|
+
}catch{/* Non-authoritative telemetry. */}
|
|
123
|
+
};
|
|
124
|
+
mark('BEGIN');
|
|
125
|
+
// Only sanitized correlation IDs may cross from the AOP boundary into
|
|
126
|
+
// the hosting callback. A faulty observer must never affect the call.
|
|
127
|
+
if(base&&typeof options?.onBegin==='function'){
|
|
128
|
+
try{options.onBegin(Object.freeze({traceId:base.traceId,spanId:base.spanId}));}
|
|
129
|
+
catch{stats.sinkFailures++}
|
|
130
|
+
}
|
|
131
|
+
const execute=()=>Reflect.apply(target,thisArg,args);
|
|
132
|
+
let result;
|
|
133
|
+
try{
|
|
134
|
+
const storage=base?contextStore():null;
|
|
135
|
+
result=storage?storage.run({traceId:base.traceId,spanId:base.spanId},execute)
|
|
136
|
+
:execute();
|
|
137
|
+
}catch(e){mark('FAILED',e);throw e}
|
|
138
|
+
const failed=value=>{
|
|
139
|
+
try{return (layer==='mcp'&&value?.isError===true)
|
|
140
|
+
||(layer==='browser'&&api.startsWith('browser.dispatch.')&&value===false)}
|
|
141
|
+
catch{stats.sinkFailures++;return false}
|
|
142
|
+
};
|
|
143
|
+
const failureCode=()=>({code:layer==='browser'
|
|
144
|
+
?'BROWSER_MESSAGE_UNHANDLED':'MCP_TOOL_ERROR'});
|
|
145
|
+
// Do not assimilate arbitrary user thenables for telemetry: invoking
|
|
146
|
+
// their then() could cause a second business side effect. Observe native
|
|
147
|
+
// Promises only, otherwise record the synchronous return boundary.
|
|
148
|
+
let nativePromise=false;
|
|
149
|
+
try{nativePromise=result instanceof Promise}catch{stats.sinkFailures++}
|
|
150
|
+
if(nativePromise){
|
|
151
|
+
// Preserve the exact native Promise object and rejection semantics.
|
|
152
|
+
try{Promise.resolve(result).then(
|
|
153
|
+
value=>{
|
|
154
|
+
const isError=failed(value);
|
|
155
|
+
mark(isError?'FAILED':'OK',
|
|
156
|
+
isError?failureCode():undefined);
|
|
157
|
+
},
|
|
158
|
+
error=>mark('FAILED',error)
|
|
159
|
+
).catch(()=>{stats.sinkFailures++});}
|
|
160
|
+
catch{stats.sinkFailures++}
|
|
161
|
+
return result;
|
|
162
|
+
}
|
|
163
|
+
const isError=failed(result);
|
|
164
|
+
mark(isError?'FAILED':'OK',
|
|
165
|
+
isError?failureCode():undefined);
|
|
166
|
+
return result;
|
|
167
|
+
}});
|
|
168
|
+
}
|
|
169
|
+
function methods(instance,prefix,surface='sdk'){
|
|
170
|
+
if(!instance||typeof instance!=='object')return instance;
|
|
171
|
+
const facade={...instance},cache=new Map();
|
|
172
|
+
return new Proxy(facade,{
|
|
173
|
+
get(object,key,receiver){
|
|
174
|
+
const v=Reflect.get(object,key,receiver);
|
|
175
|
+
if(typeof v!=='function'||typeof key!=='string')return v;
|
|
176
|
+
if(!cache.has(key))cache.set(key,observe(prefix+'.'+key,v,surface));
|
|
177
|
+
return cache.get(key);
|
|
178
|
+
},
|
|
179
|
+
set(){return false},defineProperty(){return false},deleteProperty(){return false}
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
const subscribe=observe('subscribeApiLog',listener=>{
|
|
183
|
+
if(typeof listener!=='function')throw TypeError('API_LOG_LISTENER_REQUIRED');
|
|
184
|
+
listeners.add(listener);
|
|
185
|
+
return ()=>listeners.delete(listener);
|
|
186
|
+
},'internal');
|
|
187
|
+
return Object.freeze({observe,methods,subscribe,
|
|
188
|
+
health:()=>Object.freeze({...stats,pending:queue.length}),
|
|
189
|
+
current:currentApiTrace,withParent:withApiTraceParent});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
globalThis.ChatLoopApiAspectV1=Object.freeze({createApiAspect});
|
package/extension/loop/core.js
CHANGED
|
@@ -23,7 +23,85 @@
|
|
|
23
23
|
if (standalone.length !== 1) return "UNKNOWN";
|
|
24
24
|
return match[1];
|
|
25
25
|
}
|
|
26
|
-
// Worker
|
|
27
|
-
//
|
|
28
|
-
|
|
26
|
+
// The Worker owns all Chrome I/O and state transitions. Only deterministic
|
|
27
|
+
// identity, deadline and receipt policy lives here; no second state store.
|
|
28
|
+
const RUN_BUDGET_MS=4*60*60*1000;
|
|
29
|
+
const MODEL_RECEIPT_TTL_MS=24*60*60*1000;
|
|
30
|
+
const pathOf=url=>{
|
|
31
|
+
try{
|
|
32
|
+
const u=new URL(url),path=u.pathname.replace(/\/$/,'');
|
|
33
|
+
return u.origin==='https://chatgpt.com'
|
|
34
|
+
&&/^\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(path)
|
|
35
|
+
?path:'';
|
|
36
|
+
}catch{return ''}
|
|
37
|
+
};
|
|
38
|
+
const chatIdOf=url=>pathOf(url)?.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase()||null;
|
|
39
|
+
// Corrupt persisted values cannot extend an Owner past the 4-hour budget.
|
|
40
|
+
const windowMsOf=run=>Number.isSafeInteger(run?.windowMs)&&run.windowMs>0
|
|
41
|
+
?Math.min(run.windowMs,RUN_BUDGET_MS):RUN_BUDGET_MS;
|
|
42
|
+
const deadlineOf=run=>Number.isSafeInteger(run?.startedAt)&&run.startedAt>0
|
|
43
|
+
?run.startedAt+windowMsOf(run):null;
|
|
44
|
+
const clockActive=run=>run&&['RESERVED','PENDING','WAITING_REPLY'].includes(run.phase);
|
|
45
|
+
const terminalFenceVerified=run=>!run?.contextManaged||!run?.taskId
|
|
46
|
+
||run.contextTerminalFence==='CONFIRMED';
|
|
47
|
+
// Keep only bounded metadata. A future timestamp is not valid evidence.
|
|
48
|
+
const receiptHistory=run=>{
|
|
49
|
+
if(!Array.isArray(run?.modelReceipts))return [];
|
|
50
|
+
const now=Date.now();
|
|
51
|
+
return run.modelReceipts.filter(x=>x&&typeof x.id==='string'
|
|
52
|
+
&&Number.isSafeInteger(x.updatedAt)&&x.updatedAt<=now
|
|
53
|
+
&&now-x.updatedAt<MODEL_RECEIPT_TTL_MS).slice(-16);
|
|
54
|
+
};
|
|
55
|
+
const updateModelReceipt=(run,id,change)=>{
|
|
56
|
+
if(!id)return run;
|
|
57
|
+
const records=receiptHistory(run);
|
|
58
|
+
const index=records.findIndex(x=>x.id===id);
|
|
59
|
+
const existing=index>=0?records.splice(index,1)[0]:{id};
|
|
60
|
+
return {...run,modelReceipts:[...records,
|
|
61
|
+
{...existing,...change,id,updatedAt:Date.now()}].slice(-16)};
|
|
62
|
+
};
|
|
63
|
+
const settleModelIntent=(run,status,reason)=>{
|
|
64
|
+
const pending=run?.modelIntent;
|
|
65
|
+
const finished=pending
|
|
66
|
+
?updateModelReceipt(run,pending.id,{status,
|
|
67
|
+
reason:reason||run.reason||null,
|
|
68
|
+
actualAction:run.action||pending.action,
|
|
69
|
+
checkpointForwarded:false}):run;
|
|
70
|
+
const next={...finished};
|
|
71
|
+
delete next.modelIntent;
|
|
72
|
+
delete next.modelTurnToken;
|
|
73
|
+
return next;
|
|
74
|
+
};
|
|
75
|
+
// Observer supplies raw R/P proof. The Worker only accepts a canonical
|
|
76
|
+
// read-only evidence contract; it does not parse business approval text.
|
|
77
|
+
// This does NOT replace Context's own approval/Run authorizations.
|
|
78
|
+
const normalizeAdoptionEvidence=(proof,expected={})=>{
|
|
79
|
+
if(proof?.contract!=='chat-loop.turn-observer.v1'
|
|
80
|
+
||proof.status!=='VERIFIED'
|
|
81
|
+
||typeof proof.page!=='string'
|
|
82
|
+
||pathOf('https://chatgpt.com'+proof.page)!==proof.page
|
|
83
|
+
||!/^user:[^\\s]{8,}$/.test(proof.userKey||'')
|
|
84
|
+
||!/^R[1-9][0-9]*$/.test(proof.rVersion||'')
|
|
85
|
+
||!/^P[1-9][0-9]*$/.test(proof.pVersion||''))
|
|
86
|
+
return null;
|
|
87
|
+
const evidence={
|
|
88
|
+
page:proof.page,userKey:proof.userKey,
|
|
89
|
+
priorAssistantKey:proof.priorAssistantKey||null,
|
|
90
|
+
rVersion:proof.rVersion,pVersion:proof.pVersion,
|
|
91
|
+
postApprovalAssistantKey:proof.postApprovalAssistantKey||null
|
|
92
|
+
};
|
|
93
|
+
for(const field of Object.keys(expected)){
|
|
94
|
+
if(evidence[field]!==expected[field])return null;
|
|
95
|
+
}
|
|
96
|
+
return evidence;
|
|
97
|
+
};
|
|
98
|
+
const sameAdoptionEvidence=(a,b)=>Boolean(a&&b
|
|
99
|
+
&&['page','userKey','priorAssistantKey','rVersion','pVersion',
|
|
100
|
+
'postApprovalAssistantKey'].every(field=>a[field]===b[field]));
|
|
101
|
+
// Preserve the original public Core contract used by Observer and Worker.
|
|
102
|
+
globalThis.ChatLoopCoreV1=Object.freeze({parseStatus});
|
|
103
|
+
globalThis.ChatLoopPolicyV1=Object.freeze({pathOf,chatIdOf,
|
|
104
|
+
windowMsOf,deadlineOf,clockActive,terminalFenceVerified,
|
|
105
|
+
MODEL_RECEIPT_TTL_MS,receiptHistory,updateModelReceipt,settleModelIntent,
|
|
106
|
+
normalizeAdoptionEvidence,sameAdoptionEvidence});
|
|
29
107
|
})();
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Browser Worker API root; npm index.mjs is for Node only.
|
|
2
|
+
importScripts('loop/core.js','loop/resources.js');
|
|
3
|
+
importScripts('loop/action-catalog.generated.js');
|
|
4
|
+
importScripts('loop/api-aspect.generated.js');
|
|
5
|
+
if(typeof globalThis.ChatLoopCoreV1?.parseStatus!=='function'
|
|
6
|
+
||!globalThis.ChatLoopPolicyV1||!globalThis.ChatLoopResourcesV1)
|
|
7
|
+
throw Error('CHAT_LOOP_WORKER_API_UNAVAILABLE');
|
|
8
|
+
const apiAudit=globalThis.ChatLoopApiAspectV1?.createApiAspect(
|
|
9
|
+
'@tomflow/chatloop-extension',{sink:record=>{
|
|
10
|
+
// An independent Native telemetry request, never in the Action/Owner path.
|
|
11
|
+
// Only a sanitized event is transmitted; no raw page, prompt or receipt.
|
|
12
|
+
try{
|
|
13
|
+
const native=globalThis.chrome?.runtime?.sendNativeMessage;
|
|
14
|
+
if(typeof native!=='function')return;
|
|
15
|
+
const entry={callId:record.callId,
|
|
16
|
+
traceId:record.traceId,spanId:record.spanId,
|
|
17
|
+
...(record.parentSpanId?{parentSpanId:record.parentSpanId}:{}),
|
|
18
|
+
apiName:'extension.'+record.api,phase:record.phase,
|
|
19
|
+
...(record.durationMs!==null?{durationMs:record.durationMs}:{}),
|
|
20
|
+
...(record.errorCode?{errorCode:record.errorCode}:{})};
|
|
21
|
+
const pending=native('com.tomflow.chatloop.extension',{
|
|
22
|
+
op:'api-observation',record:entry});
|
|
23
|
+
if(pending&&typeof pending.then==='function')
|
|
24
|
+
Promise.resolve(pending).catch(()=>{});
|
|
25
|
+
}catch{/* Telemetry failure may never change a Browser action. */}
|
|
26
|
+
}});
|
|
27
|
+
if(!apiAudit)throw Error('CHAT_LOOP_WORKER_API_OBSERVER_UNAVAILABLE');
|
|
28
|
+
globalThis.ChatLoopWorkerApiV1=Object.freeze({
|
|
29
|
+
audit:apiAudit,
|
|
30
|
+
parseStatus:globalThis.ChatLoopCoreV1.parseStatus,
|
|
31
|
+
policy:globalThis.ChatLoopPolicyV1,
|
|
32
|
+
resources:globalThis.ChatLoopResourcesV1,
|
|
33
|
+
eyeCatalog:globalThis.ChatLoopEyeCatalogV1
|
|
34
|
+
});
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// Read-only Observer helper: no composer writes, Chrome Owner or sends.
|
|
2
|
+
(() => {
|
|
3
|
+
globalThis.ChatLoopObserverApprovalV1=({CONTRACT,inspect,
|
|
4
|
+
activeEvidenceConversation,messageId})=>
|
|
5
|
+
(message,reply)=>{
|
|
6
|
+
if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
|
|
7
|
+
// Read-only, fail-closed two-stage approval proof for same-Chat adoption.
|
|
8
|
+
// An explicit model assertion or a copied task Context is never evidence.
|
|
9
|
+
const view=activeEvidenceConversation();
|
|
10
|
+
const fail = reason => reply({contract: CONTRACT, status:"UNVERIFIED",reason});
|
|
11
|
+
if (!view) {
|
|
12
|
+
fail("APPROVAL_CHAT_UNVERIFIED");return false;
|
|
13
|
+
}
|
|
14
|
+
const {path,nodes,role}=view;
|
|
15
|
+
const rows=nodes.map(el=>({el,role:role(el)}))
|
|
16
|
+
.filter(x=>["user","assistant"].includes(x.role));
|
|
17
|
+
const textOf=x=>(x.el.querySelector?.(".markdown")?.innerText
|
|
18
|
+
||x.el.innerText||x.el.textContent||"").trim();
|
|
19
|
+
const confirms=(value,type)=>{
|
|
20
|
+
const line=value.replace(/\s+/g," ").trim();
|
|
21
|
+
if(!line||line.length>500)return false;
|
|
22
|
+
// Native R/P review controls send two explicit, task-scoped fields:
|
|
23
|
+
// "TASK|R2-ISSUE:<uuid>|我确认 R2 v2。..." (and likewise P2).
|
|
24
|
+
// Accept only a matching kind+version from a genuine user message,
|
|
25
|
+
// never arbitrary prose containing an approval quote or TEST_ONLY.
|
|
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);
|
|
27
|
+
if(native){
|
|
28
|
+
const declared=native[2].toUpperCase(),approved=native[4].toUpperCase();
|
|
29
|
+
if(declared[0]!==type||declared!==approved
|
|
30
|
+
||Number(declared.slice(1))!==Number(native[5]))return false;
|
|
31
|
+
const note=native[6];
|
|
32
|
+
if(/TEST_ONLY|NOT_APPROVED|只是测试|仅供测试|仅为引用|复制示例|不作为.{0,15}(?:审批|批准)|此确认无效/i.test(note))return false;
|
|
33
|
+
if(type==="R"&&/(?:撤销|拒绝|不批准|不确认|不同意).{0,12}(?:需求|R[1-9][0-9]*)/i.test(note)
|
|
34
|
+
||type==="P"&&/(?:撤销|拒绝|不批准|不确认|不同意).{0,12}(?:方案|计划|P[1-9][0-9]*)/i.test(note)
|
|
35
|
+
||type==="P"&&/(?:不授权|未授权|禁止|不要|不能).{0,15}(?:Start|执行|实施|开始|启动)/i.test(note))
|
|
36
|
+
return false;
|
|
37
|
+
return true;
|
|
38
|
+
}
|
|
39
|
+
const target=type==="R"
|
|
40
|
+
? "(?:这份|当前|本版|上述)?(?:需求(?:R[1-9][0-9]*)?|R[1-9][0-9]*)"
|
|
41
|
+
: "(?:这份|当前|本版|上述)?(?:方案(?:与|及|和)?计划|实施计划|方案|计划|P[1-9][0-9]*)(?:P[1-9][0-9]*)?";
|
|
42
|
+
const affirmative=new RegExp("^(?:我)?(?:已经|已)?(?:确认|同意|批准)"+target+"[。.!!]?$","i");
|
|
43
|
+
// Keep the original standalone approval. Some real native R/P forms
|
|
44
|
+
// submit a scoped request ID followed by a direct affirmative sentence
|
|
45
|
+
// and bounded next-stage context in ONE genuine user message.
|
|
46
|
+
if(line.length<=100&&affirmative.test(line.replace(/\s+/g,"")))return true;
|
|
47
|
+
const scoped=line.match(/^([A-Z][A-Z0-9._:-]{7,120})[||]\s*([^。.!!]+[。.!!])\s*(.{1,320})$/i);
|
|
48
|
+
if(!scoped||!affirmative.test(scoped[2].replace(/\s+/g,"")))return false;
|
|
49
|
+
const note=scoped[3];
|
|
50
|
+
// A form's scope note cannot revoke approval, request the model to
|
|
51
|
+
// merely quote it, or explicitly withhold the approved plan's start.
|
|
52
|
+
if(/(?:TEST_ONLY|NOT_APPROVED|只是测试文字|只是引用|仅为引用|复制示例|不授权|未授权|并非授权|不代表.{0,15}(?:授权|确认|批准)|不作为.{0,10}(?:审批|批准|授权)|(?:仅|只是)(?:用|供|用于).{0,5}(?:测试|演示|验证))/i.test(note)
|
|
53
|
+
||/(?:撤销|取消|拒绝|不通过|不同意|不批准)(?:当前|本次|这份)?(?:需求|方案|计划|R[1-9][0-9]*|P[1-9][0-9]*)/i.test(note)
|
|
54
|
+
||type==="P"&&/(?:暂不|先不|不要|不能|不允许|禁止).{0,15}(?:执行|Start|实施|开始|启动|做)/i.test(note)
|
|
55
|
+
||/(?:但|不过|只是).{0,12}(?:先不要|先不做|不做|不要做)/.test(note))return false;
|
|
56
|
+
return true;
|
|
57
|
+
};
|
|
58
|
+
// Prefer an explicit current-version declaration. Historical mentions
|
|
59
|
+
// must not choose a version; ambiguous prose is not approval evidence.
|
|
60
|
+
const versionOf=(value,type)=>{
|
|
61
|
+
// Real formal reviews may start with a status recap mentioning an
|
|
62
|
+
// older P2 before the issued heading "P3 v3|正式修订方案".
|
|
63
|
+
// A unique, version-consistent line title outranks historical prose.
|
|
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
|
+
.filter(x=>Number(x[1].slice(1))===Number(x[2]))
|
|
66
|
+
.map(x=>x[1].toUpperCase());
|
|
67
|
+
const issuedVersions=[...new Set(issued)];
|
|
68
|
+
if(issuedVersions.length===1)return issuedVersions[0];
|
|
69
|
+
if(issuedVersions.length>1)return null;
|
|
70
|
+
const declared=[...value.matchAll(new RegExp("(?:^|\\n)\\s*(?:#{1,6}\\s*)?(?:方案版本|需求版本|当前版本|版本)?[:: ]*("+type+"[1-9][0-9]*)\\b", "gi"))].map(x=>x[1].toUpperCase());
|
|
71
|
+
const current=[...value.matchAll(new RegExp("(?:本次|当前|本版)[:: ]*("+type+"[1-9][0-9]*)\\b", "gi"))].map(x=>x[1].toUpperCase());
|
|
72
|
+
const versions=[...new Set(current.length?current:declared.length?declared:(value.match(new RegExp("\\b"+type+"[1-9][0-9]*\\b","gi"))||[]).map(x=>x.toUpperCase()))];
|
|
73
|
+
return versions.length===1?versions[0]:null;
|
|
74
|
+
};
|
|
75
|
+
const lastUser=rows.findLastIndex(x=>x.role==="user");
|
|
76
|
+
if(lastUser<3 || rows[lastUser-1].role!=="assistant") {
|
|
77
|
+
fail("APPROVAL_SEQUENCE_UNVERIFIED");return false;
|
|
78
|
+
}
|
|
79
|
+
const pUser=rows[lastUser],pAssistant=rows[lastUser-1];
|
|
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
|
|
82
|
+
// the assistant said the current plan was not presented for approval.
|
|
83
|
+
if(/(?:当前阶段[::]\s*PLAN_DRAFT|(?:维持|保持|仍为|停留在)\s*PLAN_DRAFT|方案(?:草稿)?.{0,20}(?:尚未|未曾|没有)正式(?:发布|提交)|(?:暂不|不(?:予|会|再)?)展示.{0,12}提交方案评审)/i.test(textOf(pAssistant))){
|
|
84
|
+
fail("APPROVAL_PLAN_NOT_ISSUED");return false;
|
|
85
|
+
}
|
|
86
|
+
if(!confirms(textOf(pUser),"P")
|
|
87
|
+
|| !/(?:方案|计划)/.test(textOf(pAssistant))
|
|
88
|
+
|| !/\bP[1-9][0-9]*\b/i.test(textOf(pAssistant))) {
|
|
89
|
+
fail("APPROVAL_PLAN_MISSING");return false;
|
|
90
|
+
}
|
|
91
|
+
const pVersion=versionOf(textOf(pAssistant),"P");
|
|
92
|
+
const pUserVersion=textOf(pUser).match(/\bP[1-9][0-9]*\b/i)?.[0].toUpperCase();
|
|
93
|
+
if(pUserVersion && pVersion!==pUserVersion){
|
|
94
|
+
fail("APPROVAL_PLAN_VERSION_MISMATCH");return false;
|
|
95
|
+
}
|
|
96
|
+
const rIndex=rows.slice(0,lastUser-1).findLastIndex(x=>x.role==="user"
|
|
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.
|
|
101
|
+
// This fallback is ONLY for native issue-scoped approvals. The Native
|
|
102
|
+
// Context Start lease independently verifies the effective R approval.
|
|
103
|
+
const rUser=rIndex>=0?rows[rIndex]:null;
|
|
104
|
+
const nativeR=rUser&&textOf(rUser).match(/^[A-Z][A-Z0-9._:-]{7,120}[||]\s*(R[1-9][0-9]*)-ISSUE:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}[||]\s*我确认\s+(R[1-9][0-9]*)\s+v([1-9][0-9]*)[。.!!]/i);
|
|
105
|
+
const nativeRVersion=nativeR
|
|
106
|
+
&&nativeR[1].toUpperCase()===nativeR[2].toUpperCase()
|
|
107
|
+
&&Number(nativeR[1].slice(1))===Number(nativeR[3])
|
|
108
|
+
?nativeR[1].toUpperCase():null;
|
|
109
|
+
const rAssistant=rIndex>0?rows[rIndex-1]:null;
|
|
110
|
+
if(rIndex<0 || rIndex===0&&!nativeRVersion
|
|
111
|
+
||rIndex>0&&rAssistant?.role!=="assistant"){
|
|
112
|
+
fail("APPROVAL_REQUIREMENTS_MISSING");return false;
|
|
113
|
+
}
|
|
114
|
+
if(message.expectedTaskId!==undefined){
|
|
115
|
+
// A no-URL idle adoption is only eligible for its exact Managed
|
|
116
|
+
// Task's TWO native issued approval messages in the same DOM Chat.
|
|
117
|
+
// No standalone historical affirmations or copied Task summaries.
|
|
118
|
+
const task=message.expectedTaskId;
|
|
119
|
+
const nativeIssue=(row,type)=>typeof task==="string"
|
|
120
|
+
&&/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(task)
|
|
121
|
+
&&textOf(row).startsWith(task+"|")
|
|
122
|
+
&&new RegExp("^"+type+"[1-9][0-9]*-ISSUE:"
|
|
123
|
+
+"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}[||]\\s*我确认\\s+"
|
|
124
|
+
+type+"[1-9][0-9]*\\s+v[1-9][0-9]*","i")
|
|
125
|
+
.test(textOf(row).slice(task.length+1));
|
|
126
|
+
if(!nativeRVersion||!nativeIssue(rUser,"R")
|
|
127
|
+
||!nativeIssue(pUser,"P")){
|
|
128
|
+
fail("APPROVAL_TASK_SCOPE_MISMATCH");return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// Only document-level TEST_ONLY markers deny production adoption:
|
|
132
|
+
// normal P plans can legitimately mention test-only scenarios.
|
|
133
|
+
const testOnlyReview=x=>
|
|
134
|
+
/(?:^|\n)\s*(?:#{1,6}\s*|>\s*)?(?:\*\*)?TEST_ONLY(?:\*\*)?(?:\s*$|\s*[/||:]\s*NOT_APPROVED)/mi
|
|
135
|
+
.test(textOf(x));
|
|
136
|
+
if(rAssistant&&testOnlyReview(rAssistant)||testOnlyReview(pAssistant)){
|
|
137
|
+
fail("APPROVAL_TEST_ONLY");return false;
|
|
138
|
+
}
|
|
139
|
+
if(rAssistant&&(!/(?:需求|范围|验收)/.test(textOf(rAssistant))
|
|
140
|
+
|| !/\bR[1-9][0-9]*\b/i.test(textOf(rAssistant)))) {
|
|
141
|
+
fail("APPROVAL_REQUIREMENTS_MISSING");return false;
|
|
142
|
+
}
|
|
143
|
+
const rVersion=rAssistant?versionOf(textOf(rAssistant),"R"):nativeRVersion;
|
|
144
|
+
const intervening=rows.slice(rIndex+1,lastUser-1);
|
|
145
|
+
const invalidated=intervening.some(x=>{
|
|
146
|
+
const text=textOf(x);
|
|
147
|
+
if(x.role==="assistant"){
|
|
148
|
+
const next=versionOf(text,"R");
|
|
149
|
+
return /需求|范围|验收/.test(text)&&next&&next!==rVersion;
|
|
150
|
+
}
|
|
151
|
+
// "修订 P3、保留 R2" is a plan update, NOT an R2 revocation.
|
|
152
|
+
// Only an explicit requirement-targeted change invalidates this R.
|
|
153
|
+
return /(?:撤销|取消|拒绝|不同意|不批准|修改|修订|变更)\s*(?:(?:当前|本次|这份|上述)\s*)?(?:需求|R[1-9][0-9]*)/i.test(text)
|
|
154
|
+
|| /\bR[1-9][0-9]*\b\s*(?:需求)?\s*(?:需要|应当|应该)?\s*(?:撤销|取消|拒绝|修改|修订|变更)/i.test(text);
|
|
155
|
+
});
|
|
156
|
+
if(!pVersion||!rVersion||invalidated){
|
|
157
|
+
fail("APPROVAL_REVISED_OR_REVOKED");return false;
|
|
158
|
+
}
|
|
159
|
+
const rUserVersion=textOf(rUser).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
|
|
160
|
+
const referencedR=textOf(pAssistant).match(/\bR[1-9][0-9]*\b/i)?.[0].toUpperCase();
|
|
161
|
+
if(!referencedR || referencedR!==rVersion){
|
|
162
|
+
fail("APPROVAL_PLAN_REQUIREMENT_MISMATCH");return false;
|
|
163
|
+
}
|
|
164
|
+
if(rUserVersion && rVersion!==rUserVersion){
|
|
165
|
+
fail("APPROVAL_REQUIREMENTS_VERSION_MISMATCH");return false;
|
|
166
|
+
}
|
|
167
|
+
// 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
|
|
170
|
+
// message is still the old standalone confirmation.
|
|
171
|
+
const revisedAfterApproval=rows.slice(lastUser+1).some(x=>{
|
|
172
|
+
if(x.role!=="assistant")return false;
|
|
173
|
+
const text=textOf(x),nextR=versionOf(text,"R"),
|
|
174
|
+
nextP=versionOf(text,"P");
|
|
175
|
+
return Boolean(
|
|
176
|
+
/(?:需求|范围|验收)/.test(text)&&nextR&&nextR!==rVersion
|
|
177
|
+
||/(?:方案|计划)/.test(text)&&nextP&&nextP!==pVersion
|
|
178
|
+
||/(?:SUPERSEDED|已失效|已废弃|已撤销)/i.test(text)
|
|
179
|
+
&&/(?:需求|方案|计划|R[1-9][0-9]*|P[1-9][0-9]*)/i.test(text)
|
|
180
|
+
);
|
|
181
|
+
});
|
|
182
|
+
if(revisedAfterApproval){
|
|
183
|
+
fail("APPROVAL_REVISED_AFTER_CONFIRMATION");return false;
|
|
184
|
+
}
|
|
185
|
+
const userKey=messageId(pUser.el,"user");
|
|
186
|
+
const snap=inspect();
|
|
187
|
+
// Normally the model calls Start during its P-confirmation Turn.
|
|
188
|
+
// A fresh, explicitly scoped native Start intent can also adopt AFTER
|
|
189
|
+
// that assistant Turn ends (e.g. MCP schema was stale in the same Chat).
|
|
190
|
+
// Only the exact current Chat ID, last R/P approval user identity and
|
|
191
|
+
// completed assistant reply qualify. A historical unscoped idle Chat
|
|
192
|
+
// must never become an Owner just because R/P messages are visible.
|
|
193
|
+
const explicitChatId=typeof message.explicitChatId==="string"
|
|
194
|
+
? message.explicitChatId.toLowerCase():null;
|
|
195
|
+
const currentId=path.match(/\/c\/([0-9a-f-]{12,})$/i)?.[1].toLowerCase();
|
|
196
|
+
// The managed lease may scope an idle, already-open Chat by the exact
|
|
197
|
+
// Task ID in BOTH real native R/P approval turns. No task scope from
|
|
198
|
+
// copied Context prose or generic unscoped historical confirmations.
|
|
199
|
+
const issueTask=x=>textOf(x).match(
|
|
200
|
+
/^([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}[||]/i)?.[1]||null;
|
|
201
|
+
const taskScoped=typeof message.expectedTaskId==="string"
|
|
202
|
+
&&message.expectedTaskId.length>=8
|
|
203
|
+
&&issueTask(rUser)===message.expectedTaskId
|
|
204
|
+
&&issueTask(pUser)===message.expectedTaskId;
|
|
205
|
+
if(message.expectedTaskId!==undefined&&!taskScoped){
|
|
206
|
+
fail("APPROVAL_TASK_SCOPE_MISMATCH");return false;
|
|
207
|
+
}
|
|
208
|
+
const scopedIdle=Boolean(
|
|
209
|
+
(explicitChatId&&explicitChatId===currentId||taskScoped)
|
|
210
|
+
&&!snap.stop&&!snap.busy&&snap.assistantKey
|
|
211
|
+
&&snap.composerReady&&snap.copyAction&&snap.text
|
|
212
|
+
&&!snap.pendingConfirmation);
|
|
213
|
+
if(!userKey ||snap.path!==path||snap.userKey!==userKey
|
|
214
|
+
||!(snap.stop||snap.busy||scopedIdle)
|
|
215
|
+
||snap.fatal||snap.dialog||snap.toolUnknown){
|
|
216
|
+
fail("APPROVAL_LAST_TURN_UNVERIFIED");return false;
|
|
217
|
+
}
|
|
218
|
+
reply({contract:CONTRACT,status:"VERIFIED",page:path,
|
|
219
|
+
userKey,rVersion,pVersion,priorAssistantKey:messageId(pAssistant.el,"assistant"),
|
|
220
|
+
// Idle post-approval assistant was completed BEFORE adoption.
|
|
221
|
+
// This is a historical baseline, never a fresh execution Turn.
|
|
222
|
+
...(scopedIdle?{postApprovalAssistantKey:snap.assistantKey}:{})});
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
return false;
|
|
226
|
+
};
|
|
227
|
+
})();
|