@tomflow/chatloop-tools 0.9.44 → 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.
Files changed (74) hide show
  1. package/README.md +6 -2
  2. package/bin/cli.mjs +12 -5
  3. package/index.mjs +33 -9
  4. package/lib/adapters/mcp-child.mjs +142 -30
  5. package/lib/adapters/tunnel.mjs +22 -11
  6. package/lib/context-control-auth.mjs +0 -5
  7. package/lib/context-gateway.mjs +14 -1
  8. package/lib/control.mjs +27 -8
  9. package/lib/extension-cli-contract.mjs +5 -3
  10. package/lib/extension-proxy.mjs +80 -10
  11. package/lib/gateway.mjs +20 -8
  12. package/lib/release-health-checks.mjs +49 -12
  13. package/lib/release-owner-preflight.mjs +1 -2
  14. package/lib/release-upgrade.mjs +6 -2
  15. package/lib/release.mjs +27 -6
  16. package/lib/supervisor-observability.mjs +2 -2
  17. package/lib/supervisor-runtime.mjs +96 -33
  18. package/lib/trace-gateway.mjs +43 -34
  19. package/lib/tunnel.mjs +15 -5
  20. package/node_modules/@tomflow/chatloop-context/README.md +2 -2
  21. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +1 -1
  22. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +1 -1
  23. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +1 -1
  24. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +2 -7
  25. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +3 -1
  26. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +8 -3
  27. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +13 -7
  28. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +12 -8
  29. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +20 -3
  30. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +8 -4
  31. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +5 -3
  32. package/node_modules/@tomflow/chatloop-context/package.json +3 -3
  33. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +14 -6
  34. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +26 -7
  35. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +6 -3
  36. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +5 -2
  37. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +22 -4
  38. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +19 -4
  39. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +4 -2
  40. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +11 -3
  41. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +2 -1
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +11 -3
  43. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +10 -9
  44. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -1
  45. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +9 -3
  46. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +2 -2
  47. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +8 -10
  48. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +7 -2
  49. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +2 -1
  50. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +7 -1
  51. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +16 -5
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +5 -7
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +12 -3
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +35 -21
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +11 -6
  56. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +11 -3
  57. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +39 -5
  58. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +5 -1
  59. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +5 -1
  60. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +27 -3
  61. package/node_modules/@tomflow/chatloop-extension/package.json +2 -2
  62. package/node_modules/@tomflow/chatloop-trace/README.md +7 -2
  63. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +66 -36
  64. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +17 -4
  65. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +30 -6
  66. package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
  67. package/package.json +6 -6
  68. package/providers/context.mjs +5 -1
  69. package/providers/desktop.mjs +23 -6
  70. package/providers/document.mjs +5 -3
  71. package/providers/extension.mjs +6 -4
  72. package/providers/form.mjs +5 -3
  73. package/providers/runtime.mjs +14 -6
  74. package/providers/trace.mjs +3 -2
@@ -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 timer=setTimeout(()=>{child.kill('SIGTERM');settle(fail('RESULT_TIMEOUT'));},
70
- name==='start'?330000:90000);
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
- settle(result.ok?result.value:fail(result.code),true);
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
- child.kill('SIGTERM');settle(fail('RESULT_TOO_LARGE'));return;
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',()=>settle(fail('EXTENSION_CLI_UNAVAILABLE')));
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
- if(!consume(stdout.trim()))settle(fail('INVALID_EXTENSION_REPLY'));
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
- return formatExtensionResult(name,response);
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 {content:[{type:'text',text:'ACCEPTED_UNVERIFIED: Extension reload requested; healthy restart not confirmed.'}]};
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
- if(proof.status!=='OK'||!proof.sessionId||!proof.activeChatId||!proof.activeChatUrl)
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(['ENOENT','ECONNREFUSED'].includes(e.code)
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
- // MCP input limits are transport bytes, not UTF-16 code units;
101
- // otherwise a large multibyte payload bypasses the 1 MiB boundary.
102
- if(Buffer.byteLength(buf,'utf8')>1024*1024){
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();return;
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
- const task=handledByRouter?invoke():observeProtocol(m.method,invoke);
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='',stderr='',nextId=0;
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
- let packet;try{packet=JSON.parse(line)}catch{continue;}
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){waiting.delete(packet.id);clearTimeout(pending.timer);pending.resolve(packet);}
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',chunk=>{stderr=(stderr+chunk).slice(-2048)});
77
- child.once('error',error=>rejectPending(error));
78
- child.once('exit',code=>rejectPending(Error('MCP_PROBE_EXIT:'+code+':'+stderr.slice(-500))));
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(Error('MCP_PROBE_TIMEOUT:'+method))},8000);
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
- await Promise.race([new Promise(resolve=>child.once('exit',resolve)),
145
- new Promise(resolve=>setTimeout(resolve,1000))]);
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
- // Release tests use a fake old CLI; production must provide real PID.
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
  }
@@ -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
- const tunnelConnection=await verifyTunnelConnection(p,verified,{run,runtimeLaunchEnv});
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 verifyMcpTools(p,{runtimeLaunchEnv});
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',x=>stdout+=x);
147
- child.stderr.on('data',x=>stderr+=x.slice(0,2048));
148
- child.once('error',reject);
149
- child.once('close',code=>code===0?resolve(stdout):reject(Object.assign(Error('COMMAND_FAILED'),{
150
- code:'COMMAND_FAILED',command:args[0],status:code,stdout,detail:stderr.slice(-300)})));
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){