@tomflow/chatloop-tools 0.9.62 → 0.9.64

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 (154) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +29 -10
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/package.json +3 -13
  9. package/providers/extension.mjs +59 -16
  10. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  11. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  12. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  13. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  14. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  15. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  16. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  17. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  18. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  19. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  20. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  21. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  24. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
  25. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  26. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
  27. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  28. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
  29. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
  30. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  31. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
  32. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  33. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  34. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
  35. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  36. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  37. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  38. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
  39. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
  40. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
  41. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
  42. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  45. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
  46. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  47. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
  48. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  49. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  50. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
  51. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
  52. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  53. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  54. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  55. package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
  56. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
  57. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
  58. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  63. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  64. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
  65. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  66. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  67. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
  68. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  69. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
  78. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  80. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
  81. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
  82. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
  83. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
  84. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  85. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
  86. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  87. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  88. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  89. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  90. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
  91. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  97. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
  98. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  99. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  100. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  101. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  102. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
  103. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  104. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  105. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
  106. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  107. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  108. package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
  109. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  110. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  111. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
  126. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  127. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
  128. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
  129. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
  130. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -83
  131. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  132. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
  133. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
  134. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
  135. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  136. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
  137. package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
  138. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  139. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  140. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  141. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  142. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  143. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
  144. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
  145. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
  146. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  147. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  148. package/node_modules/ps-list/index.d.ts +0 -76
  149. package/node_modules/ps-list/index.js +0 -366
  150. package/node_modules/ps-list/license +0 -9
  151. package/node_modules/ps-list/package.json +0 -44
  152. package/node_modules/ps-list/readme.md +0 -56
  153. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  154. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,153 +0,0 @@
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
- 'extension session':'Usage: chatloop-extension extension session (JSON intent on stdin)\nCancel only an exact Context-managed idle Adopt; does not deliver the Task.',
25
- 'extension entry test':'Usage: chatloop-extension extension entry test (JSON intent on stdin)\nTEST_ONLY: use the built-in Extension Action to create a new normal Chat, choose the actual native @ App, and send exactly once without a Browser Owner.'
26
- };
27
- function helpFor(args){
28
- if(args.length===1&&['-h','--help','help'].includes(args[0]))return HELP[''];
29
- if(args.at(-1)==='--help'||args.at(-1)==='-h'){
30
- const section=args.slice(0,-1).join(' ');
31
- return HELP[section] || (section.startsWith('extension chat ')
32
- ? 'Usage: chatloop-extension '+section+'\nRead the current uniquely verified Chat Owner.'
33
- : section==='extension reload'?'Usage: chatloop-extension extension reload\nRequest extension reload; final health is unverified.'
34
- : null);
35
- }
36
- return null;
37
- }
38
-
39
- const wait=ms=>new Promise(r=>setTimeout(r,ms));
40
- const emit=(event,command,fields={})=>process.stdout.write(JSON.stringify({contract,providerVersion,event,command,...fields})+'\n');
41
- const quoted=s=>"'"+s.replaceAll("'","'\\''")+"'";
42
- function installHost(extensionId) {
43
- validateExtensionId(extensionId);
44
- if(process.platform!=='darwin')throw Object.assign(Error('Native Host registration not verified on this OS'),{code:'HOST_INSTALL_UNSUPPORTED'});
45
- const conf=configFile();privateDir(dirname(conf));
46
- const node=process.execPath,script=fileURLToPath(new URL('./native-host.mjs',import.meta.url));
47
- const runner=join(dirname(conf),'native-host.sh');
48
- writeFileSync(runner,'#!/bin/sh\nexec '+quoted(node)+' '+quoted(script)+' "$@"\n',{mode:0o700});
49
- chmodSync(runner,0o700);
50
- const hostDir=join(homedir(),'Library','Application Support','Google','Chrome','NativeMessagingHosts');
51
- mkdirSync(hostDir,{recursive:true});
52
- const manifest={name:HOST_NAME,description:'Private Chat Loop Extension Native Messaging Host',
53
- path:runner,type:'stdio',allowed_origins:['chrome-extension://'+extensionId+'/']};
54
- const manifestPath=join(hostDir,HOST_NAME+'.json');
55
- writeFileSync(manifestPath,JSON.stringify(manifest,null,2)+'\n',{mode:0o600});
56
- writeFileSync(conf,JSON.stringify({extensionId,host:HOST_NAME,at:Date.now()},null,2)+'\n',{mode:0o600});
57
- return {status:'INSTALLED',extensionId,manifestPath};
58
- }
59
- function configuration() {
60
- if(!existsSync(configFile()))throw Object.assign(Error('Run host install <extension-id> first'),{code:'HOST_NOT_CONFIGURED'});
61
- const config=JSON.parse(readFileSync(configFile(),'utf8'));
62
- validateExtensionId(config.extensionId);
63
- return config;
64
- }
65
- function openAction(url) {
66
- return openExtensionActionPage(url);
67
- }
68
- async function executeAction(action,intent) {
69
- if(!ACTIONS.includes(action))throw Object.assign(Error('Unknown action'),{code:'UNKNOWN_ACTION'});
70
- const config=configuration(),req=prepare(action,intent);
71
- const descriptor=actionById.get(action);
72
- const page=descriptor?.page;
73
- if(!page)throw Object.assign(Error('Unknown action'),{code:'UNKNOWN_ACTION'});
74
- const url='chrome-extension://'+config.extensionId+'/'+page+'?requestId='+req.id
75
- +(action==='session'?'&operation='+intent.operation:'');
76
- openAction(url);
77
- const until=Date.now()+descriptor.waitMs;
78
- while(Date.now()<until){
79
- const result=readResult(req.id);
80
- if(result){
81
- if(result.status!=='OK')throw Object.assign(Error(result.code||'ACTION_FAILED'),{code:result.code||'ACTION_FAILED'});
82
- if(!result.verified) return {...result,status:'ACCEPTED_UNVERIFIED'};
83
- // The temp file is the canonical artifact. Returning small text is a CLI convenience.
84
- if(descriptor.textResult){
85
- const contents=readFileSync(result.path,'utf8');
86
- return {...result,content:contents.length<=500000?contents:undefined,
87
- truncated:contents.length>500000};
88
- }
89
- return result;
90
- }
91
- await wait(100);
92
- }
93
- throw Object.assign(Error('No verified Extension Action result; do not retry blindly'),{code:'RESULT_TIMEOUT'});
94
- }
95
- async function readIntent() {
96
- // Only for model control tools. Read a bounded stdin payload; never embed text in URL/argv.
97
- if(process.stdin.isTTY)throw Object.assign(Error('JSON intent required on stdin'),{code:'INVALID_INTENT'});
98
- let body='';
99
- process.stdin.setEncoding('utf8'); // JSON intent may span UTF-8 chunks.
100
- for await(const chunk of process.stdin){
101
- body+=chunk;
102
- if(body.length>6000)throw Object.assign(Error('Model intent too large'),{code:'INVALID_INTENT'});
103
- }
104
- try {return JSON.parse(body);}catch{
105
- throw Object.assign(Error('Invalid JSON intent'),{code:'INVALID_INTENT'});
106
- }
107
- }
108
- async function execute(argv) {
109
- const cmd=argv.join(' ');
110
- if(argv.length===0||cmd==='capabilities'){
111
- return {implemented:['capabilities','host install <extension-id>',
112
- ...actionCapabilities.map(cap=>'extension '+cap.cli.join(' ')+
113
- (cap.kind==='owner-clean'?' <tab-id>':
114
- ['owner-intent','owner-start','owner-session',
115
- 'entry-test'].includes(cap.kind)?' (JSON on stdin)':''))],
116
- available:existsSync(configFile()),hostConfigured:existsSync(configFile())};
117
- }
118
- if(argv[0]==='host'&&argv[1]==='install'&&argv.length===3)return installHost(argv[2]);
119
- const route=matchExtensionAction(actionCapabilities,argv);
120
- if(route)return executeAction(route.id,route.needsIntent
121
- ?await readIntent():route.intent);
122
- throw Object.assign(Error('Unknown command'),{code:'INVALID_ARGUMENT'});
123
- }
124
- const args=process.argv.slice(2),command=args.join(' ')||'capabilities';
125
- const help=helpFor(args);
126
- if(help!==null){
127
- process.stdout.write(help+'\n');
128
- }else{
129
- emit('STARTED',command);
130
- try{
131
- const data=await execute(args);
132
- emit('RESULT',command,{ok:true,value:data});
133
- }catch(e){
134
- const code=typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
135
- ?e.code:'UNKNOWN_RESULT';
136
- // Preserve the versioned CLI error shape but never publish arbitrary
137
- // native/OS error messages or absolute paths through stdout.
138
- emit('RESULT',command,{ok:false,error:{code,message:code}});
139
- process.exitCode=1;
140
- }
141
- }
142
- // After the CLI reply is produced, allow bounded observation delivery.
143
- // This never changes its result or retries its business side effect.
144
- try{
145
- const audit=await cliContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(5000);
146
- if(audit?.status!=='OK'){
147
- // The already-emitted RESULT remains authoritative even if Trace stalls.
148
- process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
149
- component:'extension.cli',...audit})+'\n');
150
- }
151
- }catch{
152
- // Soft telemetry must not change the CLI exit code after its business reply.
153
- }
@@ -1,207 +0,0 @@
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
- let replied=false;
12
- const write=obj=>{
13
- // One Native Messaging process may return exactly one business frame.
14
- // A later observer/drain failure must not append a contradictory result.
15
- if(replied)return;
16
- const b=Buffer.from(JSON.stringify(obj)),len=Buffer.alloc(4);
17
- len.writeUInt32LE(b.length);
18
- replied=true;
19
- process.stdout.write(Buffer.concat([len,b]));
20
- };
21
- let buf=Buffer.alloc(0),handled=false,observationOnly=false;
22
- process.stdin.on('data',async chunk=>{
23
- if(handled)return;
24
- // Bound accumulated bytes before Buffer.concat allocates. A claimed small
25
- // frame length cannot justify unbounded piped input or retained memory.
26
- if(buf.length+chunk.length>MAX_INPUT+4){
27
- handled=true;write({status:'FAILED',code:'MESSAGE_TOO_LARGE'});return;
28
- }
29
- buf=Buffer.concat([buf,chunk]);
30
- if(buf.length<4)return;
31
- const n=buf.readUInt32LE();
32
- if(n>MAX_INPUT){handled=true;write({status:'FAILED',code:'MESSAGE_TOO_LARGE'});return;}
33
- if(buf.length<4+n)return;
34
- handled=true;
35
- try{
36
- const m=JSON.parse(buf.subarray(4,4+n).toString('utf8'));
37
- observationOnly=m.op==='api-observation';
38
- const dispatch=async()=>{
39
- if(m.op==='acquire'){
40
- const r=readRequest(m.id);
41
- if(r.action!==m.action)throw Object.assign(Error('Action mismatch'),{code:'REQUEST_MISMATCH'});
42
- write({status:'OK',id:r.id,action:r.action,nonce:r.nonce,
43
- ...(r.traceParent?{traceParent:r.traceParent}:{}),
44
- ...(r.intent ? {intent:r.intent} : {})});
45
- }else if(m.op==='complete'){
46
- const r=finish(m);
47
- write({status:'SAVED',id:r.id,action:r.action,bytes:r.bytes});
48
- }else if(m.op==='session-read'){
49
- const session=readSession();let projectContext=null,contextStatus='MISSING';
50
- try{projectContext=session?registeredContext(session.projectId):null;
51
- if(projectContext)contextStatus='VERIFIED';}catch{contextStatus='UNVERIFIED';}
52
- write({status:'OK',session,contextStatus,...(projectContext?{projectContext}:{})});
53
- }else if(m.op==='context-control'){
54
- // Only Chrome Native Messaging can initiate this command. The Native
55
- // session pointer must already be synchronized by the unique Worker.
56
- const session=readSession();
57
- if(!session?.taskId||!session.sessionId)
58
- throw Object.assign(Error('No Context-managed session'),{code:'CONTEXT_SESSION_UNBOUND'});
59
- if(!['permit.consume','run.bind.initial','run.fence','run.bind.handoff',
60
- 'run.restore-same-owner','run.fence.terminal','run.credential.rotate',
61
- 'run.fence.cancel',
62
- 'run.terminalStatus','run.reopenStatus','run.snapshot'].includes(m.command)
63
- ||!m.args||typeof m.args!=='object'||Array.isArray(m.args))
64
- throw Object.assign(Error('Invalid Context command'),{code:'CONTEXT_COMMAND_INVALID'});
65
- if(m.command==='run.fence.cancel'){
66
- const request=readRequest(m.args.actionToken);
67
- const intent=request?.intent;
68
- if(request?.action!=='session'||intent?.operation!=='cancel'
69
- ||intent.confirmed!==true||intent.sessionId!==session.sessionId
70
- ||intent.projectId!==session.projectId
71
- ||intent.taskId!==session.taskId
72
- ||intent.generation!==session.generation
73
- ||intent.contextStoreEpoch!==m.args.expectedStoreEpoch
74
- ||intent.expectedTaskRevision!==m.args.expectedTaskRevision
75
- ||intent.expectedBindingRevision!==m.args.expectedBindingRevision)
76
- throw Object.assign(Error('Cancel authorization not verified'),
77
- {code:'SESSION_CANCEL_SOURCE_UNVERIFIED'});
78
- }
79
- const own=new Set(['projectId','taskId','sessionId','generation','activeChatId',
80
- 'role','principal','internalAuthorized','ownerCommitted','nativeCommitted',
81
- 'sourceRunRef','oldActionTokenRevoked','workerRestored','nativeRestored','ownerStillSame']);
82
- if(Object.keys(m.args).some(k=>own.has(k)))
83
- throw Object.assign(Error('Reserved Context identity field'),{code:'CONTEXT_IDENTITY_FORBIDDEN'});
84
- const args={...m.args,projectId:session.projectId,taskId:session.taskId,
85
- sessionId:session.sessionId,generation:session.generation,
86
- activeChatId:session.activeChatId};
87
- if(m.command==='run.bind.initial'||m.command==='run.bind.handoff')
88
- args.runRef=session.sessionId+':'+session.taskId+':'+session.generation;
89
- if(['run.fence','run.fence.terminal','run.credential.rotate',
90
- 'run.fence.cancel'].includes(m.command))
91
- args.runRef=session.sessionId+':'+session.taskId+':'+session.generation;
92
- const result=await nativeContextControl(m.command,args);
93
- write({status:'OK',result});
94
- }else if(m.op==='api-observation'){
95
- // Separate request. Observations never delay a business Native reply.
96
- const recorded=await nativeApiObservation(m.record);
97
- write({status:recorded?'RECORDED':'DROPPED'});
98
- }else if(m.op==='session-sync'){
99
- // An idle cancellation may become terminal only after the original
100
- // Context writer has been transactionally fenced. Native is the
101
- // independent boundary: Worker cannot make a canceled owner by writing
102
- // a plausible phase or by replaying a URL parameter.
103
- if(m.session?.phase==='CANCELLED'){
104
- const request=readRequest(m.cancelRequestId);
105
- const intent=request?.intent;
106
- if(request?.action!=='session'||intent?.operation!=='cancel'
107
- ||intent.confirmed!==true||intent.sessionId!==m.session.sessionId
108
- ||intent.projectId!==m.session.projectId
109
- ||intent.taskId!==m.session.taskId
110
- ||intent.generation!==m.session.generation)
111
- throw Object.assign(Error('Cancel source not verified'),
112
- {code:'SESSION_CANCEL_SOURCE_UNVERIFIED'});
113
- const old=readSession();
114
- if(!old||old.phase!=='BLOCKED'||!old.taskId
115
- ||old.sessionId!==m.session.sessionId
116
- ||old.projectId!==m.session.projectId
117
- ||old.generation!==m.session.generation
118
- ||old.updatedAt!==m.cancelBlockedUpdatedAt)
119
- throw Object.assign(Error('Cancel Native CAS failed'),
120
- {code:'SESSION_CANCEL_CAS_MISMATCH'});
121
- const terminal=await nativeContextControl('run.terminalStatus',{
122
- projectId:old.projectId,taskId:old.taskId,sessionId:old.sessionId,
123
- generation:old.generation,activeChatId:old.activeChatId});
124
- const cancelled=terminal?.sessionCancellation;
125
- if(terminal?.runRef!==null||terminal?.executionOutcome!==null
126
- ||cancelled?.status!=='CANCELLED_NOT_DELIVERED'
127
- ||cancelled.requestId!=='cancel-'+m.cancelRequestId
128
- ||cancelled?.sessionId!==old.sessionId
129
- ||cancelled?.generation!==old.generation
130
- ||cancelled?.oldRunRef!==old.sessionId+':'+old.taskId+':'+old.generation)
131
- throw Object.assign(Error('Context cancellation not fenced'),
132
- {code:'CONTEXT_CANCEL_FENCE_UNVERIFIED'});
133
- }else if(m.session?.phase==='BLOCKED'
134
- &&m.cancelFreezeExpectedAt!==undefined){
135
- const req=readRequest(m.cancelRequestId),intent=req?.intent;
136
- const old=readSession();
137
- if(req?.action!=='session'||intent?.operation!=='cancel'
138
- ||intent.confirmed!==true||!old
139
- ||old.phase!=='WAITING_REPLY'
140
- ||old.sessionId!==m.session.sessionId
141
- ||old.projectId!==m.session.projectId
142
- ||old.taskId!==m.session.taskId
143
- ||old.generation!==m.session.generation
144
- ||old.activeChatId!==m.session.activeChatId
145
- ||old.activeChatUrl!==m.session.activeChatUrl
146
- ||intent.sessionId!==old.sessionId
147
- ||intent.projectId!==old.projectId
148
- ||intent.taskId!==old.taskId
149
- ||intent.generation!==old.generation
150
- ||intent.expectedNativeUpdatedAt!==m.cancelFreezeExpectedAt
151
- ||old.updatedAt!==m.cancelFreezeExpectedAt)
152
- throw Object.assign(Error('Invalid cancellation freeze'),
153
- {code:'SESSION_CANCEL_FREEZE_CAS_MISMATCH'});
154
- }else if(Object.hasOwn(m,'cancelBlockedUpdatedAt')
155
- ||Object.hasOwn(m,'cancelFreezeExpectedAt')
156
- ||Object.hasOwn(m,'cancelRequestId'))
157
- throw Object.assign(Error('Invalid cancel transition'),
158
- {code:'SESSION_CANCEL_CAS_MISMATCH'});
159
- write({status:'OK',session:writeSession(m.session,
160
- m.replaceBlockedSessionId,m.resumeBlockedSessionId,
161
- m.resumeBlockedUpdatedAt??null,m.sameTaskPrePermitUpdatedAt??null,
162
- m.cancelBlockedUpdatedAt??null,
163
- m.cancelFreezeExpectedAt??null)});
164
- }else throw Object.assign(Error('Unknown operation'),{code:'INVALID_OPERATION'});
165
- };
166
- // The telemetry operation is intentionally excluded from self-recording.
167
- // Recording it here would recursively spawn more Native log requests.
168
- if(m.op==='api-observation')await dispatch();
169
- else {
170
- // Only a private CLI request is allowed to anchor a Native child span.
171
- // A browser-supplied ID is never treated as authorization or receipt.
172
- let parent=null;
173
- try{
174
- if(['acquire','complete'].includes(m.op)){
175
- const record=readRequest(m.id);
176
- if(record.action===m.action)parent=record.traceParent||null;
177
- }else if(m.op==='session-read'&&m.sourceRequestId){
178
- const record=readRequest(m.sourceRequestId);
179
- const p=m.traceParent;
180
- if(record.action==='status'&&record.traceParent&&p&&
181
- record.traceParent.traceId===p.traceId)parent=p;
182
- }
183
- }catch{/* Non-authoritative parent cannot modify Native business outcome. */}
184
- await observeNativeOperation(m.op,dispatch,parent);
185
- }
186
- }catch(e){
187
- const code=typeof e?.code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(e.code)
188
- ?e.code:'NATIVE_HOST_ERROR';
189
- write({status:'FAILED',code});
190
- }
191
- finally{
192
- // Observation-only requests cannot recursively generate Native audit.
193
- // Never delay their Writer receipt for an unrelated drain timeout.
194
- if(!observationOnly){
195
- try{
196
- const audit=await hostContract[Symbol.for('chat-loop.telemetry.drain.internal')]?.(4200);
197
- if(audit?.status!=='OK'){
198
- // Never expose audit internals or change an already-written reply.
199
- process.stderr.write('CHAT_LOOP_AUDIT_GAP '+JSON.stringify({
200
- component:'extension.native',...audit})+'\n');
201
- }
202
- }catch{
203
- // A logging failure must not reject this one-shot Native handler.
204
- }
205
- }
206
- }
207
- });
@@ -1 +0,0 @@
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'});
@@ -1 +0,0 @@
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'});
@@ -1 +0,0 @@
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'});
@@ -1 +0,0 @@
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'});
@@ -1 +0,0 @@
1
- export const capability=Object.freeze({id:'continue',page:'continue.html',cli:['continue'],kind:'owner-intent',waitMs:27000,textResult:true,description:'Queue Continue intent'});
@@ -1 +0,0 @@
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'});
@@ -1 +0,0 @@
1
- export const capability=Object.freeze({id:'handoff',page:'handoff.html',cli:['handoff'],kind:'owner-intent',waitMs:27000,textResult:true,description:'Queue Handoff intent'});
@@ -1 +0,0 @@
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'});
@@ -1 +0,0 @@
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 only)'});
@@ -1 +0,0 @@
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'});
@@ -1 +0,0 @@
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'});
@@ -1,123 +0,0 @@
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'));