@tomflow/chatloop-tools 0.9.46 → 0.9.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.mjs +25 -11
- package/lib/gateway.mjs +24 -3
- package/lib/trace-gateway.mjs +13 -1
- package/node_modules/@tomflow/chatloop-context/package.json +2 -2
- package/node_modules/@tomflow/chatloop-extension/README.md +2 -2
- package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +2 -1
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +3 -2
- package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
- package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +19 -2
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -1
- package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +43 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +1 -0
- package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +1 -1
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +23 -1
- package/node_modules/@tomflow/chatloop-extension/package.json +2 -2
- package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +7 -3
- package/node_modules/@tomflow/chatloop-trace/README.md +3 -2
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +11 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +35 -17
- package/package.json +6 -6
- package/providers/extension.mjs +1 -1
package/index.mjs
CHANGED
|
@@ -13,6 +13,7 @@ import {createCliCommandRouter} from './lib/cli-command-router.mjs';
|
|
|
13
13
|
let auditPort=null;
|
|
14
14
|
const auditBacklog=[];
|
|
15
15
|
let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0,auditLost=0;
|
|
16
|
+
let auditLastLossCode=null,mcpAudit=null;
|
|
16
17
|
let formObservationLost=0,documentObservationLost=0;
|
|
17
18
|
const OBSERVER_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;
|
|
18
19
|
const localError=code=>Object.assign(Error(code),{code});
|
|
@@ -34,6 +35,8 @@ async function drainAudit(){
|
|
|
34
35
|
auditNoOwnerRetries++<MAX_NO_OWNER_RETRIES)break;
|
|
35
36
|
auditBacklog.shift(); // unknown telemetry is dropped, not retried
|
|
36
37
|
auditLost++;
|
|
38
|
+
auditLastLossCode=/^[A-Z][A-Z0-9_]{1,95}$/.test(error?.code||'')?error.code:
|
|
39
|
+
'TRACE_AUDIT_SINK_FAILED';
|
|
37
40
|
auditNoOwnerRetries=0;
|
|
38
41
|
}
|
|
39
42
|
}
|
|
@@ -49,7 +52,9 @@ async function drainAudit(){
|
|
|
49
52
|
}
|
|
50
53
|
}
|
|
51
54
|
const recordApi=event=>{
|
|
52
|
-
if(auditBacklog.length>=MAX_AUDIT_BACKLOG){
|
|
55
|
+
if(auditBacklog.length>=MAX_AUDIT_BACKLOG){
|
|
56
|
+
auditLost++;auditLastLossCode='TRACE_AUDIT_BACKLOG_OVERFLOW';return;
|
|
57
|
+
}
|
|
53
58
|
auditBacklog.push(event);
|
|
54
59
|
if(auditPort){
|
|
55
60
|
if(auditRetryTimer){clearTimeout(auditRetryTimer);auditRetryTimer=null;}
|
|
@@ -61,12 +66,15 @@ const apiAspect=createApiAspect('@tomflow/chatloop-tools',{sink:recordApi});
|
|
|
61
66
|
// is delivered. Drain only *after* that reply; never delay an API or replay it.
|
|
62
67
|
async function drainCliTelemetry(timeoutMs=300){
|
|
63
68
|
const deadline=Date.now()+Math.max(0,Math.min(timeoutMs,750));
|
|
64
|
-
|
|
69
|
+
// The MCP AOP's separate queue must also drain before EOF exits.
|
|
70
|
+
const budget=Math.max(0,deadline-Date.now());
|
|
71
|
+
const [aspectFlushed,mcpFlushed]=await Promise.all([apiAspect.drain(budget),
|
|
72
|
+
mcpAudit?.drain(budget)??Promise.resolve(true)]);
|
|
65
73
|
while(auditBacklog.length||auditDraining){
|
|
66
74
|
if(Date.now()>=deadline)return false;
|
|
67
75
|
await new Promise(resolve=>setTimeout(resolve,Math.min(10,deadline-Date.now())));
|
|
68
76
|
}
|
|
69
|
-
return aspectFlushed&&auditLost===0;
|
|
77
|
+
return aspectFlushed&&mcpFlushed&&auditLost===0;
|
|
70
78
|
}
|
|
71
79
|
const INTERNAL_DRAIN=Symbol.for('chat-loop.telemetry.drain.internal');
|
|
72
80
|
// The CLI and Supervisor executable import only this package root.
|
|
@@ -174,12 +182,14 @@ async function runtime(){
|
|
|
174
182
|
const result=await control.talk(request);
|
|
175
183
|
if(request?.action!=='__trace_health'||!result?.traceHealth)return result;
|
|
176
184
|
// Supervisor Writer health is authoritative for persisted spans.
|
|
177
|
-
// Local App loss counters describe this Gateway process,
|
|
178
|
-
// or any individual Form/Document traceRef.
|
|
185
|
+
// Local App and typed API loss counters describe this Gateway process,
|
|
186
|
+
// not the Writer or any individual Form/Document traceRef.
|
|
179
187
|
const health={...result.traceHealth,
|
|
180
188
|
writerStatus:result.traceHealth.status,
|
|
181
|
-
formObservationLost,documentObservationLost
|
|
182
|
-
|
|
189
|
+
formObservationLost,documentObservationLost,
|
|
190
|
+
apiObservationLost:auditLost,
|
|
191
|
+
...(auditLost?{apiObservationLastErrorCode:auditLastLossCode}:{})};
|
|
192
|
+
if((formObservationLost>0||documentObservationLost>0||auditLost>0)
|
|
183
193
|
&&health.status==='OK')health.status='TRACE_DEGRADED';
|
|
184
194
|
return {...result,traceHealth:health};
|
|
185
195
|
};
|
|
@@ -244,13 +254,16 @@ async function runtime(){
|
|
|
244
254
|
...(event.durationMs!==null?{durationMs:event.durationMs}:{}),
|
|
245
255
|
...(event.errorCode?{errorCode:event.errorCode}:{})
|
|
246
256
|
},900).then(reply=>{
|
|
247
|
-
|
|
248
|
-
|
|
257
|
+
// A transport ACK is not proof that the Writer persisted this span.
|
|
258
|
+
if(reply?.status!=='OK'||!OBSERVER_UUID.test(reply.eventId||'')){
|
|
259
|
+
const code=/^[A-Z][A-Z0-9_]{1,95}$/.test(reply?.error?.code||'')
|
|
260
|
+
?reply.error.code:'TRACE_RECORD_FAILED';
|
|
261
|
+
throw localError(code);
|
|
262
|
+
}
|
|
249
263
|
return reply;
|
|
250
264
|
});
|
|
251
265
|
void drainAudit();
|
|
252
|
-
|
|
253
|
-
{sink:recordApi});
|
|
266
|
+
mcpAudit=createApiAspect('@tomflow/chatloop-tools',{sink:recordApi});
|
|
254
267
|
// Only declared providers may create a per-tool observation wrapper.
|
|
255
268
|
// Unknown tool names must not grow a process-lifetime cache.
|
|
256
269
|
const declaredToolNames=new Set(providerDefinitions.flatMap(p=>p.names));
|
|
@@ -291,6 +304,7 @@ async function runtime(){
|
|
|
291
304
|
});
|
|
292
305
|
gateway.configureGateway({
|
|
293
306
|
CONTRACT:control.CONTRACT,PACKAGE_VERSION:control.PACKAGE_VERSION,
|
|
307
|
+
flushAfterInputEnd:()=>drainCliTelemetry(750),
|
|
294
308
|
toolRouter,
|
|
295
309
|
// MCP handshake / rejected protocol requests do not reach toolRouter.
|
|
296
310
|
// Keep them inside the same isolated Supervisor observation channel.
|
package/lib/gateway.mjs
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
// One MCP transport: all tools/list and tools/call routes come from the
|
|
2
2
|
// compiled Provider registry, never from per-provider branches here.
|
|
3
|
-
let CONTRACT,PACKAGE_VERSION,toolRouter,observeProtocol;
|
|
3
|
+
let CONTRACT,PACKAGE_VERSION,toolRouter,observeProtocol,flushAfterInputEnd;
|
|
4
4
|
let configured=false;
|
|
5
5
|
export function configureGateway(ports){
|
|
6
6
|
if(configured)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
7
7
|
for(const key of ['CONTRACT','PACKAGE_VERSION','toolRouter','observeProtocol'])
|
|
8
8
|
if(ports?.[key]===undefined)throw Error('TOOLS_PORT_MISSING:'+key);
|
|
9
|
-
({CONTRACT,PACKAGE_VERSION,toolRouter,observeProtocol
|
|
9
|
+
({CONTRACT,PACKAGE_VERSION,toolRouter,observeProtocol,
|
|
10
|
+
flushAfterInputEnd}=ports);
|
|
11
|
+
if(flushAfterInputEnd!==undefined&&typeof flushAfterInputEnd!=='function')
|
|
12
|
+
throw Error('TOOLS_PORT_INVALID:flushAfterInputEnd');
|
|
10
13
|
if(['list','call','listResources','readResource']
|
|
11
14
|
.some(k=>typeof toolRouter[k]!=='function'))
|
|
12
15
|
throw Error('TOOLS_PORT_INVALID:toolRouter');
|
|
@@ -39,6 +42,7 @@ function modernMeta(request){
|
|
|
39
42
|
}
|
|
40
43
|
export function runGateway(){
|
|
41
44
|
let buf='',connected=false;
|
|
45
|
+
const inFlight=new Set();
|
|
42
46
|
const write=message=>process.stdout.write(JSON.stringify(message)+'\n');
|
|
43
47
|
const reply=(id,result)=>{
|
|
44
48
|
write({jsonrpc:'2.0',id,result});
|
|
@@ -125,10 +129,27 @@ export function runGateway(){
|
|
|
125
129
|
let task;
|
|
126
130
|
try{task=handledByRouter?invoke():observeProtocol(m.method,invoke)}
|
|
127
131
|
catch{reject(m.id,-32603,'INTERNAL_ERROR');continue}
|
|
128
|
-
|
|
132
|
+
const pending=Promise.resolve(task).catch(()=>{
|
|
129
133
|
reject(m.id,-32603,'INTERNAL_ERROR');
|
|
130
134
|
});
|
|
135
|
+
inFlight.add(pending);
|
|
136
|
+
void pending.finally(()=>inFlight.delete(pending));
|
|
131
137
|
}
|
|
132
138
|
if(Buffer.byteLength(buf,'utf8')>1024*1024)oversize();
|
|
133
139
|
});
|
|
140
|
+
// Closing MCP stdin after a successful reply must not strand the real
|
|
141
|
+
// BEGIN/terminal spans in a soft, unref'd audit queue. This bounded EOF
|
|
142
|
+
// cleanup never replays a tool or alters its already-emitted result.
|
|
143
|
+
process.stdin.once('end',()=>{
|
|
144
|
+
void (async()=>{
|
|
145
|
+
if(inFlight.size){
|
|
146
|
+
let timer;
|
|
147
|
+
try{await Promise.race([
|
|
148
|
+
Promise.allSettled([...inFlight]),
|
|
149
|
+
new Promise(resolve=>{timer=setTimeout(resolve,750)})
|
|
150
|
+
])}finally{clearTimeout(timer)}
|
|
151
|
+
}
|
|
152
|
+
await flushAfterInputEnd?.();
|
|
153
|
+
})().catch(()=>{});
|
|
154
|
+
});
|
|
134
155
|
}
|
package/lib/trace-gateway.mjs
CHANGED
|
@@ -24,7 +24,7 @@ export const traceGatewayEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1
|
|
|
24
24
|
&&getAllowedProjects().length===1;
|
|
25
25
|
export const traceDiagnoseTool={
|
|
26
26
|
name:'chat_loop_trace_diagnose',
|
|
27
|
-
description:'Read-only Trace timeline for an
|
|
27
|
+
description:'Read-only Trace timeline for an authorized Project or an unguessable Form/Document traceRef under api_system. Judge this instance by scopedTraceVerdict and gaps; gatewayHealth and globalObservationWarnings are process-wide and cannot identify which Chat/Task lost observations.',
|
|
28
28
|
inputSchema:{
|
|
29
29
|
type:'object',additionalProperties:false,
|
|
30
30
|
required:['projectRef'],
|
|
@@ -220,6 +220,11 @@ export async function runTraceDiagnose(args){
|
|
|
220
220
|
globalWarnings.push('FORM_TRACE_OBSERVATION_LOSS');
|
|
221
221
|
if(health?.documentObservationLost>0)
|
|
222
222
|
globalWarnings.push('DOCUMENT_TRACE_OBSERVATION_LOSS');
|
|
223
|
+
if(health?.apiObservationLost>0){
|
|
224
|
+
globalWarnings.push('MCP_API_TRACE_OBSERVATION_LOSS');
|
|
225
|
+
result.globalApiObservationLoss={count:health.apiObservationLost,
|
|
226
|
+
lastErrorCode:health.apiObservationLastErrorCode||'UNVERIFIED'};
|
|
227
|
+
}
|
|
223
228
|
if(globalWarnings.length)result.globalObservationWarnings=globalWarnings;
|
|
224
229
|
if(result.writerHealth==='TRACE_DEGRADED'){
|
|
225
230
|
result.gaps.push(health?.errorCode
|
|
@@ -235,6 +240,13 @@ export async function runTraceDiagnose(args){
|
|
|
235
240
|
}
|
|
236
241
|
result.gaps=[...new Set(result.gaps)];
|
|
237
242
|
if(result.gaps.length)result.confidence='INCOMPLETE';
|
|
243
|
+
// A process-wide loss counter is NOT an instance-level missing API span.
|
|
244
|
+
// State both scopes explicitly so consumers do not fail an unrelated Chat.
|
|
245
|
+
result.scopedTraceVerdict=result.gaps.includes('NO_MATCHING_EVENTS')
|
|
246
|
+
?'NOT_OBSERVED':result.gaps.length?'INCOMPLETE'
|
|
247
|
+
:(result.timeline?.length?'OBSERVED_EVENTS_PAIRED':'NOT_OBSERVED');
|
|
248
|
+
if(result.globalObservationWarnings?.length)
|
|
249
|
+
result.globalWarningScope='PROCESS_WIDE_NOT_ATTRIBUTED_TO_QUERY';
|
|
238
250
|
return result;
|
|
239
251
|
}
|
|
240
252
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tomflow/chatloop-context",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.15",
|
|
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.
|
|
37
|
+
"@tomflow/chatloop-extension": "0.4.21",
|
|
38
38
|
"@tomflow/chatloop-trace": "0.4.6"
|
|
39
39
|
}
|
|
40
40
|
}
|
|
@@ -42,7 +42,7 @@ The builder creates their isolated Action HTML, which uses the same
|
|
|
42
42
|
dispatch switch needs modification. The builder refuses duplicate names,
|
|
43
43
|
privileged type changes, invalid read modes, missing assets and stale output.
|
|
44
44
|
|
|
45
|
-
**A declaration does not grant sending authority.** Start, Continue, Handoff,
|
|
45
|
+
**A declaration does not grant sending authority.** The separately reviewed `entry test` Action is a TEST_ONLY, Native-authorized first-turn fixture: it requires an explicit confirmation, creates one ordinary Chat with a real structured @ App mention, and must prove the unique user message without a Browser Owner; it cannot approve R/P or invoke Start/Continue/Handoff. Its explicit privilege review is allowlisted by exact ID, route, page, deadline and receipt format. Any other new sending declaration is denied. Start, Continue, Handoff,
|
|
46
46
|
Clean, Status, screenshot and reload keep their reviewed, explicit Worker
|
|
47
47
|
handlers and existing trust boundaries. New send/Owner/Native mutation
|
|
48
48
|
requires a separate authorized security review and implementation; it cannot
|
|
@@ -72,7 +72,7 @@ Run: chatloop-extension <command> --help
|
|
|
72
72
|
|
|
73
73
|
```text
|
|
74
74
|
Usage: chatloop-extension extension <command>
|
|
75
|
-
Commands: chat text | chat dom | chat screenshot | reload | continue | handoff | clean <tab-id> | status | start
|
|
75
|
+
Commands: chat text | chat dom | chat screenshot | reload | continue | handoff | clean <tab-id> | status | start | entry test
|
|
76
76
|
Run: chatloop-extension extension <command> --help
|
|
77
77
|
```
|
|
78
78
|
|
|
@@ -8,4 +8,5 @@ import {capability as a5} from './capabilities/handoff.mjs';
|
|
|
8
8
|
import {capability as a6} from './capabilities/clean.mjs';
|
|
9
9
|
import {capability as a7} from './capabilities/status.mjs';
|
|
10
10
|
import {capability as a8} from './capabilities/start.mjs';
|
|
11
|
-
|
|
11
|
+
import {capability as a9} from './capabilities/entry_test.mjs';
|
|
12
|
+
export const actionCapabilities=Object.freeze([a0,a1,a2,a3,a4,a5,a6,a7,a8,a9]);
|
|
@@ -20,7 +20,8 @@ const HELP={
|
|
|
20
20
|
'extension continue':'Usage: chatloop-extension extension continue (JSON intent on stdin)\nSubmit next-turn text or query receipt; does not send directly.',
|
|
21
21
|
'extension handoff':'Usage: chatloop-extension extension handoff (JSON intent on stdin)\nRequest early handoff or query receipt; does not transfer directly.',
|
|
22
22
|
'extension status':'Usage: chatloop-extension extension status\nRead-only, verified active Web Chat status.',
|
|
23
|
-
'extension start':'Usage: chatloop-extension extension start (JSON on stdin)\nStart a new task with prompt, or use mode=adopt (no prompt) to bind the only R/P-approved existing Chat without sending.'
|
|
23
|
+
'extension start':'Usage: chatloop-extension extension start (JSON on stdin)\nStart a new task with prompt, or use mode=adopt (no prompt) to bind the only R/P-approved existing Chat without sending.',
|
|
24
|
+
'extension entry test':'Usage: chatloop-extension extension entry test (JSON intent on stdin)\nTEST_ONLY: use the built-in Extension Action to create a new normal Chat, choose the actual native @ App, and send exactly once without a Browser Owner.'
|
|
24
25
|
};
|
|
25
26
|
function helpFor(args){
|
|
26
27
|
if(args.length===1&&['-h','--help','help'].includes(args[0]))return HELP[''];
|
|
@@ -108,7 +109,7 @@ async function execute(argv) {
|
|
|
108
109
|
return {implemented:['capabilities','host install <extension-id>',
|
|
109
110
|
...actionCapabilities.map(cap=>'extension '+cap.cli.join(' ')+
|
|
110
111
|
(cap.kind==='owner-clean'?' <tab-id>':
|
|
111
|
-
['owner-intent','owner-start'].includes(cap.kind)?' (JSON on stdin)':''))],
|
|
112
|
+
['owner-intent','owner-start','entry-test'].includes(cap.kind)?' (JSON on stdin)':''))],
|
|
112
113
|
available:existsSync(configFile()),hostConfigured:existsSync(configFile())};
|
|
113
114
|
}
|
|
114
115
|
if(argv[0]==='host'&&argv[1]==='install'&&argv.length===3)return installHost(argv[2]);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'entry_test',page:'entry_test.html',cli:['entry','test'],kind:'entry-test',waitMs:310000,textResult:true,description:'One TEST_ONLY native @ App new-Chat entry; no Browser Owner'});
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// Reviewed TEST_ONLY native @ App entry. Never owns a Loop Session or uses Continue.
|
|
2
|
+
const HOST='com.tomflow.chatloop.extension';
|
|
3
|
+
const statusNode=document.getElementById('status');
|
|
4
|
+
const detailNode=document.getElementById('details');
|
|
5
|
+
const show=(status,detail)=>{statusNode.textContent=status;detailNode.textContent=detail;document.body.dataset.result=status==='SUCCESS'?'success':'error';};
|
|
6
|
+
const pause=ms=>new Promise(r=>setTimeout(r,ms));
|
|
7
|
+
const safeCode=code=>/^[A-Z][A-Z0-9_]{1,95}$/.test(code||'')?code:'ENTRY_TEST_UNVERIFIED';
|
|
8
|
+
async function readNewChat(id,recoverTestAt=false,recoverExactDraft=''){
|
|
9
|
+
const end=Date.now()+90000;
|
|
10
|
+
let cleaned=false;
|
|
11
|
+
while(Date.now()<end){
|
|
12
|
+
const tab=await chrome.tabs.get(id).catch(()=>null);
|
|
13
|
+
if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
|
|
14
|
+
if(tab.url==='https://chatgpt.com/'){
|
|
15
|
+
const proof=await chrome.scripting.executeScript({target:{tabId:id},
|
|
16
|
+
func:(recover,exactDraft)=>{
|
|
17
|
+
if(location.origin!=='https://chatgpt.com'||location.pathname!=='/')return false;
|
|
18
|
+
const mains=[...document.querySelectorAll('main')].filter(e=>e.getClientRects().length);
|
|
19
|
+
const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
|
|
20
|
+
||document.querySelector('[contenteditable="true"][data-composer-markdown]');
|
|
21
|
+
if(mains.length!==1||!editor?.getClientRects().length||!editor.isContentEditable
|
|
22
|
+
||mains[0].querySelector('[data-chatgpt-search-message-ids],[data-message-author-role]'))
|
|
23
|
+
return false;
|
|
24
|
+
const current=(editor.innerText||editor.textContent||'').trim();
|
|
25
|
+
if(!current)return 'READY';
|
|
26
|
+
const canonical=value=>String(value||'').replace(/\s+/g,'');
|
|
27
|
+
const exactRecovery=typeof exactDraft==='string'&&!!exactDraft
|
|
28
|
+
&&canonical(current)===canonical(exactDraft);
|
|
29
|
+
if(!recover&& !exactRecovery)return 'HAS_DRAFT';
|
|
30
|
+
if(recover&¤t!=='@'&&!exactRecovery)return 'HAS_DRAFT';
|
|
31
|
+
// Only a verified leftover "@" or byte-equivalent earlier TEST_ONLY
|
|
32
|
+
// draft may be cleared, on the newly created empty Chat home. Never
|
|
33
|
+
// touch other drafts, user turns or existing Chat tabs.
|
|
34
|
+
editor.focus();
|
|
35
|
+
const selection=window.getSelection(),range=document.createRange();
|
|
36
|
+
range.selectNodeContents(editor);selection.removeAllRanges();selection.addRange(range);
|
|
37
|
+
if(!document.execCommand('delete',false))return 'RECOVERY_FAILED';
|
|
38
|
+
return !(editor.innerText||editor.textContent||'').trim()
|
|
39
|
+
?'RECOVERED_DRAFT':'RECOVERY_FAILED';
|
|
40
|
+
},args:[recoverTestAt&&!cleaned,cleaned?'':recoverExactDraft]}).catch(()=>null);
|
|
41
|
+
const state=proof?.[0]?.result;
|
|
42
|
+
if(state==='READY')return;
|
|
43
|
+
if(state==='RECOVERED_DRAFT'){cleaned=true;continue;}
|
|
44
|
+
if(state==='HAS_DRAFT')throw Error('ENTRY_COMPOSER_HAS_DRAFT');
|
|
45
|
+
if(state==='RECOVERY_FAILED')throw Error('ENTRY_AT_RECOVERY_FAILED');
|
|
46
|
+
}
|
|
47
|
+
await pause(320);
|
|
48
|
+
}
|
|
49
|
+
throw Error('ENTRY_COMPOSER_NOT_READY');
|
|
50
|
+
}
|
|
51
|
+
async function nativeMentionAndSend(id,appId,prompt){
|
|
52
|
+
const response=await chrome.scripting.executeScript({target:{tabId:id},
|
|
53
|
+
func:async(appId,prompt)=>{
|
|
54
|
+
const wait=ms=>new Promise(r=>setTimeout(r,ms));
|
|
55
|
+
const visible=e=>Boolean(e?.getClientRects?.().length);
|
|
56
|
+
const canonical=v=>String(v||'').replace(/\s+/g,'');
|
|
57
|
+
const fail=(code,diagnostic='')=>({status:'FAILED',code,diagnostic:diagnostic.slice(0,180)});
|
|
58
|
+
const editor=document.querySelector('#prompt-textarea[contenteditable="true"]')
|
|
59
|
+
||document.querySelector('[contenteditable="true"][data-composer-markdown]');
|
|
60
|
+
if(location.origin!=='https://chatgpt.com'||location.pathname!=='/'
|
|
61
|
+
||!editor||!visible(editor)||!editor.isContentEditable
|
|
62
|
+
||(editor.innerText||editor.textContent||'').trim())
|
|
63
|
+
return fail('ENTRY_EDITOR_UNVERIFIED');
|
|
64
|
+
// Commit the natural-language task to the host editor first. Selecting
|
|
65
|
+
// a native App mention can rehydrate the composer and otherwise discard
|
|
66
|
+
// text entered immediately after the selection transaction.
|
|
67
|
+
editor.focus();
|
|
68
|
+
if(!document.execCommand('insertText',false,prompt))return fail('ENTRY_PROMPT_INPUT_FAILED');
|
|
69
|
+
await wait(700);
|
|
70
|
+
if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
|
|
71
|
+
return fail('ENTRY_PROMPT_NOT_VISIBLE');
|
|
72
|
+
const selection=window.getSelection(),range=document.createRange();
|
|
73
|
+
range.selectNodeContents(editor);range.collapse(true);
|
|
74
|
+
selection.removeAllRanges();selection.addRange(range);
|
|
75
|
+
if(!document.execCommand('insertText',false,'@'))return fail('ENTRY_AT_INPUT_FAILED');
|
|
76
|
+
let choice=null,diagnostic='';
|
|
77
|
+
const selectors=['button[data-plugin-impression-id]','[role="option"]','[role="menuitem"]','[cmdk-item]',
|
|
78
|
+
'[data-testid*="app-item"]','[data-testid*="mention-item"]'];
|
|
79
|
+
for(let i=0;i<55;i++){
|
|
80
|
+
if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED');
|
|
81
|
+
const nodes=[...document.querySelectorAll(selectors.join(','))]
|
|
82
|
+
.filter(visible).filter(e=>(e.innerText||'').includes('Chat Loop'));
|
|
83
|
+
const matching=nodes.filter(e=>e.getAttribute('data-plugin-impression-id')===appId);
|
|
84
|
+
if(matching.length===1){choice=matching[0];break;}
|
|
85
|
+
const exact=nodes.filter(e=>{
|
|
86
|
+
const t=(e.innerText||'').trim();
|
|
87
|
+
return t==='Chat Loop'||t.startsWith('Chat Loop\n');
|
|
88
|
+
});
|
|
89
|
+
if(exact.length===1){choice=exact[0];break;}
|
|
90
|
+
if(!exact.length && nodes.length===1){choice=nodes[0];break;}
|
|
91
|
+
diagnostic=nodes.slice(0,4).map(e=>e.getAttribute('data-plugin-impression-id')+':'+(e.innerText||'').slice(0,55)).join('|');
|
|
92
|
+
await wait(220);
|
|
93
|
+
}
|
|
94
|
+
if(!choice)return fail('ENTRY_NATIVE_APP_OPTION_MISSING',diagnostic);
|
|
95
|
+
choice.click();
|
|
96
|
+
// A native mention is a structured composer node, not a literal "@Chat Loop" string.
|
|
97
|
+
let native=false;
|
|
98
|
+
for(let i=0;i<38;i++){
|
|
99
|
+
const tokens=[...editor.querySelectorAll('[data-prompt-link-href],[data-app-mention-path],a[href],[data-type="mention"]')];
|
|
100
|
+
native=tokens.some(e=>(e.getAttribute('data-prompt-link-href')||'').includes(appId)
|
|
101
|
+
||(e.getAttribute('data-app-mention-path')||'').includes(appId)
|
|
102
|
+
||(e.getAttribute('href')||'').includes(appId));
|
|
103
|
+
if(native)break;
|
|
104
|
+
await wait(120);
|
|
105
|
+
}
|
|
106
|
+
if(!native)return fail('ENTRY_NATIVE_MENTION_UNVERIFIED',editor.innerHTML);
|
|
107
|
+
// Wait for the host selection transaction to settle; never rely on
|
|
108
|
+
// a transient DOM text match before clicking its native send button.
|
|
109
|
+
for(let i=0;i<5;i++){
|
|
110
|
+
await wait(240);
|
|
111
|
+
if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED_BEFORE_SEND');
|
|
112
|
+
if(!canonical(editor.innerText||editor.textContent).includes(canonical(prompt)))
|
|
113
|
+
return fail('ENTRY_PROMPT_LOST_ON_MENTION');
|
|
114
|
+
}
|
|
115
|
+
const tokens=[...editor.querySelectorAll('[data-prompt-link-href],[data-app-mention-path],a[href],[data-type="mention"]')];
|
|
116
|
+
if(!tokens.some(e=>(e.getAttribute('data-prompt-link-href')||'').includes(appId)
|
|
117
|
+
||(e.getAttribute('data-app-mention-path')||'').includes(appId)
|
|
118
|
+
||(e.getAttribute('href')||'').includes(appId)))
|
|
119
|
+
return fail('ENTRY_NATIVE_MENTION_LOST');
|
|
120
|
+
const send=document.querySelector('button[data-testid="send-button"]')
|
|
121
|
+
||document.querySelector('button[data-testid="composer-send-button"]')
|
|
122
|
+
||document.querySelector('button[aria-label="发送"]')
|
|
123
|
+
||document.querySelector('button[aria-label="Send message"]');
|
|
124
|
+
if(!send||send.disabled||!visible(send))return fail('ENTRY_SEND_UNAVAILABLE');
|
|
125
|
+
if(location.pathname!=='/')return fail('ENTRY_PAGE_CHANGED');
|
|
126
|
+
send.click(); // Exactly once. No caller retries on an uncertain receipt.
|
|
127
|
+
return {status:'CLICKED_ONCE'};
|
|
128
|
+
},args:[appId,prompt]}).catch(()=>null);
|
|
129
|
+
const r=response?.[0]?.result;
|
|
130
|
+
if(!r)throw Error('ENTRY_SEND_RESULT_UNKNOWN');
|
|
131
|
+
if(r.status!=='CLICKED_ONCE')throw Error(safeCode(r.code));
|
|
132
|
+
}
|
|
133
|
+
async function verifyNativeUserTurn(id,appId,prompt){
|
|
134
|
+
const end=Date.now()+120000;let last=null,stable=0,mismatch=0;
|
|
135
|
+
while(Date.now()<end){
|
|
136
|
+
const tab=await chrome.tabs.get(id).catch(()=>null);
|
|
137
|
+
if(!tab)throw Error('ENTRY_CHAT_TAB_GONE');
|
|
138
|
+
const path=tab.url&&new URL(tab.url).pathname;
|
|
139
|
+
if(/^\/c\/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(path||'')){
|
|
140
|
+
const r=await chrome.scripting.executeScript({target:{tabId:id},
|
|
141
|
+
func:(appId,prompt)=>{
|
|
142
|
+
if(location.origin!=='https://chatgpt.com')return null;
|
|
143
|
+
// ChatGPT can render conversation turns outside its composer <main>.
|
|
144
|
+
// A main-scoped read silently misses real user turns in that layout.
|
|
145
|
+
const users=[...document.querySelectorAll('[data-chatgpt-search-unit-key][data-chatgpt-search-message-ids]')]
|
|
146
|
+
.filter(x=>x.getAttribute('data-chatgpt-search-unit-key')?.endsWith(':user'));
|
|
147
|
+
if(!users.length){
|
|
148
|
+
users.push(...document.querySelectorAll('[data-message-author-role="user"]'));
|
|
149
|
+
}
|
|
150
|
+
const u=users.at(-1);
|
|
151
|
+
const key=u?.getAttribute('data-message-id')
|
|
152
|
+
||u?.getAttribute('data-chatgpt-search-message-ids')?.split(/\s+/)[0];
|
|
153
|
+
const bubble=u?.querySelector('[data-user-message-bubble="true"]')||u;
|
|
154
|
+
const m=bubble?.querySelector('[data-prompt-link-href="app://'+appId+'"]');
|
|
155
|
+
const canonical=v=>String(v||'').replace(/\s+/g,'');
|
|
156
|
+
return {path:location.pathname,userCount:users.length,
|
|
157
|
+
ids:users.map(x=>x.getAttribute('data-message-id')
|
|
158
|
+
||x.getAttribute('data-chatgpt-search-message-ids')?.split(/\s+/)[0]),
|
|
159
|
+
userKey:typeof key==='string'&&m
|
|
160
|
+
&&canonical(bubble.innerText||bubble.textContent).includes(canonical(prompt))
|
|
161
|
+
?'user:'+key:null,hasNativeApp:Boolean(m)};
|
|
162
|
+
},args:[appId,prompt]}).catch(()=>null);
|
|
163
|
+
const v=r?.[0]?.result;
|
|
164
|
+
if(v?.userCount>1||v?.ids?.some(x=>x!==v.ids[0]))
|
|
165
|
+
throw Error('ENTRY_DUPLICATE_USER_TURN');
|
|
166
|
+
if(v?.path===path&&v.userCount===1&&v.hasNativeApp&&!v.userKey){
|
|
167
|
+
if(++mismatch>=4)throw Error('ENTRY_USER_TURN_CONTENT_MISMATCH');
|
|
168
|
+
}else mismatch=0;
|
|
169
|
+
if(v?.path===path&&v.userCount===1&&v.hasNativeApp&&v.userKey){
|
|
170
|
+
const k=path+'|'+v.userKey;
|
|
171
|
+
stable=last===k?stable+1:1;last=k;
|
|
172
|
+
if(stable>=4){
|
|
173
|
+
const chatId=path.slice(3);
|
|
174
|
+
return {status:'OK',testOnly:true,appId,
|
|
175
|
+
activeChatId:chatId,activeChatUrl:'https://chatgpt.com'+path,
|
|
176
|
+
userKey:v.userKey};
|
|
177
|
+
}
|
|
178
|
+
}else{stable=0;last=null;}
|
|
179
|
+
}
|
|
180
|
+
await pause(350);
|
|
181
|
+
}
|
|
182
|
+
throw Error('ENTRY_NATIVE_TURN_RECEIPT_UNKNOWN');
|
|
183
|
+
}
|
|
184
|
+
async function run(){
|
|
185
|
+
const own=await chrome.tabs.getCurrent();
|
|
186
|
+
const params=new URLSearchParams(location.search),id=params.get('requestId');
|
|
187
|
+
if(!own?.id||own.url!==location.href||[...params.keys()].length!==1
|
|
188
|
+
||!/^[a-f0-9]{32}$/.test(id||'')
|
|
189
|
+
||location.href!==chrome.runtime.getURL('entry_test.html')+'?requestId='+id)
|
|
190
|
+
throw Error('ENTRY_TEST_ACTION_SOURCE_INVALID');
|
|
191
|
+
const proof=await chrome.runtime.sendNativeMessage(HOST,{op:'acquire',id,action:'entry_test'});
|
|
192
|
+
if(proof?.status!=='OK'||proof.action!=='entry_test'||proof.id!==id
|
|
193
|
+
||!proof.nonce||proof.intent?.confirmed!==true||proof.intent?.testOnly!==true)
|
|
194
|
+
throw Error('ENTRY_TEST_NATIVE_UNAUTHORIZED');
|
|
195
|
+
const intent=proof.intent;
|
|
196
|
+
let tab,clicked=false;
|
|
197
|
+
try{
|
|
198
|
+
// This read-only Worker/Native gate may admit a provably frozen orphan
|
|
199
|
+
// for an independent TEST_ONLY Chat; it never releases the old Session.
|
|
200
|
+
const admitted=async()=>{
|
|
201
|
+
const decision=await chrome.runtime.sendMessage({
|
|
202
|
+
type:'CHAT_LOOP_ENTRY_TEST_ADMISSION_V1',requestId:id}).catch(()=>null);
|
|
203
|
+
if(decision?.status!=='OK'||decision.scope!=='TEST_ONLY')
|
|
204
|
+
throw Error(safeCode(decision?.code||'ENTRY_TEST_OWNER_UNVERIFIED'));
|
|
205
|
+
};
|
|
206
|
+
await admitted();
|
|
207
|
+
let result;
|
|
208
|
+
if(intent.verifyChatUrl){
|
|
209
|
+
// Pure receipt recovery. Never click, resend, adopt or modify an existing Chat.
|
|
210
|
+
show('RUNNING','只读核对已存在 Chat 的唯一原生 @ App 用户消息。');
|
|
211
|
+
const candidates=await chrome.tabs.query({url:intent.verifyChatUrl});
|
|
212
|
+
const matches=candidates.filter(t=>t.url===intent.verifyChatUrl
|
|
213
|
+
&&Number.isSafeInteger(t.id));
|
|
214
|
+
if(matches.length!==1)throw Error('ENTRY_VERIFY_TAB_UNVERIFIED');
|
|
215
|
+
result=await verifyNativeUserTurn(matches[0].id,intent.appId,intent.prompt);
|
|
216
|
+
}else{
|
|
217
|
+
show('RUNNING','新普通 Chat 正在加载;仅验证原生 App 入口,不进行批准或 Start。');
|
|
218
|
+
tab=await chrome.tabs.create({url:'https://chatgpt.com/',active:true,
|
|
219
|
+
windowId:own.windowId,openerTabId:own.id});
|
|
220
|
+
if(!Number.isSafeInteger(tab?.id))throw Error('ENTRY_NEW_TAB_UNVERIFIED');
|
|
221
|
+
await readNewChat(tab.id,intent.recoverTestAt===true,intent.recoverExactDraft||'');
|
|
222
|
+
await admitted(); // Recheck before the only possible first send.
|
|
223
|
+
await nativeMentionAndSend(tab.id,intent.appId,intent.prompt);
|
|
224
|
+
clicked=true;
|
|
225
|
+
result=await verifyNativeUserTurn(tab.id,intent.appId,intent.prompt);
|
|
226
|
+
}
|
|
227
|
+
const stored=await chrome.runtime.sendNativeMessage(HOST,{op:'complete',id,
|
|
228
|
+
nonce:proof.nonce,action:'entry_test',status:'OK',payload:JSON.stringify(result)});
|
|
229
|
+
if(stored?.status!=='SAVED'||stored.id!==id)throw Error('ENTRY_TEST_NATIVE_RECEIPT_UNVERIFIED');
|
|
230
|
+
show('SUCCESS','已确认唯一原生 @ App 用户消息,未创建 Browser Owner。');
|
|
231
|
+
await chrome.tabs.remove(own.id);
|
|
232
|
+
}catch(error){
|
|
233
|
+
const code=safeCode(error?.message);
|
|
234
|
+
// After an uncertain click, never send again. Preserve created chat for audit.
|
|
235
|
+
const saved=await chrome.runtime.sendNativeMessage(HOST,{op:'complete',id,
|
|
236
|
+
nonce:proof.nonce,action:'entry_test',status:'FAILED',code}).catch(()=>null);
|
|
237
|
+
show('BLOCKED',code+(clicked?';已发送或副作用未知,禁止重试。':';尚未验证发送。'));
|
|
238
|
+
if(saved?.status==='SAVED')await chrome.tabs.remove(own.id).catch(()=>{});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
void run().catch(error=>show('BLOCKED',safeCode(error?.message)));
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="zh-CN"><head><meta charset="utf-8"><title>Chat Loop · Stage 01 Entry Test</title>
|
|
3
|
+
<style>body{font:15px system-ui,sans-serif;padding:24px;max-width:650px;color:#222}#status{font-weight:bold}#details{white-space:pre-wrap;overflow-wrap:anywhere}body[data-result="error"] #status{color:#b00020}</style>
|
|
4
|
+
</head><body><h1>Chat Loop · Stage 01 TEST_ONLY</h1><p id="status" role="status">VERIFYING</p>
|
|
5
|
+
<p id="details">通过独立认证的 Extension Action,在新的普通 Chat 选择原生 @ App。不会建立 Browser Owner、批准 R/P 或 Start。</p>
|
|
6
|
+
<script src="actions/entry_test.js"></script></body></html>
|
|
@@ -141,16 +141,32 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
|
|
|
141
141
|
fail("APPROVAL_REQUIREMENTS_MISSING");return false;
|
|
142
142
|
}
|
|
143
143
|
const rVersion=rAssistant?versionOf(textOf(rAssistant),"R"):nativeRVersion;
|
|
144
|
+
// A stage-02 plan can generate an immutable Rn synchronization SNAPSHOT
|
|
145
|
+
// after its P approval. It is not a new R approval: Context retains the
|
|
146
|
+
// original R/P approvals and exact P.requirementRef. Only a precisely
|
|
147
|
+
// linked notice is exempt from the "new R version" visual alarm.
|
|
148
|
+
const planDerivedSync=text=>{
|
|
149
|
+
const m=text.match(/(?:^|\n)需求文档派生同步[::]\s*(R[1-9][0-9]*)\s*←\s*已批准\s*(P[1-9][0-9]*)[((]保留原批准\s*(R[1-9][0-9]*)[,,]不签发新 R 审批[))]/);
|
|
150
|
+
return Boolean(m&&m[1]!==rVersion&&m[2]===pVersion
|
|
151
|
+
&&m[3]===rVersion
|
|
152
|
+
&&!/(?:REQUIREMENTS_REVIEW|提交需求评审|R[1-9][0-9]*-ISSUE|已撤销|撤销需求|拒绝需求)/i.test(text)
|
|
153
|
+
&&!/(?:^|\n)\s*#{1,6}\s*R[1-9][0-9]*\s+v[1-9][0-9]*/i.test(text));
|
|
154
|
+
};
|
|
144
155
|
const intervening=rows.slice(rIndex+1,lastUser-1);
|
|
145
156
|
const invalidated=intervening.some(x=>{
|
|
146
157
|
const text=textOf(x);
|
|
147
158
|
if(x.role==="assistant"){
|
|
159
|
+
if(/需求文档派生同步/.test(text)&&!planDerivedSync(text))return true;
|
|
148
160
|
const next=versionOf(text,"R");
|
|
149
|
-
return
|
|
161
|
+
return !planDerivedSync(text)&&/需求|范围|验收/.test(text)&&next&&next!==rVersion;
|
|
150
162
|
}
|
|
151
163
|
// Updating a plan while retaining the approved requirement is NOT
|
|
152
164
|
// a requirement revocation.
|
|
153
165
|
// Only an explicit requirement-targeted change invalidates this R.
|
|
166
|
+
const planSyncRequest=(/(?:修改|修订|调整).{0,14}方案.{0,80}(?:同步|更新|改).{0,14}需求/.test(text)
|
|
167
|
+
||/(?:方案|计划|P[1-9][0-9]*).{0,50}(?:同步|更新|修改|调整|改).{0,50}(?:需求|R[1-9][0-9]*)/.test(text))
|
|
168
|
+
&&!/(?:撤销|取消|拒绝|不批准|不同意|不确认)/.test(text);
|
|
169
|
+
if(planSyncRequest)return false;
|
|
154
170
|
return /(?:撤销|取消|拒绝|不同意|不批准|修改|修订|变更)\s*(?:(?:当前|本次|这份|上述)\s*)?(?:需求|R[1-9][0-9]*)/i.test(text)
|
|
155
171
|
|| /\bR[1-9][0-9]*\b\s*(?:需求)?\s*(?:需要|应当|应该)?\s*(?:撤销|取消|拒绝|修改|修订|变更)/i.test(text);
|
|
156
172
|
});
|
|
@@ -174,7 +190,8 @@ if (message?.type === "CHAT_LOOP_APPROVAL_EVIDENCE_V1") {
|
|
|
174
190
|
const text=textOf(x),nextR=versionOf(text,"R"),
|
|
175
191
|
nextP=versionOf(text,"P");
|
|
176
192
|
return Boolean(
|
|
177
|
-
|
|
193
|
+
/需求文档派生同步/.test(text)&&!planDerivedSync(text)
|
|
194
|
+
||!planDerivedSync(text)&&/(?:需求|范围|验收)/.test(text)&&nextR&&nextR!==rVersion
|
|
178
195
|
||/(?:方案|计划)/.test(text)&&nextP&&nextP!==pVersion
|
|
179
196
|
||/(?:SUPERSEDED|已失效|已废弃|已撤销)/i.test(text)
|
|
180
197
|
&&/(?:需求|方案|计划|R[1-9][0-9]*|P[1-9][0-9]*)/i.test(text)
|
|
@@ -102,6 +102,49 @@ async function startReadinessEvidence(run){
|
|
|
102
102
|
pageState:tab.url==='https://chatgpt.com/'?'BLANK_HOME':'CHANGED_UNVERIFIED',
|
|
103
103
|
...(result&&typeof result.mainCount==='number'?{readiness:result}:{})};
|
|
104
104
|
}
|
|
105
|
+
// TEST_ONLY is an independent native @ App first-turn, never a managed Owner.
|
|
106
|
+
// A frozen BLOCKED run with a lost Owner tab must not disable ordinary first-
|
|
107
|
+
// turn testing forever. Keep its Native pointer untouched: this read-only
|
|
108
|
+
// gate checks both authorities and denies any live/unknown Owner transition.
|
|
109
|
+
async function entryTestAdmission(message,sender){
|
|
110
|
+
if(!sessionPage(sender,'entry_test',message.requestId))
|
|
111
|
+
return {status:'DENIED',code:'ENTRY_TEST_SOURCE_UNVERIFIED'};
|
|
112
|
+
const disk=await chrome.runtime.sendNativeMessage(SESSION_HOST,
|
|
113
|
+
{op:'session-read'}).catch(()=>null);
|
|
114
|
+
if(disk?.status!=='OK')return {status:'DENIED',code:'ENTRY_TEST_NATIVE_UNVERIFIED'};
|
|
115
|
+
const run=await readRun(),record=disk.session;
|
|
116
|
+
if(!run?.sessionId){
|
|
117
|
+
return !record||record.phase==='DONE'
|
|
118
|
+
?{status:'OK',scope:'TEST_ONLY'}
|
|
119
|
+
:{status:'DENIED',code:'ENTRY_TEST_OWNER_UNVERIFIED'};
|
|
120
|
+
}
|
|
121
|
+
if(!matchesNativeProjection(sessionProjection(run),record))
|
|
122
|
+
return {status:'DENIED',code:'ENTRY_TEST_OWNER_MISMATCH'};
|
|
123
|
+
if(run.phase==='DONE')
|
|
124
|
+
return !run.contextManaged||run.taskId&&terminalFenceVerified(run)
|
|
125
|
+
?{status:'OK',scope:'TEST_ONLY'}
|
|
126
|
+
:{status:'DENIED',code:'ENTRY_TEST_UNFENCED'};
|
|
127
|
+
if(run.phase!=='BLOCKED'||run.contextManaged&&(!run.taskId||!terminalFenceVerified(run))
|
|
128
|
+
||!Number.isSafeInteger(run.tabId)||!pathOf('https://chatgpt.com'+run.page))
|
|
129
|
+
return {status:'DENIED',code:'ENTRY_TEST_ACTIVE_OWNER'};
|
|
130
|
+
// Chrome may reuse the old numeric tab ID. Even a changed tab is not a
|
|
131
|
+
// verified absence. A new tab showing the same Chat is also a live risk.
|
|
132
|
+
if(await chrome.tabs.get(run.tabId).catch(()=>null))
|
|
133
|
+
return {status:'DENIED',code:'ENTRY_TEST_OWNER_TAB_PRESENT'};
|
|
134
|
+
const existing=await chrome.tabs.query({url:'https://chatgpt.com/*'}).catch(()=>null);
|
|
135
|
+
if(!Array.isArray(existing)
|
|
136
|
+
||existing.some(tab=>chatIdOf(tab.url)===chatIdOf('https://chatgpt.com'+run.page)))
|
|
137
|
+
return {status:'DENIED',code:'ENTRY_TEST_OWNER_REOPENED'};
|
|
138
|
+
const again=await readRun();
|
|
139
|
+
const second=await chrome.runtime.sendNativeMessage(SESSION_HOST,
|
|
140
|
+
{op:'session-read'}).catch(()=>null);
|
|
141
|
+
if(!again||JSON.stringify(again)!==JSON.stringify(run)
|
|
142
|
+
||second?.status!=='OK'||!second.session
|
|
143
|
+
||second.session.updatedAt!==record.updatedAt
|
|
144
|
+
||!matchesNativeProjection(sessionProjection(again),second.session))
|
|
145
|
+
return {status:'DENIED',code:'ENTRY_TEST_OWNER_DRIFT'};
|
|
146
|
+
return {status:'OK',scope:'TEST_ONLY',mode:'FROZEN_BLOCKED_NO_OWNER'};
|
|
147
|
+
}
|
|
105
148
|
async function sessionStatus(message,sender){
|
|
106
149
|
if(!sessionPage(sender,'status',message.requestId))
|
|
107
150
|
return {status:'DENIED',code:'INVALID_STATUS_SOURCE'};
|
|
@@ -68,6 +68,7 @@ const SERIAL_ROUTES=new Map([
|
|
|
68
68
|
['CHAT_LOOP_SESSION_START_TAKE_V1',sessionStartTake],
|
|
69
69
|
['CHAT_LOOP_SESSION_START_RESULT_V1',sessionStartResult],
|
|
70
70
|
['CHAT_LOOP_SESSION_STATUS_V1',sessionStatus],
|
|
71
|
+
['CHAT_LOOP_ENTRY_TEST_ADMISSION_V1',entryTestAdmission],
|
|
71
72
|
['CHAT_LOOP_RESOURCE_CHAT_V1',resourceChatGate]
|
|
72
73
|
|
|
73
74
|
]);
|
|
@@ -12,7 +12,7 @@ export function matchExtensionAction(catalog,argv){
|
|
|
12
12
|
&&Number.isSafeInteger(Number(input.at(-1))))
|
|
13
13
|
return {id:cap.id,intent:{tabId:Number(input.at(-1))}};
|
|
14
14
|
if(input.length===route.length&&input.join(' ')===route.join(' '))
|
|
15
|
-
return {id:cap.id,needsIntent:['owner-intent','owner-start'].includes(cap.kind)};
|
|
15
|
+
return {id:cap.id,needsIntent:['owner-intent','owner-start','entry-test'].includes(cap.kind)};
|
|
16
16
|
}
|
|
17
17
|
return null;
|
|
18
18
|
}
|
|
@@ -49,6 +49,28 @@ export function requestDir(id) {
|
|
|
49
49
|
return join(tempRoot(),id);
|
|
50
50
|
}
|
|
51
51
|
function validateIntent(action, intent) {
|
|
52
|
+
if(action==='entry_test'){
|
|
53
|
+
if(!intent||typeof intent!=='object'||Array.isArray(intent)
|
|
54
|
+
||Object.keys(intent).some(k=>!['prompt','appId','testOnly','confirmed','recoverTestAt','recoverExactDraft','verifyChatUrl'].includes(k))
|
|
55
|
+
||typeof intent.prompt!=='string'||!intent.prompt.trim()||intent.prompt.length>4000
|
|
56
|
+
||/[\x00-\x08\x0b\x0c\x0e-\x1f]/.test(intent.prompt)
|
|
57
|
+
||typeof intent.appId!=='string'||!/^asdk_app_[a-z0-9]{20,64}$/.test(intent.appId)
|
|
58
|
+
||intent.testOnly!==true||intent.confirmed!==true
|
|
59
|
+
||(intent.verifyChatUrl!==undefined&&(
|
|
60
|
+
typeof intent.verifyChatUrl!=='string'
|
|
61
|
+
||!/^https:\/\/chatgpt\.com\/c\/[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(intent.verifyChatUrl)
|
|
62
|
+
||intent.recoverTestAt!==undefined||intent.recoverExactDraft!==undefined))
|
|
63
|
+
||(intent.recoverTestAt!==undefined&&intent.recoverTestAt!==true)
|
|
64
|
+
||(intent.recoverExactDraft!==undefined
|
|
65
|
+
&&(typeof intent.recoverExactDraft!=='string'
|
|
66
|
+
||!intent.recoverExactDraft.trim()
|
|
67
|
+
||intent.recoverExactDraft.length>4000)))
|
|
68
|
+
throw Object.assign(Error('Explicit test-only entry intent required'),{code:'INVALID_ENTRY_TEST_INTENT'});
|
|
69
|
+
return {prompt:intent.prompt,appId:intent.appId,testOnly:true,confirmed:true,
|
|
70
|
+
...(intent.recoverTestAt?{recoverTestAt:true}:{}),
|
|
71
|
+
...(intent.recoverExactDraft?{recoverExactDraft:intent.recoverExactDraft}:{}),
|
|
72
|
+
...(intent.verifyChatUrl?{verifyChatUrl:intent.verifyChatUrl}:{})};
|
|
73
|
+
}
|
|
52
74
|
if(action==='start'){
|
|
53
75
|
if(!intent||typeof intent!=='object'||Array.isArray(intent)
|
|
54
76
|
||Object.keys(intent).some(k=>!['projectId','taskId','purpose','prompt','confirmed','replaceBlockedSessionId','mode','chatUrl','contextLeaseRef','contextStoreEpoch','contextTaskRevision','contextApprovalRevision'].includes(k))
|
|
@@ -144,7 +166,7 @@ export function readRequest(id) {
|
|
|
144
166
|
const r=JSON.parse(readFileSync(p,'utf8'));
|
|
145
167
|
if(r.id!==id||!ACTIONS.includes(r.action)||Date.now()>r.expiresAt)
|
|
146
168
|
throw Object.assign(Error('Request expired or changed'),{code:'REQUEST_EXPIRED'});
|
|
147
|
-
if(['continue','handoff','clean','start'].includes(r.action))validateIntent(r.action,r.intent);
|
|
169
|
+
if(['continue','handoff','clean','start','entry_test'].includes(r.action))validateIntent(r.action,r.intent);
|
|
148
170
|
if(r.traceParent!==undefined&&!validParent(r.traceParent))delete r.traceParent;
|
|
149
171
|
return r;
|
|
150
172
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tomflow/chatloop-extension",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.21",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "Chat Loop Extension
|
|
5
|
+
"description": "Chat Loop Extension: reviewed formal Action pages, including TEST_ONLY native App entry",
|
|
6
6
|
"bin": {
|
|
7
7
|
"chatloop-extension": "bin/cli.mjs"
|
|
8
8
|
},
|
|
@@ -41,7 +41,7 @@ export async function compileActions(source=join(root,'capabilities'),
|
|
|
41
41
|
const {capability:c}=await import(pathToFileURL(path).href+'?sha256='+hash);
|
|
42
42
|
if(!c||c.id!==file.slice(0,-4)||
|
|
43
43
|
!/^[a-z][a-z0-9_]*$/.test(c.id)||
|
|
44
|
-
!/^[a-z][a-z0-
|
|
44
|
+
!/^[a-z][a-z0-9_-]*\.html$/.test(c.page)||
|
|
45
45
|
!Array.isArray(c.cli)||!c.cli.length||
|
|
46
46
|
c.cli.some(t=>typeof t!=='string'||!/^[a-z][a-z0-9-]*$/.test(t))||
|
|
47
47
|
!Number.isSafeInteger(c.waitMs)||c.waitMs<1||c.waitMs>310000||
|
|
@@ -64,12 +64,16 @@ export async function compileActions(source=join(root,'capabilities'),
|
|
|
64
64
|
if(c.kind==='eye-read'&&(!c.id.startsWith('chat_')||
|
|
65
65
|
!['text','dom'].includes(c.readMode)))
|
|
66
66
|
throw fail('EXTENSION_EYE_READ_MODE_INVALID');
|
|
67
|
-
|
|
67
|
+
const reviewedEntry=c.id==='entry_test' && c.kind==='entry-test'
|
|
68
|
+
&&c.page==='entry_test.html' &&c.cli.join(' ')==='entry test'
|
|
69
|
+
&&c.waitMs===310000 &&c.textResult===true;
|
|
70
|
+
if(newAction && c.kind!=='eye-read' && !reviewedEntry)
|
|
68
71
|
throw fail('EXTENSION_PRIVILEGED_ACTION_REVIEW_REQUIRED');
|
|
69
72
|
if((c.id==='chat_text'&&c.readMode!=='text')||
|
|
70
73
|
(c.id==='chat_dom'&&c.readMode!=='dom'))
|
|
71
74
|
throw fail('EXTENSION_BUILTIN_EYE_MODE_CHANGED');
|
|
72
75
|
const page=join(extension,c.page);
|
|
76
|
+
if(reviewedEntry&&!existsSync(page))throw fail('EXTENSION_ENTRY_ACTION_PAGE_MISSING');
|
|
73
77
|
const generated=existsSync(page)&&
|
|
74
78
|
readFileSync(page,'utf8').startsWith(generatedMarker);
|
|
75
79
|
if(!existsSync(page) && !newAction)
|
|
@@ -79,7 +83,7 @@ export async function compileActions(source=join(root,'capabilities'),
|
|
|
79
83
|
if(!readFileSync(page,'utf8').includes(expected))
|
|
80
84
|
throw fail('EXTENSION_ACTION_EXECUTOR_MISMATCH');
|
|
81
85
|
}
|
|
82
|
-
actions.push({...c,file,generated:newAction});
|
|
86
|
+
actions.push({...c,file,generated:newAction && c.kind==='eye-read'});
|
|
83
87
|
}
|
|
84
88
|
actions.sort((a,b)=>(
|
|
85
89
|
(originals.indexOf(a.id)<0?99:originals.indexOf(a.id))-
|
|
@@ -18,8 +18,9 @@ The root exposes two data APIs, a shared AOP factory and one opt-in, non-authori
|
|
|
18
18
|
Writer prunes only parseable records older than the configured retention
|
|
19
19
|
window at startup and daily across its active file and bounded rotation
|
|
20
20
|
segments. Unknown/malformed-age lines are preserved; source identity and
|
|
21
|
-
permissions are rechecked before atomic replacement.
|
|
22
|
-
visible in
|
|
21
|
+
permissions are rechecked before atomic replacement. A file with no expired
|
|
22
|
+
records is not rewritten or replaced. Retention results are visible in
|
|
23
|
+
`health().retention`.
|
|
23
24
|
- `createTraceReader({filePath,allowedProjects})`: the Gateway invokes
|
|
24
25
|
`diagnose({projectRef,traceId|sessionRef,maxEvents})`, `apiUsage({windowMinutes,limit})`
|
|
25
26
|
or `health()`. `apiUsage` requires a Reader explicitly scoped to
|
|
@@ -192,6 +192,7 @@ export function makeTraceReader(options,deps){
|
|
|
192
192
|
||!Number.isSafeInteger(limit)||limit<1||limit>200)
|
|
193
193
|
throw fail('TRACE_INVALID_LIMIT');
|
|
194
194
|
const now=Date.now(),since=now-windowMinutes*60000;
|
|
195
|
+
const sinceIso=new Date(since).toISOString();
|
|
195
196
|
const calls=new Map(),seenEvents=new Set();
|
|
196
197
|
const files=scopedFiles();
|
|
197
198
|
let malformed=0;
|
|
@@ -201,6 +202,16 @@ export function makeTraceReader(options,deps){
|
|
|
201
202
|
for await(const line of boundedLines(stream)){
|
|
202
203
|
if(line===null){malformed++;continue}
|
|
203
204
|
if(!line.trim())continue
|
|
205
|
+
// The Writer's canonical v2 JSONL places ISO time first. Skip
|
|
206
|
+
// expired history before JSON.parse/event validation; this is a
|
|
207
|
+
// per-record filter, NOT an early file stop, so out-of-order
|
|
208
|
+
// timestamps and multiple retained segments stay observable.
|
|
209
|
+
// Noncanonical/malformed rows still use the normal read path.
|
|
210
|
+
if(line.startsWith('{"time":"')){
|
|
211
|
+
const stamp=line.slice(9,33);
|
|
212
|
+
if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(stamp)
|
|
213
|
+
&&line[33]==='"'&&stamp<sinceIso)continue;
|
|
214
|
+
}
|
|
204
215
|
let v;try{v=JSON.parse(line)}catch{malformed++;continue}
|
|
205
216
|
// New event families provide their own safe usage projection.
|
|
206
217
|
// A Provider never acquires access to a Project by being registered.
|
|
@@ -23,11 +23,25 @@ function pruneFile(filePath,cutoff,secureFile){
|
|
|
23
23
|
process.getuid&&opened.uid!==process.getuid()||!sameFile(before,opened))
|
|
24
24
|
throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
|
|
25
25
|
{code:'TRACE_RETENTION_SOURCE_CHANGED'});
|
|
26
|
-
temp=filePath+'.retention-'+randomUUID();
|
|
27
|
-
output=openSync(temp,FS.O_WRONLY|FS.O_CREAT|FS.O_EXCL|FS.O_NOFOLLOW,0o600);
|
|
28
26
|
const chunk=Buffer.allocUnsafe(64*1024),newline=Buffer.from([10]);
|
|
29
|
-
let position=0,pending=Buffer.alloc(0),longLine=false;
|
|
27
|
+
let position=0,pending=Buffer.alloc(0),longLine=false,processedBytes=0;
|
|
30
28
|
let droppedRecords=0,droppedBytes=0,keptRecords=0;
|
|
29
|
+
// Do not copy an entire retained log every day if nothing has expired.
|
|
30
|
+
// The first expired record triggers an exact, bounded prefix copy; all
|
|
31
|
+
// earlier bytes remain untouched until then.
|
|
32
|
+
const beginRewrite=()=>{
|
|
33
|
+
if(output!==undefined)return;
|
|
34
|
+
temp=filePath+'.retention-'+randomUUID();
|
|
35
|
+
output=openSync(temp,FS.O_WRONLY|FS.O_CREAT|FS.O_EXCL|FS.O_NOFOLLOW,0o600);
|
|
36
|
+
const copy=Buffer.allocUnsafe(64*1024);
|
|
37
|
+
for(let offset=0;offset<processedBytes;){
|
|
38
|
+
const n=readSync(input,copy,0,Math.min(copy.length,processedBytes-offset),offset);
|
|
39
|
+
if(!n)throw Object.assign(Error('TRACE_RETENTION_READ_INCOMPLETE'),
|
|
40
|
+
{code:'TRACE_RETENTION_READ_INCOMPLETE'});
|
|
41
|
+
writeAll(output,copy.subarray(0,n));
|
|
42
|
+
offset+=n;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
31
45
|
const keepLine=(line,terminated=true)=>{
|
|
32
46
|
let expired=false;
|
|
33
47
|
if(line.length<=8192){
|
|
@@ -37,15 +51,18 @@ function pruneFile(filePath,cutoff,secureFile){
|
|
|
37
51
|
expired=Number.isFinite(timestamp)&×tamp<cutoff;
|
|
38
52
|
}catch{}
|
|
39
53
|
}
|
|
40
|
-
if(expired){
|
|
41
|
-
|
|
54
|
+
if(expired){
|
|
55
|
+
beginRewrite();droppedRecords++;droppedBytes+=line.length+(terminated?1:0);
|
|
56
|
+
}else{
|
|
42
57
|
// An unterminated, possibly torn final record is historical evidence.
|
|
43
|
-
// Retention
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
58
|
+
// Retention must never invent an absent final LF.
|
|
59
|
+
if(output!==undefined){
|
|
60
|
+
writeAll(output,line);
|
|
61
|
+
if(terminated)writeAll(output,newline);
|
|
62
|
+
}
|
|
47
63
|
keptRecords++;
|
|
48
64
|
}
|
|
65
|
+
processedBytes+=line.length+(terminated?1:0);
|
|
49
66
|
};
|
|
50
67
|
while(position<before.size){
|
|
51
68
|
const count=readSync(input,chunk,0,Math.min(chunk.length,before.size-position),position);
|
|
@@ -57,22 +74,26 @@ function pruneFile(filePath,cutoff,secureFile){
|
|
|
57
74
|
const end=chunk.indexOf(10,start);
|
|
58
75
|
if(longLine){
|
|
59
76
|
const next=end<0?count:end+1;
|
|
60
|
-
writeAll(output,chunk.subarray(start,next));
|
|
77
|
+
if(output!==undefined)writeAll(output,chunk.subarray(start,next));
|
|
78
|
+
processedBytes+=next-start;
|
|
61
79
|
if(end<0){start=count;continue;}
|
|
62
80
|
longLine=false;start=next;continue;
|
|
63
81
|
}
|
|
64
82
|
if(end<0){
|
|
65
83
|
const part=chunk.subarray(start,count);
|
|
66
84
|
if(pending.length+part.length>8192){
|
|
67
|
-
writeAll(output,pending);writeAll(output,part);
|
|
85
|
+
if(output!==undefined){writeAll(output,pending);writeAll(output,part);}
|
|
86
|
+
processedBytes+=pending.length+part.length;
|
|
68
87
|
pending=Buffer.alloc(0);longLine=true;keptRecords++;
|
|
69
88
|
}else pending=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
|
|
70
89
|
start=count;continue;
|
|
71
90
|
}
|
|
72
91
|
const part=chunk.subarray(start,end);
|
|
73
92
|
const line=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
|
|
74
|
-
if(line.length>8192){
|
|
75
|
-
|
|
93
|
+
if(line.length>8192){
|
|
94
|
+
if(output!==undefined){writeAll(output,line);writeAll(output,newline);}
|
|
95
|
+
processedBytes+=line.length+1;keptRecords++;
|
|
96
|
+
}else keepLine(line);
|
|
76
97
|
pending=Buffer.alloc(0);start=end+1;
|
|
77
98
|
}
|
|
78
99
|
}
|
|
@@ -83,10 +104,7 @@ function pruneFile(filePath,cutoff,secureFile){
|
|
|
83
104
|
if(!sameFile(before,after)||!sameFile(before,current))
|
|
84
105
|
throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
|
|
85
106
|
{code:'TRACE_RETENTION_SOURCE_CHANGED'});
|
|
86
|
-
if(!droppedRecords){
|
|
87
|
-
closeSync(output);output=undefined;unlinkSync(temp);temp=null;
|
|
88
|
-
return {droppedRecords,droppedBytes,pruned:false};
|
|
89
|
-
}
|
|
107
|
+
if(!droppedRecords)return {droppedRecords,droppedBytes,pruned:false};
|
|
90
108
|
fsyncSync(output);closeSync(output);output=undefined;
|
|
91
109
|
closeSync(input);
|
|
92
110
|
if(!keptRecords){unlinkSync(filePath);unlinkSync(temp);temp=null;}
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.9.
|
|
6
|
+
"version": "0.9.50",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
|
|
9
9
|
"bin": {
|
|
@@ -33,17 +33,17 @@
|
|
|
33
33
|
"prepack": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check && node ./scripts/build-document-app.mjs --check"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@tomflow/chatloop-context": "0.6.
|
|
36
|
+
"@tomflow/chatloop-context": "0.6.15",
|
|
37
37
|
"@tomflow/chatloop-trace": "0.4.6",
|
|
38
38
|
"@wonderwhy-er/desktop-commander": "0.2.44",
|
|
39
|
-
"
|
|
40
|
-
"
|
|
39
|
+
"ps-list": "9.0.0",
|
|
40
|
+
"@tomflow/chatloop-extension": "0.4.21"
|
|
41
41
|
},
|
|
42
42
|
"bundleDependencies": [
|
|
43
43
|
"@tomflow/chatloop-context",
|
|
44
44
|
"@tomflow/chatloop-trace",
|
|
45
|
-
"
|
|
46
|
-
"
|
|
45
|
+
"ps-list",
|
|
46
|
+
"@tomflow/chatloop-extension"
|
|
47
47
|
],
|
|
48
48
|
"engines": {
|
|
49
49
|
"node": ">=24"
|
package/providers/extension.mjs
CHANGED
|
@@ -20,7 +20,7 @@ const endpoints=[
|
|
|
20
20
|
[['extension','reload'],extensionTool('reload','Request reload of Chat Loop Extension; final health is unverified.',false)],
|
|
21
21
|
[['extension','status'],extensionTool('status','Read the unique current Mac Chrome Web Chat Owner; never starts or sends.',true)],
|
|
22
22
|
[['extension','start'],extensionTool('start',
|
|
23
|
-
'
|
|
23
|
+
'Controlled execution ONLY: in Stage 03, mode=adopt binds the browser-verified R/P-approved original Chat without resending. The prompt-based branch creates a machine-owned execution session and requires the model status protocol; it is NOT a native @ Chat Loop user entry or Stage 01/02 testing mechanism. For TEST_ONLY native @ App entry, use the separate Extension entry test action, not Start.',false,
|
|
24
24
|
{projectId:{type:'string',minLength:1,maxLength:128,pattern:PROJECT_ID.source},
|
|
25
25
|
taskId:{type:'string',minLength:1,maxLength:128,pattern:PROJECT_ID.source},
|
|
26
26
|
purpose:{type:'string',enum:['REPAIR_SAME_SCOPE']},
|