@tomflow/chatloop-tools 0.9.43 → 0.9.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -2
- package/bin/cli.mjs +12 -5
- package/index.mjs +60 -33
- package/lib/adapters/mcp-child.mjs +142 -30
- package/lib/adapters/tunnel.mjs +22 -11
- package/lib/context-control-auth.mjs +0 -5
- package/lib/context-gateway.mjs +14 -1
- package/lib/control.mjs +27 -8
- package/lib/extension-cli-contract.mjs +5 -3
- package/lib/extension-proxy.mjs +80 -10
- package/lib/gateway.mjs +20 -8
- package/lib/release-health-checks.mjs +49 -12
- package/lib/release-owner-preflight.mjs +1 -2
- package/lib/release-upgrade.mjs +6 -2
- package/lib/release.mjs +27 -6
- package/lib/supervisor-observability.mjs +2 -2
- package/lib/supervisor-runtime.mjs +96 -33
- package/lib/trace-gateway.mjs +70 -45
- package/lib/trace-observation.mjs +5 -3
- package/lib/tunnel.mjs +15 -5
- package/node_modules/@tomflow/chatloop-context/README.md +2 -2
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +1 -1
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +1 -1
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +1 -1
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +2 -7
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +3 -1
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +8 -3
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +13 -7
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +12 -8
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +20 -3
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +8 -4
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +5 -3
- package/node_modules/@tomflow/chatloop-context/package.json +3 -3
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +14 -6
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +26 -7
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +6 -3
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +5 -2
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +22 -4
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +19 -4
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +4 -2
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +11 -3
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +2 -1
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +11 -3
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +10 -9
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -1
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +9 -3
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +2 -2
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +8 -10
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +7 -2
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +2 -1
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +7 -1
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +16 -5
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +5 -7
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +12 -3
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +35 -21
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +11 -6
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +11 -3
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +39 -5
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +5 -1
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +5 -1
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +27 -3
- package/node_modules/@tomflow/chatloop-extension/package.json +2 -2
- package/node_modules/@tomflow/chatloop-trace/README.md +7 -2
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +66 -36
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +17 -4
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +30 -6
- package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
- package/package.json +6 -6
- package/providers/context.mjs +5 -1
- package/providers/desktop.mjs +23 -6
- package/providers/document.mjs +31 -5
- package/providers/extension.mjs +6 -4
- package/providers/form.mjs +5 -3
- package/providers/runtime.mjs +14 -6
- package/providers/trace.mjs +3 -2
package/lib/control.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import {connect} from 'node:net';
|
|
2
|
-
import {
|
|
2
|
+
import {lstatSync, mkdirSync, readFileSync, unlinkSync} from 'node:fs';
|
|
3
3
|
import {homedir} from 'node:os';
|
|
4
4
|
import {join} from 'node:path';
|
|
5
5
|
|
|
@@ -39,7 +39,12 @@ export function ensurePrivateDir() {
|
|
|
39
39
|
if (!s.isDirectory() || s.isSymbolicLink() || (process.getuid && s.uid !== process.getuid()) || (s.mode & 0o077))
|
|
40
40
|
throw Object.assign(new Error('Insecure local-tools state directory'), {code:'INSECURE_STATE_DIR'});
|
|
41
41
|
}
|
|
42
|
-
|
|
42
|
+
// Detect occupied entries even if a symlink target no longer exists.
|
|
43
|
+
function pathPresent(path) {
|
|
44
|
+
try{lstatSync(path);return true}
|
|
45
|
+
catch(error){if(error.code==='ENOENT')return false;throw error}
|
|
46
|
+
}
|
|
47
|
+
function lockPresent(){return pathPresent(paths().lock)}
|
|
43
48
|
function verifyOwner(hello) {
|
|
44
49
|
const p=paths();
|
|
45
50
|
const d=lstatSync(p.dir), l=lstatSync(p.lock), s=lstatSync(p.socket);
|
|
@@ -89,13 +94,18 @@ export function send(request, timeout=3000) {
|
|
|
89
94
|
});
|
|
90
95
|
});
|
|
91
96
|
}
|
|
97
|
+
const verifiedBusinessReply=(reply,request)=>{
|
|
98
|
+
if(reply?.contract!==CONTRACT||reply.requestId!==request?.requestId)
|
|
99
|
+
throw Object.assign(Error('Uncorrelated Supervisor reply'),{code:'INVALID_REPLY'});
|
|
100
|
+
return reply;
|
|
101
|
+
};
|
|
92
102
|
export async function talk(request,timeout=12000){
|
|
93
103
|
const hello=await send({action:'__ping'},1200);
|
|
94
104
|
if(hello.contract!==CONTRACT||hello.version!==VERSION||hello.packageVersion!==PACKAGE_VERSION||
|
|
95
105
|
hello.registrySignature!==registry().map(t=>t.id+':'+t.enabled).join('|'))
|
|
96
106
|
throw Object.assign(new Error('Version or registry mismatch'),{code:'INCOMPATIBLE_VERSION'});
|
|
97
107
|
verifyOwner(hello);
|
|
98
|
-
return send(request,timeout);
|
|
108
|
+
return verifiedBusinessReply(await send(request,timeout),request);
|
|
99
109
|
}
|
|
100
110
|
|
|
101
111
|
// Upgrade is the only lifecycle path allowed to speak to the currently active
|
|
@@ -126,21 +136,30 @@ export async function talkForUpgrade(request,timeout=12000){
|
|
|
126
136
|
throw Object.assign(new Error('Upgrade owner lock and IPC mismatch'),{
|
|
127
137
|
code:'MANAGER_UNAVAILABLE'
|
|
128
138
|
});
|
|
129
|
-
return send(request,timeout);
|
|
139
|
+
return verifiedBusinessReply(await send(request,timeout),request);
|
|
130
140
|
}
|
|
131
141
|
export async function recoverStaleLock() {
|
|
132
142
|
const p=paths();
|
|
133
|
-
if
|
|
143
|
+
if(!lockPresent())return;
|
|
144
|
+
const first=lstatSync(p.lock);
|
|
145
|
+
if(!first.isFile()||first.isSymbolicLink()||(first.mode&0o077)
|
|
146
|
+
||process.getuid&&first.uid!==process.getuid())
|
|
147
|
+
throw Object.assign(Error('Untrusted owner lock'),{code:'MANAGER_UNAVAILABLE'});
|
|
134
148
|
const contents=readFileSync(p.lock,'utf8');
|
|
135
149
|
let data; try{data=JSON.parse(contents);}catch{throw Object.assign(new Error('Unrecognized owner lock'),{code:'MANAGER_UNAVAILABLE'});}
|
|
136
150
|
if (!Number.isSafeInteger(data.pid) || data.pid<2 || !data.nonce) throw Object.assign(new Error('Unverified owner lock'),{code:'MANAGER_UNAVAILABLE'});
|
|
137
151
|
try { process.kill(data.pid,0); throw Object.assign(new Error('Owner may still be alive'),{code:'MANAGER_UNAVAILABLE'}); }
|
|
138
152
|
catch(err){ if(err.code!=='ESRCH')throw err; }
|
|
139
153
|
// Fail closed on a changed lock; never send signals to a PID read from disk.
|
|
140
|
-
|
|
141
|
-
if(
|
|
154
|
+
const now=lstatSync(p.lock);
|
|
155
|
+
if(now.dev!==first.dev||now.ino!==first.ino
|
|
156
|
+
||readFileSync(p.lock,'utf8')!==contents)
|
|
157
|
+
throw Object.assign(new Error('Owner changed'),{code:'MANAGER_UNAVAILABLE'});
|
|
158
|
+
if(pathPresent(p.socket)) {
|
|
142
159
|
const s=lstatSync(p.socket);
|
|
143
|
-
if(!s.isSocket()
|
|
160
|
+
if(!s.isSocket()||s.isSymbolicLink()||(s.mode&0o077)
|
|
161
|
+
||process.getuid&&s.uid!==process.getuid())
|
|
162
|
+
throw Object.assign(new Error('Unowned socket'),{code:'MANAGER_UNAVAILABLE'});
|
|
144
163
|
unlinkSync(p.socket);
|
|
145
164
|
}
|
|
146
165
|
unlinkSync(p.lock);
|
|
@@ -8,8 +8,10 @@ export function acceptExtensionCliReceipt(reply,command,exitCode){
|
|
|
8
8
|
||reply.contract!==EXTENSION_CLI_CONTRACT
|
|
9
9
|
||reply.event!=='RESULT'||reply.command!==command
|
|
10
10
|
||typeof reply.ok!=='boolean'
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
// The official CLI always emits its npm package version. A mutable
|
|
12
|
+
// @latest provider cannot be audited if the receipt omits its identity.
|
|
13
|
+
||typeof reply.providerVersion!=='string'
|
|
14
|
+
||!VERSION.test(reply.providerVersion))
|
|
13
15
|
return invalid('INVALID_EXTENSION_REPLY');
|
|
14
16
|
if(reply.ok!==true||exitCode!==0)
|
|
15
17
|
return invalid(typeof reply.error?.code==='string'
|
|
@@ -18,5 +20,5 @@ export function acceptExtensionCliReceipt(reply,command,exitCode){
|
|
|
18
20
|
if(!reply.value||typeof reply.value!=='object'||Array.isArray(reply.value))
|
|
19
21
|
return invalid('INVALID_EXTENSION_REPLY');
|
|
20
22
|
return {ok:true,value:reply.value,
|
|
21
|
-
providerVersion:reply.providerVersion
|
|
23
|
+
providerVersion:reply.providerVersion};
|
|
22
24
|
}
|
package/lib/extension-proxy.mjs
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// Thin delegation only: all action implementations, CLI and Native Host live in
|
|
2
2
|
// @tomflow/chatloop-extension. This package does not touch Chrome pages.
|
|
3
3
|
import {spawn} from 'node:child_process';
|
|
4
|
-
import {readFileSync,statSync} from 'node:fs';
|
|
4
|
+
import {readFileSync,statSync,lstatSync} from 'node:fs';
|
|
5
5
|
import {tmpdir} from 'node:os';
|
|
6
|
+
import {join,dirname,basename} from 'node:path';
|
|
6
7
|
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
7
8
|
// Private modules never import or resolve another private implementation.
|
|
8
9
|
let extensionCommand, validExtensionArgs, isControlTool, acceptExtensionCliReceipt, extensionTools, readApiParent;
|
|
@@ -25,10 +26,20 @@ export {extensionTools};
|
|
|
25
26
|
const EXTENSION_PACKAGE='@tomflow/chatloop-extension@latest';
|
|
26
27
|
const NPX_COMMAND=process.platform==='win32'?'npx.cmd':'npx';
|
|
27
28
|
const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
29
|
+
const CHAT_URL=/^https:\/\/chatgpt\.com\/(?:c\/[0-9a-f-]{12,}|g\/[^/]+\/c\/[0-9a-f-]{12,})$/i;
|
|
30
|
+
const CHAT_ID=/^[0-9a-f-]{12,}$/i;
|
|
28
31
|
// Match the existing Context child-CLI correlation boundary. Never inherit
|
|
29
32
|
// an unverified stale parent from the supervisor process environment.
|
|
30
33
|
function childApiEnvironment(){
|
|
31
34
|
const env={...process.env};
|
|
35
|
+
// Extension is an npm-resolved CLI consumer, not a Context/Trace/Tunnel
|
|
36
|
+
// credential consumer. Preserve ordinary Node/npm execution settings and
|
|
37
|
+
// the local Tools state locator; do not forward unrelated private grants.
|
|
38
|
+
for(const key of Object.keys(env)){
|
|
39
|
+
if(/^(?:CHAT_LOOP_CONTEXT_|CHAT_LOOP_TRACE_|CHAT_LOOP_TUNNEL_)/.test(key)
|
|
40
|
+
||/(?:^|_)(?:API_KEY|ADMIN_KEY|ACCESS_KEY|TOKEN|SECRET|PASSWORD|PRIVATE_KEY|CREDENTIALS?)(?:_|$)/i.test(key))
|
|
41
|
+
delete env[key];
|
|
42
|
+
}
|
|
32
43
|
try{
|
|
33
44
|
const parent=readApiParent?.();
|
|
34
45
|
if(parent&&UUID.test(parent.traceId||'')&&UUID.test(parent.spanId||''))
|
|
@@ -44,6 +55,26 @@ export const extensionInvocation=name=>{
|
|
|
44
55
|
args:['--yes','--package='+EXTENSION_PACKAGE,'chatloop-extension',...command]};
|
|
45
56
|
};
|
|
46
57
|
const fail=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
58
|
+
// The mutable external CLI is not a file-read authority for the MCP Gateway.
|
|
59
|
+
// Accept only its declared, same-account private screenshot artifact path.
|
|
60
|
+
function screenshotSourceVerified(path){
|
|
61
|
+
if(typeof path!=='string')return false;
|
|
62
|
+
const parent=dirname(path),id=basename(parent);
|
|
63
|
+
if(!/^[a-f0-9]{32}$/.test(id))return false;
|
|
64
|
+
const root=join(tmpdir(),'chatloop-extension-'+
|
|
65
|
+
(process.getuid?.()??process.env.USERNAME??'user'));
|
|
66
|
+
if(path!==join(root,id,'result.png'))return false;
|
|
67
|
+
try{
|
|
68
|
+
for(const dir of [root,parent]){
|
|
69
|
+
const st=lstatSync(dir);
|
|
70
|
+
if(!st.isDirectory()||st.isSymbolicLink()||(st.mode&0o077)
|
|
71
|
+
||process.getuid&&st.uid!==process.getuid())return false;
|
|
72
|
+
}
|
|
73
|
+
const file=lstatSync(path);
|
|
74
|
+
return file.isFile()&&!file.isSymbolicLink()&&!(file.mode&0o077)
|
|
75
|
+
&&(!process.getuid||file.uid===process.getuid());
|
|
76
|
+
}catch{return false}
|
|
77
|
+
}
|
|
47
78
|
export async function forwardExtensionAction(name,args={}) {
|
|
48
79
|
if(!validExtensionArgs(name,args))return fail('INVALID_ARGUMENT');
|
|
49
80
|
const invocation=extensionInvocation(name);
|
|
@@ -66,8 +97,15 @@ export async function forwardExtensionAction(name,args={}) {
|
|
|
66
97
|
tailTimer.unref?.();
|
|
67
98
|
}
|
|
68
99
|
};
|
|
69
|
-
const
|
|
70
|
-
|
|
100
|
+
const abortUnknown=()=>{
|
|
101
|
+
// A timed-out or malformed CLI response cannot prove an Action never
|
|
102
|
+
// occurred. Do not return a retryable "no provider" classification.
|
|
103
|
+
child.kill('SIGTERM');
|
|
104
|
+
tailTimer=setTimeout(()=>child.kill('SIGKILL'),2000);
|
|
105
|
+
tailTimer.unref?.();
|
|
106
|
+
settle(fail('EXTENSION_RESULT_UNKNOWN'));
|
|
107
|
+
};
|
|
108
|
+
const timer=setTimeout(abortUnknown,name==='start'?330000:90000);
|
|
71
109
|
const command=name==='clean'?'extension clean '+args.tabId:extensionCommand(name).join(' ');
|
|
72
110
|
const consume=line=>{
|
|
73
111
|
let msg;try{msg=JSON.parse(line)}catch{return false}
|
|
@@ -77,7 +115,11 @@ export async function forwardExtensionAction(name,args={}) {
|
|
|
77
115
|
const result=acceptExtensionCliReceipt(msg,command,msg.ok===true?0:1);
|
|
78
116
|
// Latest is mutable. Trust only the declared CLI v1 protocol, exact
|
|
79
117
|
// command, structural result and action receipt, never a stale pin.
|
|
80
|
-
|
|
118
|
+
// Keep the verified CLI package version separate from the business
|
|
119
|
+
// payload. The MCP response may expose it as optional provenance.
|
|
120
|
+
settle(result.ok?{...result.value,providerVersion:result.providerVersion}
|
|
121
|
+
:fail(result.code==='INVALID_EXTENSION_REPLY'
|
|
122
|
+
?'EXTENSION_RESULT_UNKNOWN':result.code),true);
|
|
81
123
|
return true;
|
|
82
124
|
};
|
|
83
125
|
// Decode UTF-8 incrementally, and accept the completed RESULT frame
|
|
@@ -91,7 +133,8 @@ export async function forwardExtensionAction(name,args={}) {
|
|
|
91
133
|
if(finished)return;
|
|
92
134
|
stdoutBytes+=Buffer.byteLength(chunk,'utf8');
|
|
93
135
|
if(stdoutBytes>9*1024*1024){
|
|
94
|
-
|
|
136
|
+
// A truncated CLI stream cannot prove that the browser Action failed.
|
|
137
|
+
abortUnknown();return;
|
|
95
138
|
}
|
|
96
139
|
stdout+=chunk;
|
|
97
140
|
for(let n;(n=stdout.indexOf('\n'))>=0;){
|
|
@@ -100,27 +143,54 @@ export async function forwardExtensionAction(name,args={}) {
|
|
|
100
143
|
}
|
|
101
144
|
});
|
|
102
145
|
child.stderr.on('data',()=>{}); // Never expose private Chrome diagnostics.
|
|
103
|
-
child.on('error',
|
|
146
|
+
child.on('error',error=>settle(fail(
|
|
147
|
+
['ENOENT','EACCES'].includes(error?.code)
|
|
148
|
+
?'EXTENSION_CLI_UNAVAILABLE':'EXTENSION_RESULT_UNKNOWN')));
|
|
104
149
|
child.on('close',code=>{
|
|
105
150
|
closed=true;
|
|
106
151
|
if(tailTimer)clearTimeout(tailTimer);
|
|
107
152
|
if(finished)return;
|
|
108
|
-
|
|
153
|
+
// The child may have opened an Action page before losing stdout.
|
|
154
|
+
// Missing RESULT is an unknown side effect, not a proven failed call.
|
|
155
|
+
if(!consume(stdout.trim()))settle(fail('EXTENSION_RESULT_UNKNOWN'));
|
|
109
156
|
});
|
|
110
157
|
});
|
|
111
|
-
|
|
158
|
+
if(name==='chat_screenshot'&&response?.status==='OK'
|
|
159
|
+
&&!screenshotSourceVerified(response.path))return fail('IMAGE_SOURCE_UNVERIFIED');
|
|
160
|
+
const formatted=formatExtensionResult(name,response);
|
|
161
|
+
if(formatted?.isError){
|
|
162
|
+
// A provider-valid RESULT with an invalid *business* payload is not
|
|
163
|
+
// evidence that the browser Action failed before its side effect.
|
|
164
|
+
// Never expose a generic format error as permission to retry a send.
|
|
165
|
+
return typeof response?.providerVersion==='string'
|
|
166
|
+
?fail('EXTENSION_RESULT_UNKNOWN'):formatted;
|
|
167
|
+
}
|
|
168
|
+
if(typeof response?.providerVersion!=='string')return formatted;
|
|
169
|
+
// MCP _meta carries the audited CLI provenance without changing the JSON
|
|
170
|
+
// business receipt consumed by Owner/Continue/Handoff callers.
|
|
171
|
+
return {...formatted,_meta:{'com.tomflow.chatloop/extension-cli':{
|
|
172
|
+
providerVersion:response.providerVersion}}};
|
|
112
173
|
}
|
|
113
174
|
export function formatExtensionResult(name,response) {
|
|
114
175
|
if(response?.isError)return response;
|
|
176
|
+
// Only reload is designed to acknowledge before its own Extension worker
|
|
177
|
+
// exits. Every other action requires a verified business result.
|
|
115
178
|
if(response?.status==='ACCEPTED_UNVERIFIED')
|
|
116
|
-
return
|
|
179
|
+
return name==='reload'
|
|
180
|
+
?{content:[{type:'text',text:'ACCEPTED_UNVERIFIED: Extension reload requested; healthy restart not confirmed.'}]}
|
|
181
|
+
:fail('EXTENSION_RESULT_UNVERIFIED');
|
|
117
182
|
if(response?.status!=='OK'||response.action!==name||typeof response.path!=='string')
|
|
118
183
|
return fail('INVALID_EXTENSION_RESULT');
|
|
119
184
|
if(['start','status'].includes(name)){
|
|
120
185
|
try{
|
|
121
186
|
const proof=JSON.parse(response.content);
|
|
122
187
|
if(name==='start'){
|
|
123
|
-
|
|
188
|
+
// A mutable CLI provider must not return a mismatched Chat/session
|
|
189
|
+
// identity as a successful Start/Adopt receipt.
|
|
190
|
+
if(proof.status!=='OK'||!UUID.test(proof.sessionId||'')
|
|
191
|
+
||!CHAT_ID.test(proof.activeChatId||'')
|
|
192
|
+
||!CHAT_URL.test(proof.activeChatUrl||'')
|
|
193
|
+
||!proof.activeChatUrl.endsWith('/'+proof.activeChatId))
|
|
124
194
|
return fail('START_RESULT_UNVERIFIED');
|
|
125
195
|
}else if(!['OK','UNVERIFIED'].includes(proof.status))return fail('STATUS_RESULT_UNVERIFIED');
|
|
126
196
|
return {content:[{type:'text',text:JSON.stringify(proof)}]};
|
package/lib/gateway.mjs
CHANGED
|
@@ -16,6 +16,12 @@ export function configureGateway(ports){
|
|
|
16
16
|
}
|
|
17
17
|
const failure=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
18
18
|
const rpcError=(code,message)=>({code,message});
|
|
19
|
+
const safeToolError=e=>['ENOENT','ECONNREFUSED'].includes(e?.code)
|
|
20
|
+
?'TOOL_UNAVAILABLE'
|
|
21
|
+
:['MCP_PROVIDER_RESULT_INVALID','INVALID_REPLY','TIMEOUT','UNKNOWN_RESULT']
|
|
22
|
+
.includes(e?.code)?'UNKNOWN_RESULT'
|
|
23
|
+
:/^[A-Z][A-Z0-9_]{1,95}$/.test(e?.code||'')
|
|
24
|
+
?e.code:'MANAGER_UNAVAILABLE';
|
|
19
25
|
// Modern MCP requests carry their own protocol revision; the former MCP
|
|
20
26
|
// initialize handshake remains supported for already-installed clients.
|
|
21
27
|
const MODERN='2026-07-28';
|
|
@@ -79,8 +85,7 @@ export function runGateway(){
|
|
|
79
85
|
}
|
|
80
86
|
if(m.method==='tools/call'){
|
|
81
87
|
try{return reply(m.id,modernResult(await toolRouter.call(m.params?.name,m.params?.arguments)))}
|
|
82
|
-
catch(e){return reply(m.id,modernResult(failure(
|
|
83
|
-
?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE')))}
|
|
88
|
+
catch(e){return reply(m.id,modernResult(failure(safeToolError(e))))}
|
|
84
89
|
}
|
|
85
90
|
if(m.method==='resources/list'){
|
|
86
91
|
try{return reply(m.id,modernList(toolRouter.listResources()))}
|
|
@@ -97,15 +102,16 @@ export function runGateway(){
|
|
|
97
102
|
process.stdin.setEncoding('utf8');
|
|
98
103
|
process.stdin.on('data',chunk=>{
|
|
99
104
|
buf+=chunk;
|
|
100
|
-
//
|
|
101
|
-
//
|
|
102
|
-
|
|
105
|
+
// The 1 MiB limit applies to each frame, not to an arbitrary stdout
|
|
106
|
+
// chunk holding several valid JSON-RPC requests. Count UTF-8 bytes.
|
|
107
|
+
const oversize=()=>{
|
|
103
108
|
process.stderr.write('MCP frame too large\n');
|
|
104
|
-
process.exitCode=1;process.stdin.pause();
|
|
105
|
-
}
|
|
109
|
+
process.exitCode=1;process.stdin.pause();
|
|
110
|
+
};
|
|
106
111
|
let n;
|
|
107
112
|
while((n=buf.indexOf('\n'))>=0){
|
|
108
113
|
const line=buf.slice(0,n);buf=buf.slice(n+1);
|
|
114
|
+
if(Buffer.byteLength(line,'utf8')>1024*1024){oversize();return}
|
|
109
115
|
let m;try{m=JSON.parse(line)}catch{continue}
|
|
110
116
|
if(m?.id===undefined)continue; // MCP notifications have no call receipt.
|
|
111
117
|
// tools/list and tools/call already have their own runtime API spans;
|
|
@@ -113,10 +119,16 @@ export function runGateway(){
|
|
|
113
119
|
const handledByRouter=(connected||modernMeta(m))&&
|
|
114
120
|
['tools/list','tools/call','resources/list','resources/read'].includes(m.method);
|
|
115
121
|
const invoke=()=>processMessage(m);
|
|
116
|
-
|
|
122
|
+
// Execute the initial handshake in frame order: delaying initialize
|
|
123
|
+
// to a microtask makes a following tools/list appear unauthenticated.
|
|
124
|
+
// Synchronous observer failures still receive a bounded RPC error.
|
|
125
|
+
let task;
|
|
126
|
+
try{task=handledByRouter?invoke():observeProtocol(m.method,invoke)}
|
|
127
|
+
catch{reject(m.id,-32603,'INTERNAL_ERROR');continue}
|
|
117
128
|
void Promise.resolve(task).catch(()=>{
|
|
118
129
|
reject(m.id,-32603,'INTERNAL_ERROR');
|
|
119
130
|
});
|
|
120
131
|
}
|
|
132
|
+
if(Buffer.byteLength(buf,'utf8')>1024*1024)oversize();
|
|
121
133
|
});
|
|
122
134
|
}
|
|
@@ -13,7 +13,6 @@ export function tunnelBinaryPath(stage,platform=process.platform+'-'+process.arc
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
export async function verifyTunnelConnection(p,verified,ports={}){
|
|
16
|
-
if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return {result:'ok',testOnly:true};
|
|
17
16
|
const {run,runtimeLaunchEnv}=ports;
|
|
18
17
|
if(typeof run!=='function'||typeof runtimeLaunchEnv!=='function')
|
|
19
18
|
throw Object.assign(Error('TUNNEL_PROBE_PORT_MISSING'),{
|
|
@@ -44,7 +43,6 @@ export async function verifyTunnelConnection(p,verified,ports={}){
|
|
|
44
43
|
code:'NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY',tunnelStatus:last});
|
|
45
44
|
}
|
|
46
45
|
export async function verifyMcpTools(p,ports={}){
|
|
47
|
-
if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return {ok:true,testOnly:true};
|
|
48
46
|
const {runtimeLaunchEnv}=ports;
|
|
49
47
|
if(typeof runtimeLaunchEnv!=='function')
|
|
50
48
|
throw Object.assign(Error('MCP_PROBE_PORT_MISSING'),{
|
|
@@ -53,7 +51,7 @@ export async function verifyMcpTools(p,ports={}){
|
|
|
53
51
|
env:{...runtimeLaunchEnv(),CHAT_LOOP_API_LOG_STDERR:'0'},
|
|
54
52
|
stdio:['pipe','pipe','pipe'],windowsHide:true
|
|
55
53
|
});
|
|
56
|
-
let buffer='',
|
|
54
|
+
let buffer='',nextId=0,protocolFailure=null;
|
|
57
55
|
const waiting=new Map();
|
|
58
56
|
const rejectPending=error=>{
|
|
59
57
|
for(const pending of waiting.values()){
|
|
@@ -61,26 +59,56 @@ export async function verifyMcpTools(p,ports={}){
|
|
|
61
59
|
}
|
|
62
60
|
waiting.clear();
|
|
63
61
|
};
|
|
62
|
+
const failProbe=code=>{
|
|
63
|
+
if(protocolFailure)return;
|
|
64
|
+
protocolFailure=code;
|
|
65
|
+
rejectPending(Object.assign(Error(code),{code}));
|
|
66
|
+
};
|
|
64
67
|
child.stdout.setEncoding('utf8');
|
|
65
68
|
child.stderr.setEncoding('utf8');
|
|
66
69
|
child.stdout.on('data',chunk=>{
|
|
70
|
+
if(protocolFailure)return;
|
|
67
71
|
buffer+=chunk;
|
|
68
72
|
let end;
|
|
69
73
|
while((end=buffer.indexOf('\n'))>=0){
|
|
70
74
|
const line=buffer.slice(0,end);buffer=buffer.slice(end+1);
|
|
71
|
-
|
|
75
|
+
if(!line.trim())continue;
|
|
76
|
+
if(Buffer.byteLength(line,'utf8')>2*1024*1024)
|
|
77
|
+
return failProbe('MCP_PROBE_FRAME_TOO_LARGE');
|
|
78
|
+
let packet;try{packet=JSON.parse(line)}catch{
|
|
79
|
+
return failProbe('MCP_PROBE_FRAME_INVALID');
|
|
80
|
+
}
|
|
81
|
+
if(!packet||typeof packet!=='object'||Array.isArray(packet)
|
|
82
|
+
||packet.jsonrpc!=='2.0')
|
|
83
|
+
return failProbe('MCP_PROBE_FRAME_INVALID');
|
|
72
84
|
const pending=waiting.get(packet.id);
|
|
73
|
-
if(pending){
|
|
85
|
+
if(pending){
|
|
86
|
+
waiting.delete(packet.id);clearTimeout(pending.timer);
|
|
87
|
+
if(Object.hasOwn(packet,'error')===Object.hasOwn(packet,'result'))
|
|
88
|
+
pending.reject(Object.assign(Error('MCP_PROBE_REPLY_INVALID'),
|
|
89
|
+
{code:'MCP_PROBE_REPLY_INVALID'}));
|
|
90
|
+
else pending.resolve(packet);
|
|
91
|
+
}
|
|
74
92
|
}
|
|
93
|
+
if(Buffer.byteLength(buffer,'utf8')>2*1024*1024)
|
|
94
|
+
failProbe('MCP_PROBE_FRAME_TOO_LARGE');
|
|
75
95
|
});
|
|
76
|
-
child.stderr.on('data',
|
|
77
|
-
child.
|
|
78
|
-
child.
|
|
96
|
+
child.stderr.on('data',()=>{}); // Never retain private child diagnostics.
|
|
97
|
+
child.stdout.on('error',()=>failProbe('MCP_PROBE_TRANSPORT_FAILED'));
|
|
98
|
+
child.stderr.on('error',()=>{});
|
|
99
|
+
child.stdin.on('error',()=>failProbe('MCP_PROBE_TRANSPORT_FAILED'));
|
|
100
|
+
child.once('error',()=>failProbe('MCP_PROBE_TRANSPORT_FAILED'));
|
|
101
|
+
child.once('exit',code=>failProbe(code===0?'MCP_PROBE_EXIT':'MCP_PROBE_EXIT_FAILED'));
|
|
79
102
|
const request=(method,params={})=>new Promise((resolve,reject)=>{
|
|
103
|
+
if(protocolFailure)return reject(Object.assign(
|
|
104
|
+
Error(protocolFailure),{code:protocolFailure}));
|
|
80
105
|
const id=++nextId;
|
|
81
|
-
const timer=setTimeout(()=>{waiting.delete(id);reject(
|
|
106
|
+
const timer=setTimeout(()=>{waiting.delete(id);reject(Object.assign(
|
|
107
|
+
Error('MCP_PROBE_TIMEOUT'),{code:'MCP_PROBE_TIMEOUT'}))},8000);
|
|
82
108
|
waiting.set(id,{resolve,reject,timer});
|
|
83
|
-
child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n')
|
|
109
|
+
try{child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n')}
|
|
110
|
+
catch{waiting.delete(id);clearTimeout(timer);reject(Object.assign(
|
|
111
|
+
Error('MCP_PROBE_TRANSPORT_FAILED'),{code:'MCP_PROBE_TRANSPORT_FAILED'}))}
|
|
84
112
|
});
|
|
85
113
|
try{
|
|
86
114
|
const meta={
|
|
@@ -138,10 +166,19 @@ export async function verifyMcpTools(p,ports={}){
|
|
|
138
166
|
if(!docHtml.includes('chat_loop_document__render')||!docHtml.includes('复制全文'))
|
|
139
167
|
throw Object.assign(Error('MCP_PROBE_DOCUMENT_APP_OUTDATED'),{
|
|
140
168
|
code:'MCP_PROBE_DOCUMENT_APP_OUTDATED'});
|
|
169
|
+
// A corrupt frame in the same stdout chunk as the final reply must not
|
|
170
|
+
// be masked by a previously resolved request promise.
|
|
171
|
+
if(protocolFailure)throw Object.assign(
|
|
172
|
+
Error(protocolFailure),{code:protocolFailure});
|
|
141
173
|
return {ok:true,toolCount:names.length,formResource:uri,documentResource:docUri};
|
|
142
174
|
}finally{
|
|
143
175
|
try{child.stdin.end();child.kill('SIGTERM')}catch{}
|
|
144
|
-
|
|
145
|
-
new Promise(resolve=>
|
|
176
|
+
if(child.exitCode===null&&child.signalCode===null)
|
|
177
|
+
await Promise.race([new Promise(resolve=>child.once('exit',resolve)),
|
|
178
|
+
new Promise(resolve=>setTimeout(resolve,1000))]);
|
|
179
|
+
// The probe owns this exact child. Never leave an unresponsive candidate
|
|
180
|
+
// running after its health result has been returned or rejected.
|
|
181
|
+
if(child.exitCode===null&&child.signalCode===null)
|
|
182
|
+
try{child.kill('SIGKILL')}catch{}
|
|
146
183
|
}
|
|
147
184
|
}
|
|
@@ -10,8 +10,7 @@ const delay=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
|
10
10
|
export function activeDesktopCommands(oldStatus){
|
|
11
11
|
const dc=oldStatus?.results?.find(x=>x.toolId==='desktop-commander');
|
|
12
12
|
if(!dc?.pid){
|
|
13
|
-
//
|
|
14
|
-
if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return [];
|
|
13
|
+
// No environment variable may bypass the real owner identity gate.
|
|
15
14
|
throw Object.assign(Error('TOOL_PROCESS_ID_UNVERIFIED'),
|
|
16
15
|
{code:'TOOL_PROCESS_ID_UNVERIFIED'});
|
|
17
16
|
}
|
package/lib/release-upgrade.mjs
CHANGED
|
@@ -289,9 +289,13 @@ export async function upgradeRuntime(options={}){
|
|
|
289
289
|
code:'NEW_RUNTIME_TUNNEL_UNHEALTHY'
|
|
290
290
|
});
|
|
291
291
|
phase='verify-tunnel-connection';
|
|
292
|
-
|
|
292
|
+
// Production uses the real probes. Isolated tests inject their fake probes
|
|
293
|
+
// explicitly; process environment can never turn off a release gate.
|
|
294
|
+
const tunnelProbe=options.probes?.tunnelConnection??verifyTunnelConnection;
|
|
295
|
+
const mcpProbe=options.probes?.mcpTools??verifyMcpTools;
|
|
296
|
+
const tunnelConnection=await tunnelProbe(p,verified,{run,runtimeLaunchEnv});
|
|
293
297
|
phase='verify-mcp';
|
|
294
|
-
const mcp=await
|
|
298
|
+
const mcp=await mcpProbe(p,{runtimeLaunchEnv});
|
|
295
299
|
phase='record-new';
|
|
296
300
|
atomicWrite(p.current,JSON.stringify({version:p.version,entry:p.entry,
|
|
297
301
|
status:'ACTIVE'},null,2)+'\n');
|
package/lib/release.mjs
CHANGED
|
@@ -140,14 +140,35 @@ function atomicWrite(path,content){
|
|
|
140
140
|
function run(bin,args,opts={}){
|
|
141
141
|
return new Promise((resolve,reject)=>{
|
|
142
142
|
const child=spawn(bin,args,{env:opts.env||process.env,stdio:['ignore','pipe','pipe'],windowsHide:true});
|
|
143
|
-
let stdout='',stderr='';
|
|
143
|
+
let stdout='',stderr='',bytes=0,overflow=false,killTimer=null;
|
|
144
144
|
child.stdout.setEncoding('utf8');
|
|
145
145
|
child.stderr.setEncoding('utf8');
|
|
146
|
-
child.stdout.on('data',
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
146
|
+
child.stdout.on('data',chunk=>{
|
|
147
|
+
if(overflow)return;
|
|
148
|
+
bytes+=Buffer.byteLength(chunk,'utf8');
|
|
149
|
+
if(bytes>2*1024*1024){
|
|
150
|
+
// Upgrade probes are bounded. A truncated CLI reply is never a
|
|
151
|
+
// confirmed success, even when a candidate has already started.
|
|
152
|
+
overflow=true;child.kill('SIGTERM');
|
|
153
|
+
killTimer=setTimeout(()=>child.kill('SIGKILL'),2000);
|
|
154
|
+
killTimer.unref?.();
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
stdout+=chunk;
|
|
158
|
+
});
|
|
159
|
+
child.stderr.on('data',chunk=>{stderr=(stderr+chunk).slice(-2048)});
|
|
160
|
+
child.once('error',error=>{
|
|
161
|
+
if(killTimer)clearTimeout(killTimer);
|
|
162
|
+
reject(error);
|
|
163
|
+
});
|
|
164
|
+
child.once('close',code=>{
|
|
165
|
+
if(killTimer)clearTimeout(killTimer);
|
|
166
|
+
if(overflow)return reject(Object.assign(
|
|
167
|
+
Error('RELEASE_COMMAND_OUTPUT_TOO_LARGE'),
|
|
168
|
+
{code:'RELEASE_COMMAND_OUTPUT_TOO_LARGE'}));
|
|
169
|
+
return code===0?resolve(stdout):reject(Object.assign(Error('COMMAND_FAILED'),{
|
|
170
|
+
code:'COMMAND_FAILED',command:args[0],status:code,stdout,detail:stderr.slice(-300)}));
|
|
171
|
+
});
|
|
151
172
|
});
|
|
152
173
|
}
|
|
153
174
|
async function cli(entry,action,opts={}){
|
|
@@ -8,7 +8,7 @@ const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
|
|
|
8
8
|
|
|
9
9
|
export function createSupervisorObservability({
|
|
10
10
|
filePath,rotationEnabled,contextUsageGrant,observationGrants=process.env,
|
|
11
|
-
contract,nonce,processId,
|
|
11
|
+
contract,nonce,processId,error,
|
|
12
12
|
createSupervisorTraceBridge,createTraceWriterImpl=createTraceWriter
|
|
13
13
|
}){
|
|
14
14
|
const traceWriter=createTraceWriterImpl({
|
|
@@ -58,7 +58,7 @@ export function createSupervisorObservability({
|
|
|
58
58
|
?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
|
|
59
59
|
};
|
|
60
60
|
const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
|
|
61
|
-
traceWriter,contract,observationGrants
|
|
61
|
+
traceWriter,contract,error,observationGrants
|
|
62
62
|
});
|
|
63
63
|
|
|
64
64
|
function recordApiObservation(req){
|