@tomflow/chatloop-tools 0.9.20 → 0.9.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  2. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  3. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  4. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  5. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  13. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  16. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  43. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  44. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  45. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  46. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  47. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  48. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  49. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  50. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  51. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  109. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  110. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  111. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  112. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  113. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  114. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  115. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  116. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  117. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  118. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  119. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  120. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  121. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  122. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  123. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  124. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  125. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  126. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  127. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  128. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  129. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  130. package/node_modules/ps-list/index.d.ts +76 -0
  131. package/node_modules/ps-list/index.js +366 -0
  132. package/node_modules/ps-list/license +9 -0
  133. package/node_modules/ps-list/package.json +44 -0
  134. package/node_modules/ps-list/readme.md +56 -0
  135. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  136. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  137. package/package.json +10 -2
@@ -0,0 +1,109 @@
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
+ nativeContextControl,nativeApiObservation,observeNativeOperation}=hostContract;
10
+ const MAX_INPUT=48*1024*1024;
11
+ const write=obj=>{
12
+ const b=Buffer.from(JSON.stringify(obj)),len=Buffer.alloc(4);
13
+ len.writeUInt32LE(b.length);process.stdout.write(Buffer.concat([len,b]));
14
+ };
15
+ let buf=Buffer.alloc(0),handled=false,observationOnly=false;
16
+ process.stdin.on('data',async chunk=>{
17
+ if(handled)return;
18
+ buf=Buffer.concat([buf,chunk]);
19
+ if(buf.length<4)return;
20
+ const n=buf.readUInt32LE();
21
+ if(n>MAX_INPUT){handled=true;write({status:'FAILED',code:'MESSAGE_TOO_LARGE'});return;}
22
+ if(buf.length<4+n)return;
23
+ handled=true;
24
+ try{
25
+ const m=JSON.parse(buf.subarray(4,4+n).toString('utf8'));
26
+ observationOnly=m.op==='api-observation';
27
+ const dispatch=async()=>{
28
+ if(m.op==='acquire'){
29
+ const r=readRequest(m.id);
30
+ if(r.action!==m.action)throw Object.assign(Error('Action mismatch'),{code:'REQUEST_MISMATCH'});
31
+ write({status:'OK',id:r.id,action:r.action,nonce:r.nonce,
32
+ ...(r.traceParent?{traceParent:r.traceParent}:{}),
33
+ ...(r.intent ? {intent:r.intent} : {})});
34
+ }else if(m.op==='complete'){
35
+ const r=finish(m);
36
+ write({status:'SAVED',id:r.id,action:r.action,bytes:r.bytes});
37
+ }else if(m.op==='session-read'){
38
+ const session=readSession();let projectContext=null,contextStatus='MISSING';
39
+ try{projectContext=session?registeredContext(session.projectId):null;
40
+ if(projectContext)contextStatus='VERIFIED';}catch{contextStatus='UNVERIFIED';}
41
+ write({status:'OK',session,contextStatus,...(projectContext?{projectContext}:{})});
42
+ }else if(m.op==='context-control'){
43
+ // Only Chrome Native Messaging can initiate this command. The Native
44
+ // session pointer must already be synchronized by the unique Worker.
45
+ const session=readSession();
46
+ if(!session?.taskId||!session.sessionId)
47
+ throw Object.assign(Error('No Context-managed session'),{code:'CONTEXT_SESSION_UNBOUND'});
48
+ if(!['permit.consume','run.bind.initial','run.fence','run.bind.handoff',
49
+ 'run.restore-same-owner','run.fence.terminal','run.credential.rotate',
50
+ 'run.terminalStatus','run.reopenStatus','run.snapshot'].includes(m.command)
51
+ ||!m.args||typeof m.args!=='object'||Array.isArray(m.args))
52
+ throw Object.assign(Error('Invalid Context command'),{code:'CONTEXT_COMMAND_INVALID'});
53
+ const own=new Set(['projectId','taskId','sessionId','generation','activeChatId',
54
+ 'role','principal','internalAuthorized','ownerCommitted','nativeCommitted',
55
+ 'sourceRunRef','oldActionTokenRevoked','workerRestored','nativeRestored','ownerStillSame']);
56
+ if(Object.keys(m.args).some(k=>own.has(k)))
57
+ throw Object.assign(Error('Reserved Context identity field'),{code:'CONTEXT_IDENTITY_FORBIDDEN'});
58
+ const args={...m.args,projectId:session.projectId,taskId:session.taskId,
59
+ sessionId:session.sessionId,generation:session.generation,
60
+ activeChatId:session.activeChatId};
61
+ if(m.command==='run.bind.initial'||m.command==='run.bind.handoff')
62
+ args.runRef=session.sessionId+':'+session.taskId+':'+session.generation;
63
+ if(['run.fence','run.fence.terminal','run.credential.rotate'].includes(m.command))
64
+ args.runRef=session.sessionId+':'+session.taskId+':'+session.generation;
65
+ const result=await nativeContextControl(m.command,args);
66
+ write({status:'OK',result});
67
+ }else if(m.op==='api-observation'){
68
+ // Separate request. Observations never delay a business Native reply.
69
+ const recorded=await nativeApiObservation(m.record);
70
+ write({status:recorded?'RECORDED':'DROPPED'});
71
+ }else if(m.op==='session-sync'){
72
+ write({status:'OK',session:writeSession(m.session,
73
+ m.replaceBlockedSessionId,m.resumeBlockedSessionId,m.resumeBlockedUpdatedAt??null)});
74
+ }else throw Object.assign(Error('Unknown operation'),{code:'INVALID_OPERATION'});
75
+ };
76
+ // The telemetry operation is intentionally excluded from self-recording.
77
+ // Recording it here would recursively spawn more Native log requests.
78
+ if(m.op==='api-observation')await dispatch();
79
+ else {
80
+ // Only a private CLI request is allowed to anchor a Native child span.
81
+ // A browser-supplied ID is never treated as authorization or receipt.
82
+ let parent=null;
83
+ try{
84
+ if(['acquire','complete'].includes(m.op)){
85
+ const record=readRequest(m.id);
86
+ if(record.action===m.action)parent=record.traceParent||null;
87
+ }else if(m.op==='session-read'&&m.sourceRequestId){
88
+ const record=readRequest(m.sourceRequestId);
89
+ const p=m.traceParent;
90
+ if(record.action==='status'&&record.traceParent&&p&&
91
+ record.traceParent.traceId===p.traceId)parent=p;
92
+ }
93
+ }catch{/* Non-authoritative parent cannot modify Native business outcome. */}
94
+ await observeNativeOperation(m.op,dispatch,parent);
95
+ }
96
+ }catch(e){write({status:'FAILED',code:e.code||'NATIVE_HOST_ERROR'});}
97
+ finally{
98
+ // Observation-only requests cannot recursively generate Native audit.
99
+ // Never delay their Writer receipt for an unrelated drain timeout.
100
+ if(!observationOnly){
101
+ const audit=await hostContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(4200);
102
+ if(audit?.status!=='OK'){
103
+ // The business reply is already written and remains authoritative.
104
+ process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
105
+ component:'extension.native',...audit})+'\n');
106
+ }
107
+ }
108
+ }
109
+ });
@@ -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:'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:'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,120 @@
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 saved=await chrome.runtime.sendNativeMessage(host,{
110
+ op:'complete',id:reqId,nonce:receipt.nonce,action,status:'FAILED',
111
+ code:String(e.message||'CLEAN_UNVERIFIED').slice(0,120)});
112
+ if(saved?.status==='SAVED'&&saved.id===reqId){
113
+ await chrome.tabs.remove(own.id).catch(()=>{});
114
+ }
115
+ }catch{}
116
+ }
117
+ throw e;
118
+ }
119
+ }
120
+ run().catch(e=>show('BLOCKED',e.message||'CLEAN_FAILED'));
@@ -0,0 +1,180 @@
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 saved = await chrome.runtime.sendNativeMessage(nativeHost,{
130
+ op:"complete",id:machineId,nonce:req.nonce,action,status:"FAILED",
131
+ code:String(error?.message||"ACTION_FAILED").slice(0,120)
132
+ });
133
+ // Machine errors already have a durable CLI receipt. They must not
134
+ // accumulate as abandoned tabs; manual/unverified errors remain open.
135
+ if(saved?.status==="SAVED" && saved.id===machineId) {
136
+ const own = await chrome.tabs.getCurrent();
137
+ if(own?.id && own.url===location.href)
138
+ await chrome.tabs.remove(own.id).catch(()=>{});
139
+ }
140
+ }
141
+ } catch { /* CLI timeout is UNKNOWN, never success. */ }
142
+ }
143
+ function requireOwnTab(tab) {
144
+ if (!tab?.id) throw Error("ACTION_TAB_UNVERIFIED");
145
+ return tab;
146
+ }
147
+ // Text and DOM share the same verified read path. Their separate pages
148
+ // select a fixed mode and clipboard settling delay; no extra executor.
149
+ async function runReadAction(mode, clipboardMs, action="chat_"+mode) {
150
+ if(!['text','dom'].includes(mode)||!/^chat_[a-z0-9_]+$/.test(action))
151
+ throw Error('EYE_MODE_UNSUPPORTED');
152
+ try {
153
+ const machine=await machineBinding(action);
154
+ const own=requireOwnTab(await chrome.tabs.getCurrent());
155
+ const target=machine ? await machineTarget(machine) : await findTarget(own);
156
+ show("RUNNING", mode+" → ChatGPT tab "+target.id);
157
+ const value=await readChat(target,mode);
158
+ if(!value.length)throw Error("EMPTY_CONTENT");
159
+ if(machine)await machineResult(machine,value);
160
+ else {
161
+ copyText(value);
162
+ await new Promise(resolve=>setTimeout(resolve,clipboardMs));
163
+ }
164
+ await done(own,mode,target);
165
+ }catch(error){
166
+ await machineFailure(action,error);
167
+ fail(error.message || "UNEXPECTED_ERROR",
168
+ "操作未完成;动作页已保留,未对其他 ChatGPT 标签页进行操作。");
169
+ }
170
+ }
171
+ function done(ownTab, action, target) {
172
+ show("SUCCESS", action + " completed for tab " + target.id);
173
+ document.body.dataset.result = "success";
174
+ return closeAction(ownTab);
175
+ }
176
+ globalThis.ChatLoopActionCommonV1 = Object.freeze({
177
+ show, fail, findTarget, readChat, copyText, closeAction, done, requireOwnTab,
178
+ machineBinding, machineTarget, machineResult, machineFailure, runReadAction
179
+ });
180
+ })();