@tomflow/chatloop-tools 0.9.21 → 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 (83) hide show
  1. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  2. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  3. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  4. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  5. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  6. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  7. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  8. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  9. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  10. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  11. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  12. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  13. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  14. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  15. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  16. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  17. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  18. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  19. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  20. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  21. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  22. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  23. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  24. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  25. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  26. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  27. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  28. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  29. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  30. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  31. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  32. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  33. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  34. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  35. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  36. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  37. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  38. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  39. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  40. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  41. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  43. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  44. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  45. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  46. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  47. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  48. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  49. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  50. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  51. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  56. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  57. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  65. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  66. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  67. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  68. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  69. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  70. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  71. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  72. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  73. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  74. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  75. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  76. package/node_modules/ps-list/index.d.ts +76 -0
  77. package/node_modules/ps-list/index.js +366 -0
  78. package/node_modules/ps-list/license +9 -0
  79. package/node_modules/ps-list/package.json +44 -0
  80. package/node_modules/ps-list/readme.md +56 -0
  81. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  82. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  83. package/package.json +7 -3
@@ -0,0 +1,94 @@
1
+ # @tomflow/chatloop-extension
2
+
3
+ Chrome MV3 companion for Chat Loop. **Browser Worker is the only Chrome Owner and
4
+ send authority**; Native Messaging is a guarded persistence/IPC boundary,
5
+ not a second browser executor.
6
+
7
+ ## Runtime entrypoints
8
+
9
+ - `index.mjs`: npm SDK with `verifyOrphanOwnerIdle`, `extensionCliApi`,
10
+ `nativeHostApi` — the only three exported functions.
11
+ - `bin/cli.mjs`: the `chatloop-extension` CLI (`npx` after publishing).
12
+ - `bin/native-host.mjs`: private Chrome Native Messaging Host process.
13
+ - `extension/background.js`: MV3 Worker and unique Browser Owner.
14
+ - `extension/actions/*.js`: Action executors; browser APIs are not Node SDKs.
15
+
16
+ ## API invocation logging
17
+
18
+ The public npm SDK, CLI and Native Host functions use a generated, bounded,
19
+ non-blocking API observation slice. The MV3 Worker's formal message dispatch
20
+ records only the allowlisted message type, not payloads or chat text. It
21
+ forwards a separate, best-effort Native observation into the **existing
22
+ Supervisor Trace** when available; an unavailable Native Host or Supervisor
23
+ can drop these observations but cannot change Owner or action receipts.
24
+ Remotely exposed Extension MCP calls are recorded independently by the Tools
25
+ Gateway's single API observation port. No second log service is created.
26
+ Logging cannot authorize sending, change Owner or retry an UNKNOWN action.
27
+
28
+ ## Build-time Action capabilities
29
+
30
+ Each `capabilities/<id>.mjs` owns an Action's name, CLI route, page,
31
+ execution kind, result type and local deadline. No separate API catalog is
32
+ maintained. `npm run build:actions` generates both:
33
+
34
+ - `actions.generated.mjs` — Node CLI/Native SDK action catalog.
35
+ - `extension/loop/action-catalog.generated.js` — browser-only Eye map.
36
+
37
+ New **read-only Eye** actions can declare an additional `chat_*` name,
38
+ their own CLI route, and either the existing `text` or `dom` read mode.
39
+ The builder creates their isolated Action HTML, which uses the same
40
+ `actions/common.js` target/Owner/Native receipt checks and the shared
41
+ `actions/read-mode.js` executor. No existing Action or central CLI/Worker
42
+ dispatch switch needs modification. The builder refuses duplicate names,
43
+ privileged type changes, invalid read modes, missing assets and stale output.
44
+
45
+ **A declaration does not grant sending authority.** Start, Continue, Handoff,
46
+ Clean, Status, screenshot and reload keep their reviewed, explicit Worker
47
+ handlers and existing trust boundaries. New send/Owner/Native mutation
48
+ requires a separate authorized security review and implementation; it cannot
49
+ be enabled by dropping in a capability file. Browser read actions never
50
+ clear an unknown send result or adopt a different Chat Owner.
51
+
52
+ ### Validation
53
+
54
+ ```sh
55
+ npm run build:actions
56
+ npm run build:actions:check
57
+ npm test
58
+ ```
59
+
60
+ Workspace `npm run check` and npm `pretest`/`prepack` also verify generated
61
+ catalogs. `test/capability-composition.test.mjs` proves isolated addition and
62
+ removal of an Eye action and rejects privileged or duplicate declarations.
63
+ The package build and Chrome manifest versions must match.
64
+
65
+ ## CLI
66
+
67
+ ```text
68
+ Usage: chatloop-extension <command> [options]
69
+ Commands: capabilities, host, extension
70
+ Run: chatloop-extension <command> --help
71
+ ```
72
+
73
+ ```text
74
+ Usage: chatloop-extension extension <command>
75
+ Commands: chat text | chat dom | chat screenshot | reload | continue | handoff | clean <tab-id> | status | start
76
+ Run: chatloop-extension extension <command> --help
77
+ ```
78
+
79
+ For the installed command list, run `chatloop-extension extension --help`.
80
+
81
+ `extension start` requires the real approved intent; `mode=adopt` does not
82
+ re-send. Continue/Handoff only register intents with one Turn token and never
83
+ silently send or repeat. Clean needs an exact verified tab ID, and Status
84
+ is read-only. IPC messages are one-shot and have durable identity checks.
85
+
86
+ This package's source version is read from its own `package.json`. Installed
87
+ Tools/Context consumers may pin a different Extension version; updating
88
+ their dependencies is a separate release task. Source tests do not prove
89
+ npm publication, Chrome reload, Native Host installation or Stage 03 E2E.
90
+ Inspect real installed versions, Owner and authoritative receipts first.
91
+
92
+ Product-level Extension/Context documents live in the source repository,
93
+ **not in this published npm package**. Its runtime API and security contract
94
+ are described above without requiring that repository.
@@ -0,0 +1,11 @@
1
+ // GENERATED by scripts/build-actions.mjs — do not edit.
2
+ import {capability as a0} from './capabilities/chat_text.mjs';
3
+ import {capability as a1} from './capabilities/chat_dom.mjs';
4
+ import {capability as a2} from './capabilities/chat_screenshot.mjs';
5
+ import {capability as a3} from './capabilities/reload.mjs';
6
+ import {capability as a4} from './capabilities/continue.mjs';
7
+ import {capability as a5} from './capabilities/handoff.mjs';
8
+ import {capability as a6} from './capabilities/clean.mjs';
9
+ import {capability as a7} from './capabilities/status.mjs';
10
+ import {capability as a8} from './capabilities/start.mjs';
11
+ export const actionCapabilities=Object.freeze([a0,a1,a2,a3,a4,a5,a6,a7,a8]);
@@ -0,0 +1,141 @@
1
+ #!/usr/bin/env node
2
+ // CLI is owned by the Extension package; local-tools delegates, never implements actions.
3
+ import {existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync} from 'node:fs';
4
+ import {homedir} from 'node:os';
5
+ import {dirname,join,resolve} from 'node:path';
6
+ import {fileURLToPath} from 'node:url';
7
+ import {extensionCliApi} from '../index.mjs';
8
+ const cliContract=extensionCliApi();
9
+ const {ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME,configFile,prepare,readResult,privateDir,validateExtensionId,openExtensionActionPage}=cliContract;
10
+ const actionById=new Map(actionCapabilities.map(cap=>[cap.id,cap]));
11
+ const actionHelp=actionCapabilities.map(cap=>cap.cli.join(' ')+
12
+ (cap.kind==='owner-clean'?' <tab-id>':'')).join(' | ');
13
+ const contract='chat-loop.extension-cli.v1';
14
+ const providerVersion=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
15
+ const HELP={
16
+ '': 'Usage: chatloop-extension <command> [options]\nCommands: capabilities, host, extension\nRun: chatloop-extension <command> --help',
17
+ host: 'Usage: chatloop-extension host install <extension-id>\nRegisters the local Chrome Native Messaging Host (macOS).',
18
+ extension: 'Usage: chatloop-extension extension <command>\nCommands: '+actionHelp+'\nRun: chatloop-extension extension <command> --help',
19
+ 'extension clean':'Usage: chatloop-extension extension clean <tab-id>\nClear only the verified ChatGPT composer. Never send or close a Chat.\nMachine Clean requires the exact tab id of a terminal Chat Loop Owner; popup Clean requires a user-selected ChatGPT tab.',
20
+ 'extension continue':'Usage: chatloop-extension extension continue (JSON intent on stdin)\nSubmit next-turn text or query receipt; does not send directly.',
21
+ 'extension handoff':'Usage: chatloop-extension extension handoff (JSON intent on stdin)\nRequest early handoff or query receipt; does not transfer directly.',
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.'
24
+ };
25
+ function helpFor(args){
26
+ if(args.length===1&&['-h','--help','help'].includes(args[0]))return HELP[''];
27
+ if(args.at(-1)==='--help'||args.at(-1)==='-h'){
28
+ const section=args.slice(0,-1).join(' ');
29
+ return HELP[section] || (section.startsWith('extension chat ')
30
+ ? 'Usage: chatloop-extension '+section+'\nRead the current uniquely verified Chat Owner.'
31
+ : section==='extension reload'?'Usage: chatloop-extension extension reload\nRequest extension reload; final health is unverified.'
32
+ : null);
33
+ }
34
+ return null;
35
+ }
36
+
37
+ const wait=ms=>new Promise(r=>setTimeout(r,ms));
38
+ const emit=(event,command,fields={})=>process.stdout.write(JSON.stringify({contract,providerVersion,event,command,...fields})+'\n');
39
+ const quoted=s=>"'"+s.replaceAll("'","'\\''")+"'";
40
+ function installHost(extensionId) {
41
+ validateExtensionId(extensionId);
42
+ if(process.platform!=='darwin')throw Object.assign(Error('Native Host registration not verified on this OS'),{code:'HOST_INSTALL_UNSUPPORTED'});
43
+ const conf=configFile();privateDir(dirname(conf));
44
+ const node=process.execPath,script=fileURLToPath(new URL('./native-host.mjs',import.meta.url));
45
+ const runner=join(dirname(conf),'native-host.sh');
46
+ writeFileSync(runner,'#!/bin/sh\nexec '+quoted(node)+' '+quoted(script)+' "$@"\n',{mode:0o700});
47
+ chmodSync(runner,0o700);
48
+ const hostDir=join(homedir(),'Library','Application Support','Google','Chrome','NativeMessagingHosts');
49
+ mkdirSync(hostDir,{recursive:true});
50
+ const manifest={name:HOST_NAME,description:'Private Chat Loop Extension Native Messaging Host',
51
+ path:runner,type:'stdio',allowed_origins:['chrome-extension://'+extensionId+'/']};
52
+ const manifestPath=join(hostDir,HOST_NAME+'.json');
53
+ writeFileSync(manifestPath,JSON.stringify(manifest,null,2)+'\n',{mode:0o600});
54
+ writeFileSync(conf,JSON.stringify({extensionId,host:HOST_NAME,at:Date.now()},null,2)+'\n',{mode:0o600});
55
+ return {status:'INSTALLED',extensionId,manifestPath};
56
+ }
57
+ function configuration() {
58
+ if(!existsSync(configFile()))throw Object.assign(Error('Run host install <extension-id> first'),{code:'HOST_NOT_CONFIGURED'});
59
+ const config=JSON.parse(readFileSync(configFile(),'utf8'));
60
+ validateExtensionId(config.extensionId);
61
+ return config;
62
+ }
63
+ function openAction(url) {
64
+ return openExtensionActionPage(url);
65
+ }
66
+ async function executeAction(action,intent) {
67
+ if(!ACTIONS.includes(action))throw Object.assign(Error('Unknown action'),{code:'UNKNOWN_ACTION'});
68
+ const config=configuration(),req=prepare(action,intent);
69
+ const descriptor=actionById.get(action);
70
+ const page=descriptor?.page;
71
+ if(!page)throw Object.assign(Error('Unknown action'),{code:'UNKNOWN_ACTION'});
72
+ const url='chrome-extension://'+config.extensionId+'/'+page+'?requestId='+req.id;
73
+ openAction(url);
74
+ const until=Date.now()+descriptor.waitMs;
75
+ while(Date.now()<until){
76
+ const result=readResult(req.id);
77
+ if(result){
78
+ if(result.status!=='OK')throw Object.assign(Error(result.code||'ACTION_FAILED'),{code:result.code||'ACTION_FAILED'});
79
+ if(!result.verified) return {...result,status:'ACCEPTED_UNVERIFIED'};
80
+ // The temp file is the canonical artifact. Returning small text is a CLI convenience.
81
+ if(descriptor.textResult){
82
+ const contents=readFileSync(result.path,'utf8');
83
+ return {...result,content:contents.length<=500000?contents:undefined,
84
+ truncated:contents.length>500000};
85
+ }
86
+ return result;
87
+ }
88
+ await wait(100);
89
+ }
90
+ throw Object.assign(Error('No verified Extension Action result; do not retry blindly'),{code:'RESULT_TIMEOUT'});
91
+ }
92
+ async function readIntent() {
93
+ // Only for model control tools. Read a bounded stdin payload; never embed text in URL/argv.
94
+ if(process.stdin.isTTY)throw Object.assign(Error('JSON intent required on stdin'),{code:'INVALID_INTENT'});
95
+ let body='';
96
+ process.stdin.setEncoding('utf8'); // JSON intent may span UTF-8 chunks.
97
+ for await(const chunk of process.stdin){
98
+ body+=chunk;
99
+ if(body.length>6000)throw Object.assign(Error('Model intent too large'),{code:'INVALID_INTENT'});
100
+ }
101
+ try {return JSON.parse(body);}catch{
102
+ throw Object.assign(Error('Invalid JSON intent'),{code:'INVALID_INTENT'});
103
+ }
104
+ }
105
+ async function execute(argv) {
106
+ const cmd=argv.join(' ');
107
+ if(argv.length===0||cmd==='capabilities'){
108
+ return {implemented:['capabilities','host install <extension-id>',
109
+ ...actionCapabilities.map(cap=>'extension '+cap.cli.join(' ')+
110
+ (cap.kind==='owner-clean'?' <tab-id>':
111
+ ['owner-intent','owner-start'].includes(cap.kind)?' (JSON on stdin)':''))],
112
+ available:existsSync(configFile()),hostConfigured:existsSync(configFile())};
113
+ }
114
+ if(argv[0]==='host'&&argv[1]==='install'&&argv.length===3)return installHost(argv[2]);
115
+ const route=matchExtensionAction(actionCapabilities,argv);
116
+ if(route)return executeAction(route.id,route.needsIntent
117
+ ?await readIntent():route.intent);
118
+ throw Object.assign(Error('Unknown command'),{code:'INVALID_ARGUMENT'});
119
+ }
120
+ const args=process.argv.slice(2),command=args.join(' ')||'capabilities';
121
+ const help=helpFor(args);
122
+ if(help!==null){
123
+ process.stdout.write(help+'\n');
124
+ }else{
125
+ emit('STARTED',command);
126
+ try{
127
+ const data=await execute(args);
128
+ emit('RESULT',command,{ok:true,value:data});
129
+ }catch(e){
130
+ emit('RESULT',command,{ok:false,error:{code:e.code||'UNKNOWN_RESULT',message:e.message}});
131
+ process.exitCode=1;
132
+ }
133
+ }
134
+ // After the CLI reply is produced, allow bounded observation delivery.
135
+ // This never changes its result or retries its business side effect.
136
+ const audit=await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(5000);
137
+ if(audit?.status!=='OK'){
138
+ // Sanitized counters only; the already-emitted RESULT is authoritative.
139
+ process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
140
+ component:'extension.cli',...audit})+'\n');
141
+ }
@@ -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'));