@tomflow/chatloop-tools 0.9.64 → 0.9.70
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/node_modules/@tomflow/chatloop-context/README.md +296 -0
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +290 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
- package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +261 -0
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
- package/node_modules/@tomflow/chatloop-context/index.mjs +238 -0
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +77 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +286 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +180 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
- package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
- package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
- package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
- package/node_modules/@tomflow/chatloop-context/package.json +38 -0
- package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
- package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
- package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
- package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
- package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
- package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
- package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
- package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
- package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
- package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
- package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
- package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
- package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
- package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
- package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
- package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +228 -0
- package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
- package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
- package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
- package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
- package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
- package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
- package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
- package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
- package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
- package/node_modules/ps-list/index.d.ts +76 -0
- package/node_modules/ps-list/index.js +366 -0
- package/node_modules/ps-list/license +9 -0
- package/node_modules/ps-list/package.json +44 -0
- package/node_modules/ps-list/readme.md +56 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
- package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
- package/package.json +12 -4
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Chrome Native Messaging: one request per process, no persistent server.
|
|
3
|
+
import {nativeHostApi} from '../index.mjs';
|
|
4
|
+
// Chrome owns this one-shot Native process. Never inherit a shell/CLI trace
|
|
5
|
+
// parent; only the verified private Action request can establish its parent.
|
|
6
|
+
delete process.env.CHAT_LOOP_API_PARENT;
|
|
7
|
+
const hostContract=nativeHostApi();
|
|
8
|
+
const {readRequest,finish,readSession,writeSession,registeredContext,
|
|
9
|
+
handleScopedNativeMessage,nativeContextControl,
|
|
10
|
+
nativeApiObservation,observeNativeOperation}=hostContract;
|
|
11
|
+
const MAX_INPUT=48*1024*1024;
|
|
12
|
+
let replied=false;
|
|
13
|
+
const write=obj=>{
|
|
14
|
+
// One Native Messaging process may return exactly one business frame.
|
|
15
|
+
// A later observer/drain failure must not append a contradictory result.
|
|
16
|
+
if(replied)return;
|
|
17
|
+
const b=Buffer.from(JSON.stringify(obj)),len=Buffer.alloc(4);
|
|
18
|
+
len.writeUInt32LE(b.length);
|
|
19
|
+
replied=true;
|
|
20
|
+
process.stdout.write(Buffer.concat([len,b]));
|
|
21
|
+
};
|
|
22
|
+
let buf=Buffer.alloc(0),handled=false,observationOnly=false;
|
|
23
|
+
process.stdin.on('data',async chunk=>{
|
|
24
|
+
if(handled)return;
|
|
25
|
+
// Bound accumulated bytes before Buffer.concat allocates. A claimed small
|
|
26
|
+
// frame length cannot justify unbounded piped input or retained memory.
|
|
27
|
+
if(buf.length+chunk.length>MAX_INPUT+4){
|
|
28
|
+
handled=true;write({status:'FAILED',code:'MESSAGE_TOO_LARGE'});return;
|
|
29
|
+
}
|
|
30
|
+
buf=Buffer.concat([buf,chunk]);
|
|
31
|
+
if(buf.length<4)return;
|
|
32
|
+
const n=buf.readUInt32LE();
|
|
33
|
+
if(n>MAX_INPUT){handled=true;write({status:'FAILED',code:'MESSAGE_TOO_LARGE'});return;}
|
|
34
|
+
if(buf.length<4+n)return;
|
|
35
|
+
handled=true;
|
|
36
|
+
try{
|
|
37
|
+
const m=JSON.parse(buf.subarray(4,4+n).toString('utf8'));
|
|
38
|
+
observationOnly=m.op==='api-observation';
|
|
39
|
+
const dispatch=async()=>{
|
|
40
|
+
if(m.op==='acquire'){
|
|
41
|
+
const r=readRequest(m.id);
|
|
42
|
+
if(r.action!==m.action)throw Object.assign(Error('Action mismatch'),{code:'REQUEST_MISMATCH'});
|
|
43
|
+
write({status:'OK',id:r.id,action:r.action,nonce:r.nonce,
|
|
44
|
+
...(r.traceParent?{traceParent:r.traceParent}:{}),
|
|
45
|
+
...(r.intent ? {intent:r.intent} : {})});
|
|
46
|
+
}else if(m.op==='complete'){
|
|
47
|
+
const r=finish(m);
|
|
48
|
+
write({status:'SAVED',id:r.id,action:r.action,bytes:r.bytes});
|
|
49
|
+
}else if(m.op==='session-read'){
|
|
50
|
+
const session=readSession();let projectContext=null,contextStatus='MISSING';
|
|
51
|
+
try{projectContext=session?registeredContext(session.projectId):null;
|
|
52
|
+
if(projectContext)contextStatus='VERIFIED';}catch{contextStatus='UNVERIFIED';}
|
|
53
|
+
write({status:'OK',session,contextStatus,...(projectContext?{projectContext}:{})});
|
|
54
|
+
}else if(['session-read-v2','session-sync-v2','session-snapshot-v2',
|
|
55
|
+
'context-status-v2','context-writer-check-v2',
|
|
56
|
+
'context-control-v2','continue-permit-v2',
|
|
57
|
+
'continue-reconcile-v2','continue-send-check-v2',
|
|
58
|
+
'continue-result-v2','continue-result-read-v2',
|
|
59
|
+
'handoff-permit-v2','handoff-send-check-v2',
|
|
60
|
+
'handoff-abort-fence-v2',
|
|
61
|
+
'handoff-abort-fence-read-v2','handoff-result-v2',
|
|
62
|
+
'handoff-result-read-v2','task-terminal-v2',
|
|
63
|
+
'task-terminal-read-v2','task-cancel-v2',
|
|
64
|
+
'task-cancel-read-v2','task-retire-v2',
|
|
65
|
+
'task-recover-handoff-v2','task-recover-read-v2',
|
|
66
|
+
'task-recover-finalize-v2'].includes(m.op)){
|
|
67
|
+
write(await handleScopedNativeMessage(m));
|
|
68
|
+
}else if(m.op==='context-control'){
|
|
69
|
+
// Only Chrome Native Messaging can initiate this command. The Native
|
|
70
|
+
// session pointer must already be synchronized by the unique Worker.
|
|
71
|
+
const session=readSession();
|
|
72
|
+
if(!session?.taskId||!session.sessionId)
|
|
73
|
+
throw Object.assign(Error('No Context-managed session'),{code:'CONTEXT_SESSION_UNBOUND'});
|
|
74
|
+
if(!['permit.consume','run.bind.initial','run.fence','run.bind.handoff',
|
|
75
|
+
'run.restore-same-owner','run.fence.terminal','run.credential.rotate',
|
|
76
|
+
'run.fence.cancel',
|
|
77
|
+
'run.terminalStatus','run.reopenStatus','run.snapshot'].includes(m.command)
|
|
78
|
+
||!m.args||typeof m.args!=='object'||Array.isArray(m.args))
|
|
79
|
+
throw Object.assign(Error('Invalid Context command'),{code:'CONTEXT_COMMAND_INVALID'});
|
|
80
|
+
if(m.command==='run.fence.cancel'){
|
|
81
|
+
const request=readRequest(m.args.actionToken);
|
|
82
|
+
const intent=request?.intent;
|
|
83
|
+
if(request?.action!=='session'||intent?.operation!=='cancel'
|
|
84
|
+
||intent.confirmed!==true||intent.sessionId!==session.sessionId
|
|
85
|
+
||intent.projectId!==session.projectId
|
|
86
|
+
||intent.taskId!==session.taskId
|
|
87
|
+
||intent.generation!==session.generation
|
|
88
|
+
||intent.contextStoreEpoch!==m.args.expectedStoreEpoch
|
|
89
|
+
||intent.expectedTaskRevision!==m.args.expectedTaskRevision
|
|
90
|
+
||intent.expectedBindingRevision!==m.args.expectedBindingRevision)
|
|
91
|
+
throw Object.assign(Error('Cancel authorization not verified'),
|
|
92
|
+
{code:'SESSION_CANCEL_SOURCE_UNVERIFIED'});
|
|
93
|
+
}
|
|
94
|
+
const own=new Set(['projectId','taskId','sessionId','generation','activeChatId',
|
|
95
|
+
'role','principal','internalAuthorized','ownerCommitted','nativeCommitted',
|
|
96
|
+
'sourceRunRef','oldActionTokenRevoked','workerRestored','nativeRestored','ownerStillSame']);
|
|
97
|
+
if(Object.keys(m.args).some(k=>own.has(k)))
|
|
98
|
+
throw Object.assign(Error('Reserved Context identity field'),{code:'CONTEXT_IDENTITY_FORBIDDEN'});
|
|
99
|
+
const args={...m.args,projectId:session.projectId,taskId:session.taskId,
|
|
100
|
+
sessionId:session.sessionId,generation:session.generation,
|
|
101
|
+
activeChatId:session.activeChatId};
|
|
102
|
+
if(m.command==='run.bind.initial'||m.command==='run.bind.handoff')
|
|
103
|
+
args.runRef=session.sessionId+':'+session.taskId+':'+session.generation;
|
|
104
|
+
if(['run.fence','run.fence.terminal','run.credential.rotate',
|
|
105
|
+
'run.fence.cancel'].includes(m.command))
|
|
106
|
+
args.runRef=session.sessionId+':'+session.taskId+':'+session.generation;
|
|
107
|
+
const result=await nativeContextControl(m.command,args);
|
|
108
|
+
write({status:'OK',result});
|
|
109
|
+
}else if(m.op==='api-observation'){
|
|
110
|
+
// Separate request. Observations never delay a business Native reply.
|
|
111
|
+
const recorded=await nativeApiObservation(m.record);
|
|
112
|
+
write({status:recorded?'RECORDED':'DROPPED'});
|
|
113
|
+
}else if(m.op==='session-sync'){
|
|
114
|
+
// An idle cancellation may become terminal only after the original
|
|
115
|
+
// Context writer has been transactionally fenced. Native is the
|
|
116
|
+
// independent boundary: Worker cannot make a canceled owner by writing
|
|
117
|
+
// a plausible phase or by replaying a URL parameter.
|
|
118
|
+
if(m.session?.phase==='CANCELLED'){
|
|
119
|
+
const request=readRequest(m.cancelRequestId);
|
|
120
|
+
const intent=request?.intent;
|
|
121
|
+
if(request?.action!=='session'||intent?.operation!=='cancel'
|
|
122
|
+
||intent.confirmed!==true||intent.sessionId!==m.session.sessionId
|
|
123
|
+
||intent.projectId!==m.session.projectId
|
|
124
|
+
||intent.taskId!==m.session.taskId
|
|
125
|
+
||intent.generation!==m.session.generation)
|
|
126
|
+
throw Object.assign(Error('Cancel source not verified'),
|
|
127
|
+
{code:'SESSION_CANCEL_SOURCE_UNVERIFIED'});
|
|
128
|
+
const old=readSession();
|
|
129
|
+
if(!old||old.phase!=='BLOCKED'||!old.taskId
|
|
130
|
+
||old.sessionId!==m.session.sessionId
|
|
131
|
+
||old.projectId!==m.session.projectId
|
|
132
|
+
||old.generation!==m.session.generation
|
|
133
|
+
||old.updatedAt!==m.cancelBlockedUpdatedAt)
|
|
134
|
+
throw Object.assign(Error('Cancel Native CAS failed'),
|
|
135
|
+
{code:'SESSION_CANCEL_CAS_MISMATCH'});
|
|
136
|
+
const terminal=await nativeContextControl('run.terminalStatus',{
|
|
137
|
+
projectId:old.projectId,taskId:old.taskId,sessionId:old.sessionId,
|
|
138
|
+
generation:old.generation,activeChatId:old.activeChatId});
|
|
139
|
+
const cancelled=terminal?.sessionCancellation;
|
|
140
|
+
if(terminal?.runRef!==null||terminal?.executionOutcome!==null
|
|
141
|
+
||cancelled?.status!=='CANCELLED_NOT_DELIVERED'
|
|
142
|
+
||cancelled.requestId!=='cancel-'+m.cancelRequestId
|
|
143
|
+
||cancelled?.sessionId!==old.sessionId
|
|
144
|
+
||cancelled?.generation!==old.generation
|
|
145
|
+
||cancelled?.oldRunRef!==old.sessionId+':'+old.taskId+':'+old.generation)
|
|
146
|
+
throw Object.assign(Error('Context cancellation not fenced'),
|
|
147
|
+
{code:'CONTEXT_CANCEL_FENCE_UNVERIFIED'});
|
|
148
|
+
}else if(m.session?.phase==='BLOCKED'
|
|
149
|
+
&&m.cancelFreezeExpectedAt!==undefined){
|
|
150
|
+
const req=readRequest(m.cancelRequestId),intent=req?.intent;
|
|
151
|
+
const old=readSession();
|
|
152
|
+
if(req?.action!=='session'||intent?.operation!=='cancel'
|
|
153
|
+
||intent.confirmed!==true||!old
|
|
154
|
+
||old.phase!=='WAITING_REPLY'
|
|
155
|
+
||old.sessionId!==m.session.sessionId
|
|
156
|
+
||old.projectId!==m.session.projectId
|
|
157
|
+
||old.taskId!==m.session.taskId
|
|
158
|
+
||old.generation!==m.session.generation
|
|
159
|
+
||old.activeChatId!==m.session.activeChatId
|
|
160
|
+
||old.activeChatUrl!==m.session.activeChatUrl
|
|
161
|
+
||intent.sessionId!==old.sessionId
|
|
162
|
+
||intent.projectId!==old.projectId
|
|
163
|
+
||intent.taskId!==old.taskId
|
|
164
|
+
||intent.generation!==old.generation
|
|
165
|
+
||intent.expectedNativeUpdatedAt!==m.cancelFreezeExpectedAt
|
|
166
|
+
||old.updatedAt!==m.cancelFreezeExpectedAt)
|
|
167
|
+
throw Object.assign(Error('Invalid cancellation freeze'),
|
|
168
|
+
{code:'SESSION_CANCEL_FREEZE_CAS_MISMATCH'});
|
|
169
|
+
}else if(Object.hasOwn(m,'cancelBlockedUpdatedAt')
|
|
170
|
+
||Object.hasOwn(m,'cancelFreezeExpectedAt')
|
|
171
|
+
||Object.hasOwn(m,'cancelRequestId'))
|
|
172
|
+
throw Object.assign(Error('Invalid cancel transition'),
|
|
173
|
+
{code:'SESSION_CANCEL_CAS_MISMATCH'});
|
|
174
|
+
write({status:'OK',session:writeSession(m.session,
|
|
175
|
+
m.replaceBlockedSessionId,m.resumeBlockedSessionId,
|
|
176
|
+
m.resumeBlockedUpdatedAt??null,m.sameTaskPrePermitUpdatedAt??null,
|
|
177
|
+
m.cancelBlockedUpdatedAt??null,
|
|
178
|
+
m.cancelFreezeExpectedAt??null)});
|
|
179
|
+
}else throw Object.assign(Error('Unknown operation'),{code:'INVALID_OPERATION'});
|
|
180
|
+
};
|
|
181
|
+
// The telemetry operation is intentionally excluded from self-recording.
|
|
182
|
+
// Recording it here would recursively spawn more Native log requests.
|
|
183
|
+
if(m.op==='api-observation')await dispatch();
|
|
184
|
+
else {
|
|
185
|
+
// Only a private CLI request is allowed to anchor a Native child span.
|
|
186
|
+
// A browser-supplied ID is never treated as authorization or receipt.
|
|
187
|
+
let parent=null;
|
|
188
|
+
try{
|
|
189
|
+
if(['acquire','complete'].includes(m.op)){
|
|
190
|
+
const record=readRequest(m.id);
|
|
191
|
+
if(record.action===m.action)parent=record.traceParent||null;
|
|
192
|
+
}else if(m.op==='session-read'&&m.sourceRequestId){
|
|
193
|
+
const record=readRequest(m.sourceRequestId);
|
|
194
|
+
const p=m.traceParent;
|
|
195
|
+
if(record.action==='status'&&record.traceParent&&p&&
|
|
196
|
+
record.traceParent.traceId===p.traceId)parent=p;
|
|
197
|
+
}else{
|
|
198
|
+
// Read the exact signed source to JOIN audit spans only. V2
|
|
199
|
+
// Continue/Handoff/Status/Cancel cannot inherit a Start parent,
|
|
200
|
+
// nor can an unrelated request forge the original Task trace.
|
|
201
|
+
// This mapping is observation-only; it grants no Owner/Permit.
|
|
202
|
+
const sourced={
|
|
203
|
+
'session-read-v2':'start','session-sync-v2':'start',
|
|
204
|
+
'context-control-v2':'start','context-status-v2':'status',
|
|
205
|
+
'continue-permit-v2':'continue','continue-reconcile-v2':'continue',
|
|
206
|
+
'continue-send-check-v2':'continue',
|
|
207
|
+
'continue-result-v2':'continue','continue-result-read-v2':'continue',
|
|
208
|
+
'handoff-permit-v2':'handoff','handoff-send-check-v2':'handoff',
|
|
209
|
+
'handoff-abort-fence-v2':'handoff',
|
|
210
|
+
'handoff-abort-fence-read-v2':'handoff',
|
|
211
|
+
'handoff-result-v2':'handoff','handoff-result-read-v2':'handoff',
|
|
212
|
+
'task-cancel-v2':'session','task-cancel-read-v2':'session',
|
|
213
|
+
'task-recover-handoff-v2':'session','task-recover-read-v2':'session',
|
|
214
|
+
'task-recover-finalize-v2':'session'
|
|
215
|
+
}[m.op];
|
|
216
|
+
if(sourced&&m.sourceRequestId){
|
|
217
|
+
const record=readRequest(m.sourceRequestId);
|
|
218
|
+
if(record.action===sourced&&record.traceParent)
|
|
219
|
+
parent=record.traceParent;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}catch{/* Non-authoritative parent cannot modify Native business outcome. */}
|
|
223
|
+
await observeNativeOperation(m.op,dispatch,parent);
|
|
224
|
+
}
|
|
225
|
+
}catch(e){
|
|
226
|
+
const code=typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
|
|
227
|
+
?e.code:'NATIVE_HOST_ERROR';
|
|
228
|
+
write({status:'FAILED',code});
|
|
229
|
+
}
|
|
230
|
+
finally{
|
|
231
|
+
// Observation-only requests cannot recursively generate Native audit.
|
|
232
|
+
// Never delay their Writer receipt for an unrelated drain timeout.
|
|
233
|
+
if(!observationOnly){
|
|
234
|
+
try{
|
|
235
|
+
const audit=await hostContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(4200);
|
|
236
|
+
if(audit?.status!=='OK'){
|
|
237
|
+
// Never expose audit internals or change an already-written reply.
|
|
238
|
+
process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
|
|
239
|
+
component:'extension.native',...audit})+'\n');
|
|
240
|
+
}
|
|
241
|
+
}catch{
|
|
242
|
+
// A logging failure must not reject this one-shot Native handler.
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'chat_dom',page:'dom.html',cli:['chat', 'dom'],kind:'eye-read',waitMs:27000,textResult:true,readMode:'dom',description:'Read verified owner chat DOM'});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'chat_screenshot',page:'screenshot.html',cli:['chat', 'screenshot'],kind:'eye-screenshot',waitMs:27000,textResult:false,description:'Capture verified owner screenshot'});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'chat_text',page:'text.html',cli:['chat', 'text'],kind:'eye-read',waitMs:27000,textResult:true,readMode:'text',description:'Read verified owner chat text'});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'clean',page:'clean.html',cli:['clean'],kind:'owner-clean',waitMs:27000,textResult:true,description:'Clean exact composer without sending'});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'continue',page:'continue.html',cli:['continue'],kind:'owner-intent',waitMs:27000,textResult:true,description:'Queue Continue intent'});
|
|
@@ -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 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'handoff',page:'handoff.html',cli:['handoff'],kind:'owner-intent',waitMs:27000,textResult:true,description:'Queue Handoff intent'});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'reload',page:'reload.html',cli:['reload'],kind:'eye-reload',waitMs:27000,textResult:false,description:'Request extension reload, unverified'});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'session',page:'session.html',cli:['session'],kind:'owner-session',waitMs:90000,textResult:true,description:'Exact Owner lifecycle operation (cancel idle Adopt or recover proven unsent Handoff)'});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'start',page:'start.html',cli:['start'],kind:'owner-start',waitMs:310000,textResult:true,description:'Start or adopt approved Chat'});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const capability=Object.freeze({id:'status',page:'status.html',cli:['status'],kind:'owner-status',waitMs:27000,textResult:true,description:'Read unique browser Owner'});
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// Standalone Clean Action: one verified composer only. No sends, Owner mutations or tab closures.
|
|
2
|
+
const statusNode=document.getElementById('status');
|
|
3
|
+
const detailNode=document.getElementById('details');
|
|
4
|
+
const show=(status,detail)=>{statusNode.textContent=status;detailNode.textContent=detail;
|
|
5
|
+
document.body.dataset.result=status==='SUCCESS'?'success':status==='BLOCKED'?'error':'running';};
|
|
6
|
+
const isChat=url=>{try{const u=new URL(url);return u.origin==='https://chatgpt.com'
|
|
7
|
+
&& (u.pathname==='/'||/^\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i.test(u.pathname));}
|
|
8
|
+
catch{return false;}};
|
|
9
|
+
const runKey='chat-loop.action.run.v1';
|
|
10
|
+
function targetAuthorized(tab,run,machine,own){
|
|
11
|
+
if(!isChat(tab?.url) || !Number.isSafeInteger(tab?.id))throw Error('CLEAN_TARGET_NOT_CHATGPT');
|
|
12
|
+
if(tab.id===own.id)throw Error('CLEAN_SELF_TARGET');
|
|
13
|
+
if(machine){
|
|
14
|
+
const owner=run?.tabId===tab.id && tab.url==='https://chatgpt.com'+run?.page;
|
|
15
|
+
// This exact unconfirmed START home has no Chat Owner yet. The machine
|
|
16
|
+
// may clear its composer only after a terminal readiness failure.
|
|
17
|
+
const failedStartHome=run?.phase==='BLOCKED'&&run.action==='START'
|
|
18
|
+
&&run.attemptedNewTabId===tab.id&&tab.url==='https://chatgpt.com/'
|
|
19
|
+
&&['NEW_CHAT_NOT_READY','START_COMPOSER_NOT_EMPTY']
|
|
20
|
+
.includes(run.lastStartFailureCode);
|
|
21
|
+
if(!owner&&!failedStartHome)throw Error('CLEAN_MACHINE_TARGET_NOT_OWNED');
|
|
22
|
+
if(run && !['DONE','BLOCKED'].includes(run.phase))
|
|
23
|
+
throw Error('CLEAN_ACTIVE_LOOP_DENIED');
|
|
24
|
+
}else{
|
|
25
|
+
if(tab.windowId!==own.windowId)throw Error('CLEAN_WINDOW_CHANGED');
|
|
26
|
+
if(run?.tabId===tab.id&&!['DONE','BLOCKED'].includes(run.phase))
|
|
27
|
+
throw Error('CLEAN_ACTIVE_LOOP_DENIED');
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
async function clear(target,machine){
|
|
31
|
+
const [proof]=await chrome.scripting.executeScript({target:{tabId:target.id},
|
|
32
|
+
func:async expected=>{
|
|
33
|
+
try{
|
|
34
|
+
if(location.origin!=='https://chatgpt.com'||location.href!==expected.url)
|
|
35
|
+
return {status:'TARGET_CHANGED'};
|
|
36
|
+
const visible=node=>!!node?.getClientRects?.().length
|
|
37
|
+
&& getComputedStyle(node).display!=='none';
|
|
38
|
+
const main=[...document.querySelectorAll('main')].filter(visible);
|
|
39
|
+
if(main.length!==1)return {status:'MAIN_UNVERIFIED'};
|
|
40
|
+
const inputs=[...document.querySelectorAll(
|
|
41
|
+
'[contenteditable="true"][data-composer-markdown],#prompt-textarea[contenteditable="true"]')]
|
|
42
|
+
.filter(visible);
|
|
43
|
+
const unique=[...new Set(inputs)];
|
|
44
|
+
if(unique.length!==1)return {status:'COMPOSER_UNVERIFIED'};
|
|
45
|
+
const input=unique[0];
|
|
46
|
+
if(input.closest('[aria-disabled="true"]')
|
|
47
|
+
|| [...document.querySelectorAll(
|
|
48
|
+
'[data-testid*="attachment-preview"],[data-testid*="image-preview"],[data-testid="composer-attachment"]')]
|
|
49
|
+
.some(visible))return {status:'COMPOSER_HAS_ATTACHMENTS'};
|
|
50
|
+
if([...document.querySelectorAll(
|
|
51
|
+
'button[data-testid="stop-button"],button[aria-label="Stop generating"],button[aria-label="停止响应"]')]
|
|
52
|
+
.some(visible))return {status:'TURN_STILL_RUNNING'};
|
|
53
|
+
const before=(input.innerText||input.textContent||'').trim();
|
|
54
|
+
if(before){
|
|
55
|
+
input.focus();
|
|
56
|
+
const range=document.createRange();
|
|
57
|
+
range.selectNodeContents(input);
|
|
58
|
+
const selection=window.getSelection();
|
|
59
|
+
selection.removeAllRanges();selection.addRange(range);
|
|
60
|
+
if(!document.execCommand('delete',false))return {status:'DELETE_REJECTED'};
|
|
61
|
+
}
|
|
62
|
+
await new Promise(resolve=>setTimeout(resolve,400));
|
|
63
|
+
if(location.href!==expected.url)return {status:'TARGET_CHANGED'};
|
|
64
|
+
const remaining=(input.innerText||input.textContent||'').trim();
|
|
65
|
+
if(remaining)return {status:'CLEAN_NOT_CONFIRMED'};
|
|
66
|
+
return {status:'CLEARED',hadDraft:!!before};
|
|
67
|
+
}catch{return {status:'CLEAN_UNVERIFIED'};}
|
|
68
|
+
},args:[{url:target.url,machine}]});
|
|
69
|
+
if(proof?.result?.status!=='CLEARED')throw Error(proof?.result?.status||'CLEAN_UNVERIFIED');
|
|
70
|
+
const live=await chrome.tabs.get(target.id);
|
|
71
|
+
if(!live||live.url!==target.url)throw Error('CLEAN_TARGET_CHANGED_AFTER');
|
|
72
|
+
return {status:'CLEARED',action:'clean',tabId:target.id,hadDraft:proof.result.hadDraft===true};
|
|
73
|
+
}
|
|
74
|
+
async function run(){
|
|
75
|
+
const params=new URLSearchParams(location.search);
|
|
76
|
+
const own=await chrome.tabs.getCurrent();
|
|
77
|
+
if(!own?.id||own.url!==location.href)throw Error('CLEAN_ACTION_TAB_UNVERIFIED');
|
|
78
|
+
const reqId=params.get('requestId');
|
|
79
|
+
const machine=reqId!==null;
|
|
80
|
+
if(machine?([ ...params.keys()].length!==1||!/^[a-f0-9]{32}$/.test(reqId)):
|
|
81
|
+
([...params.keys()].length!==1||!/^[1-9][0-9]*$/.test(params.get('tabId')||'')))
|
|
82
|
+
throw Error('CLEAN_PARAMETERS_INVALID');
|
|
83
|
+
const host='com.tomflow.chatloop.extension', action='clean';
|
|
84
|
+
let receipt,tabId;
|
|
85
|
+
if(machine){
|
|
86
|
+
receipt=await chrome.runtime.sendNativeMessage(host,{op:'acquire',id:reqId,action});
|
|
87
|
+
if(receipt?.status!=='OK'||receipt.id!==reqId||receipt.action!==action
|
|
88
|
+
||typeof receipt.nonce!=='string'||!Number.isSafeInteger(receipt.intent?.tabId))
|
|
89
|
+
throw Error(receipt?.code||'CLEAN_REQUEST_UNVERIFIED');
|
|
90
|
+
tabId=receipt.intent.tabId;
|
|
91
|
+
}else tabId=Number(params.get('tabId'));
|
|
92
|
+
try{
|
|
93
|
+
const tab=await chrome.tabs.get(tabId);
|
|
94
|
+
const state=await chrome.storage.local.get(runKey);
|
|
95
|
+
targetAuthorized(tab,state[runKey],machine,own);
|
|
96
|
+
show('RUNNING','已确认单个目标,清理其未发送文本。');
|
|
97
|
+
const result=await clear(tab,machine);
|
|
98
|
+
if(machine){
|
|
99
|
+
const saved=await chrome.runtime.sendNativeMessage(host,{
|
|
100
|
+
op:'complete',id:reqId,nonce:receipt.nonce,action,status:'OK',
|
|
101
|
+
payload:JSON.stringify(result)});
|
|
102
|
+
if(saved?.status!=='SAVED'||saved.id!==reqId)throw Error('CLEAN_RECEIPT_UNVERIFIED');
|
|
103
|
+
}
|
|
104
|
+
show('SUCCESS','仅清空输入框;未发送消息或修改 Chat Owner。');
|
|
105
|
+
await chrome.tabs.remove(own.id);
|
|
106
|
+
}catch(e){
|
|
107
|
+
if(machine&&receipt?.nonce){
|
|
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';
|
|
112
|
+
const saved=await chrome.runtime.sendNativeMessage(host,{
|
|
113
|
+
op:'complete',id:reqId,nonce:receipt.nonce,action,status:'FAILED',code});
|
|
114
|
+
if(saved?.status==='SAVED'&&saved.id===reqId){
|
|
115
|
+
await chrome.tabs.remove(own.id).catch(()=>{});
|
|
116
|
+
}
|
|
117
|
+
}catch{}
|
|
118
|
+
}
|
|
119
|
+
throw e;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
run().catch(e=>show('BLOCKED',
|
|
123
|
+
/^[A-Z][A-Z0-9_]{1,95}$/.test(e?.message||'')?e.message:'CLEAN_FAILED'));
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Shared Eye Action primitives only. No action is dispatched or executed here.
|
|
2
|
+
(() => {
|
|
3
|
+
const CONTRACT = "chat-loop.eye.v1";
|
|
4
|
+
const params = new URLSearchParams(location.search);
|
|
5
|
+
const statusNode = document.getElementById("status");
|
|
6
|
+
const detailsNode = document.getElementById("details");
|
|
7
|
+
function show(status, message) {
|
|
8
|
+
statusNode.textContent = status;
|
|
9
|
+
detailsNode.textContent = message;
|
|
10
|
+
}
|
|
11
|
+
function fail(code, message) {
|
|
12
|
+
show(code, message);
|
|
13
|
+
document.body.dataset.result = "error";
|
|
14
|
+
console.error("Chat Loop eye:", code, message);
|
|
15
|
+
}
|
|
16
|
+
function isChatGPT(value) {
|
|
17
|
+
try {
|
|
18
|
+
const u = new URL(value);
|
|
19
|
+
return u.protocol === "https:" && u.hostname === "chatgpt.com";
|
|
20
|
+
} catch { return false; }
|
|
21
|
+
}
|
|
22
|
+
async function findTarget(ownTab) {
|
|
23
|
+
// Action pages may open in a different window from the ChatGPT tab.
|
|
24
|
+
const candidates = await chrome.tabs.query({url: "https://chatgpt.com/*"});
|
|
25
|
+
const eligible = candidates.filter(tab => isChatGPT(tab.url));
|
|
26
|
+
const requested = params.get("tabId");
|
|
27
|
+
if (requested !== null) {
|
|
28
|
+
if (!/^[1-9][0-9]*$/.test(requested)) throw Error("INVALID_TAB_ID");
|
|
29
|
+
const match = eligible.find(tab => tab.id === Number(requested));
|
|
30
|
+
if (!match) throw Error("TARGET_NOT_CHATGPT_OR_NOT_FOUND");
|
|
31
|
+
return match;
|
|
32
|
+
}
|
|
33
|
+
// When an action page was opened from a ChatGPT tab, respect its opener.
|
|
34
|
+
const opener = eligible.find(tab => tab.id === ownTab.openerTabId);
|
|
35
|
+
if (opener) return opener;
|
|
36
|
+
if (eligible.length === 0) throw Error("NO_CHATGPT_TAB");
|
|
37
|
+
if (eligible.length !== 1) {
|
|
38
|
+
const ids = eligible.map(tab => tab.id).join(", ");
|
|
39
|
+
throw Error("AMBIGUOUS_CHATGPT_TABS: use ?tabId=... (available: " + ids + ")");
|
|
40
|
+
}
|
|
41
|
+
return eligible[0];
|
|
42
|
+
}
|
|
43
|
+
async function closeAction(ownTab) {
|
|
44
|
+
await chrome.tabs.remove(ownTab.id);
|
|
45
|
+
}
|
|
46
|
+
async function readChat(tab, mode) {
|
|
47
|
+
// Capture the original URL, not the mutable Chrome Tab object. A user may
|
|
48
|
+
// navigate this same tab while a content-script read is in flight.
|
|
49
|
+
const expectedUrl=tab.url;
|
|
50
|
+
const verifyTarget=async()=>{
|
|
51
|
+
const current=await chrome.tabs.get(tab.id).catch(()=>null);
|
|
52
|
+
if(!current || current.url!==expectedUrl)throw Error('TARGET_CHANGED_DURING_READ');
|
|
53
|
+
};
|
|
54
|
+
const request = () => chrome.tabs.sendMessage(tab.id,
|
|
55
|
+
{type: "CHAT_LOOP_EYE_READ_V1", mode});
|
|
56
|
+
let response;
|
|
57
|
+
try {
|
|
58
|
+
response = await request();
|
|
59
|
+
} catch {
|
|
60
|
+
// Reload invalidates old content scripts. Never reinject after a tab has
|
|
61
|
+
// navigated away from the original target during this read.
|
|
62
|
+
await verifyTarget();
|
|
63
|
+
try {
|
|
64
|
+
await chrome.scripting.executeScript({target: {tabId: tab.id}, files: ["content.js"]});
|
|
65
|
+
response = await request();
|
|
66
|
+
} catch {
|
|
67
|
+
throw Error("CONTENT_SCRIPT_UNAVAILABLE: could not reinject into ChatGPT tab");
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (response?.contract !== CONTRACT || response?.status !== "OK"
|
|
71
|
+
|| response?.mode !== mode || typeof response?.value !== "string") {
|
|
72
|
+
throw Error("INVALID_CONTENT_RESPONSE");
|
|
73
|
+
}
|
|
74
|
+
await verifyTarget();
|
|
75
|
+
return response.value;
|
|
76
|
+
}
|
|
77
|
+
function copyText(value) {
|
|
78
|
+
// Synchronous copy avoids losing the macOS pasteboard when this action tab closes.
|
|
79
|
+
const field = document.createElement("textarea");
|
|
80
|
+
field.value = value;
|
|
81
|
+
field.setAttribute("readonly", "");
|
|
82
|
+
field.style.position = "fixed";
|
|
83
|
+
field.style.opacity = "0";
|
|
84
|
+
document.body.appendChild(field);
|
|
85
|
+
field.focus();
|
|
86
|
+
field.select();
|
|
87
|
+
const copied = document.execCommand("copy");
|
|
88
|
+
field.remove();
|
|
89
|
+
if (!copied) throw Error("CLIPBOARD_COPY_FAILED");
|
|
90
|
+
}
|
|
91
|
+
// Only requestId generated by the local CLI enables machine-result mode.
|
|
92
|
+
// Manual Action pages keep the verified clipboard/download behavior.
|
|
93
|
+
const nativeHost = "com.tomflow.chatloop.extension";
|
|
94
|
+
const machineId = params.get("requestId");
|
|
95
|
+
async function machineBinding(action) {
|
|
96
|
+
if (machineId === null) return null;
|
|
97
|
+
if (!/^[a-f0-9]{32}$/.test(machineId)) throw Error("INVALID_MACHINE_REQUEST");
|
|
98
|
+
const request = await chrome.runtime.sendNativeMessage(nativeHost,
|
|
99
|
+
{op:"acquire",id:machineId,action});
|
|
100
|
+
if (request?.status !== "OK" || request.id !== machineId || request.action !== action
|
|
101
|
+
|| typeof request.nonce !== "string") throw Error(request?.code || "NATIVE_REQUEST_REJECTED");
|
|
102
|
+
const target = await chrome.runtime.sendMessage({
|
|
103
|
+
type:"CHAT_LOOP_EXTENSION_TARGET_V1",id:machineId,action
|
|
104
|
+
});
|
|
105
|
+
if (target?.status !== "OK") throw Error(target?.code || "OWNER_NOT_AVAILABLE");
|
|
106
|
+
return {id:machineId,nonce:request.nonce,action,
|
|
107
|
+
tabId:target.tabId??null,page:target.page??null};
|
|
108
|
+
}
|
|
109
|
+
async function machineTarget(binding) {
|
|
110
|
+
if (!binding || !Number.isInteger(binding.tabId)
|
|
111
|
+
|| typeof binding.page !== "string") throw Error("OWNER_UNVERIFIED");
|
|
112
|
+
const tab = await chrome.tabs.get(binding.tabId);
|
|
113
|
+
if (!tab?.url || new URL(tab.url).pathname !== binding.page
|
|
114
|
+
|| new URL(tab.url).origin !== "https://chatgpt.com") throw Error("OWNER_CHANGED");
|
|
115
|
+
return tab;
|
|
116
|
+
}
|
|
117
|
+
async function machineResult(binding,payload) {
|
|
118
|
+
const response = await chrome.runtime.sendNativeMessage(nativeHost,{
|
|
119
|
+
op:"complete",id:binding.id,nonce:binding.nonce,action:binding.action,status:"OK",payload
|
|
120
|
+
});
|
|
121
|
+
if(response?.status!=="SAVED"||response.id!==binding.id)throw Error(response?.code||"NATIVE_RESULT_UNVERIFIED");
|
|
122
|
+
}
|
|
123
|
+
async function machineFailure(action,error) {
|
|
124
|
+
if (machineId === null || !/^[a-f0-9]{32}$/.test(machineId)) return;
|
|
125
|
+
try {
|
|
126
|
+
const req=await chrome.runtime.sendNativeMessage(nativeHost,
|
|
127
|
+
{op:"acquire",id:machineId,action});
|
|
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';
|
|
133
|
+
const saved = await chrome.runtime.sendNativeMessage(nativeHost,{
|
|
134
|
+
op:"complete",id:machineId,nonce:req.nonce,action,status:"FAILED",code
|
|
135
|
+
});
|
|
136
|
+
// Machine errors already have a durable CLI receipt. They must not
|
|
137
|
+
// accumulate as abandoned tabs; manual/unverified errors remain open.
|
|
138
|
+
if(saved?.status==="SAVED" && saved.id===machineId) {
|
|
139
|
+
const own = await chrome.tabs.getCurrent();
|
|
140
|
+
if(own?.id && own.url===location.href)
|
|
141
|
+
await chrome.tabs.remove(own.id).catch(()=>{});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
} catch { /* CLI timeout is UNKNOWN, never success. */ }
|
|
145
|
+
}
|
|
146
|
+
function requireOwnTab(tab) {
|
|
147
|
+
if (!tab?.id) throw Error("ACTION_TAB_UNVERIFIED");
|
|
148
|
+
return tab;
|
|
149
|
+
}
|
|
150
|
+
// Text and DOM share the same verified read path. Their separate pages
|
|
151
|
+
// select a fixed mode and clipboard settling delay; no extra executor.
|
|
152
|
+
async function runReadAction(mode, clipboardMs, action="chat_"+mode) {
|
|
153
|
+
if(!['text','dom'].includes(mode)||!/^chat_[a-z0-9_]+$/.test(action))
|
|
154
|
+
throw Error('EYE_MODE_UNSUPPORTED');
|
|
155
|
+
try {
|
|
156
|
+
const machine=await machineBinding(action);
|
|
157
|
+
const own=requireOwnTab(await chrome.tabs.getCurrent());
|
|
158
|
+
const target=machine ? await machineTarget(machine) : await findTarget(own);
|
|
159
|
+
show("RUNNING", mode+" → ChatGPT tab "+target.id);
|
|
160
|
+
const value=await readChat(target,mode);
|
|
161
|
+
if(!value.length)throw Error("EMPTY_CONTENT");
|
|
162
|
+
if(machine)await machineResult(machine,value);
|
|
163
|
+
else {
|
|
164
|
+
copyText(value);
|
|
165
|
+
await new Promise(resolve=>setTimeout(resolve,clipboardMs));
|
|
166
|
+
}
|
|
167
|
+
await done(own,mode,target);
|
|
168
|
+
}catch(error){
|
|
169
|
+
await machineFailure(action,error);
|
|
170
|
+
fail(error.message || "UNEXPECTED_ERROR",
|
|
171
|
+
"操作未完成;动作页已保留,未对其他 ChatGPT 标签页进行操作。");
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function done(ownTab, action, target) {
|
|
175
|
+
show("SUCCESS", action + " completed for tab " + target.id);
|
|
176
|
+
document.body.dataset.result = "success";
|
|
177
|
+
return closeAction(ownTab);
|
|
178
|
+
}
|
|
179
|
+
globalThis.ChatLoopActionCommonV1 = Object.freeze({
|
|
180
|
+
show, fail, findTarget, readChat, copyText, closeAction, done, requireOwnTab,
|
|
181
|
+
machineBinding, machineTarget, machineResult, machineFailure, runReadAction
|
|
182
|
+
});
|
|
183
|
+
})();
|