@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
package/README.md CHANGED
@@ -62,10 +62,10 @@ activation condition, scoped call adapter and optional CLI commands.
62
62
  The seven built-in Providers are:
63
63
 
64
64
  - `desktop`: allowlisted Desktop Commander tools and isolated fixtures
65
- - `extension`: official pinned Extension CLI and nine scoped actions
65
+ - `extension`: nine scoped actions delegated to the official Extension CLI, currently resolved through npm `@latest` per invocation (a mutable dist-tag, not a pinned runtime/Chrome version); the received CLI contract must be verified independently. Timeout, missing/invalid CLI identity, and malformed action results return `EXTENSION_RESULT_UNKNOWN`, never a safe-to-retry send failure; the actual Chrome-loaded Owner/version still require separate verification
66
66
  - `runtime`: exact-request receipt lookup without replay
67
67
  - `context`: independent Context SDK read/write schemas and fixed CLI
68
- - `trace`: Project-scoped diagnosis and SOFT stage observations, plus a bearer-token-scoped Form Trace lookup using the Prepare `traceRef`
68
+ - `trace`: Project-scoped diagnosis and SOFT stage observations; an independent `api_system` lookup can correlate an individual Form/Document App using its opaque `traceRef` returned by Prepare/Show. These are soft API/UI observations, not authenticated clicks or business approvals.
69
69
  - Document: independent generic read-only MCP App (show/render). Caller controls title, content and open-ended format; reader safely renders supported formats and retains the original source for one-click copy, with a source fallback for other formats. It does not create a business template, approval, Form or new Chat message.
70
70
  - Form: stateless, generic single-select MCP App. Prepare accepts only caller-defined options and optional conditional text input; it preserves or generates formId and returns a random traceRef. It never accepts, stores, renders or copies a business document: the caller presents R/P separately using the generic Document App. Render acknowledges the UI; Submit returns selected value/label and optional text. ui/update-model-context makes a result available to future model turns but does not trigger one or prove approval. Form does not send Chat messages, interpret decisions, call Context or impose expiry. Prepare/Render/Submit observations are correlated by formId and traceRef without altering results.
71
71
 
@@ -126,6 +126,10 @@ SourceUnit files remain migration evidence, not alternate current facts.
126
126
  - `npm test` runs isolated package and Gateway regression tests.
127
127
  - Workspace `npm run check` verifies API boundaries, source syntax,
128
128
  documentation links, and both Context/Tools generated compositions.
129
+ Its default repository checker also invokes `test/plugin-contract.test.mjs`
130
+ through `node --test`. Use the root `npm run check:static` to run those
131
+ source/manifest guards **without executing test cases**; the default
132
+ `npm run check` retains the contract test for normal release validation.
129
133
  - Workspace `npm run pack:tools -- <existing-output-directory>` produces
130
134
  an offline, version-pinned Tools tarball containing the declared Context
131
135
  and Trace SDKs **plus their verified runtime dependency closure**
package/bin/cli.mjs CHANGED
@@ -60,7 +60,10 @@ function inspect(){
60
60
  async function connectOrLaunch(request){
61
61
  try{return await talk(request,request.deadlineMs+2000);}
62
62
  catch(err){
63
- if(!['ENOENT','ECONNREFUSED','TIMEOUT','UNKNOWN_RESULT'].includes(err.code))throw err;
63
+ // Only a connection failure before the request reaches a Supervisor
64
+ // permits launching one. TIMEOUT/UNKNOWN_RESULT may have already caused
65
+ // a side effect and must not be replayed in a replacement process.
66
+ if(!['ENOENT','ECONNREFUSED'].includes(err.code))throw err;
64
67
  }
65
68
  ensurePrivateDir();
66
69
  try{await recoverStaleLock();}
@@ -69,7 +72,9 @@ async function connectOrLaunch(request){
69
72
  if(err.message!=='Owner may still be alive')throw err;
70
73
  for(let i=0;i<50;i++){
71
74
  await new Promise(resolve=>setTimeout(resolve,65));
72
- try{return await talk(request);}catch(e){if(e.code==='INCOMPATIBLE_VERSION')throw e;}
75
+ try{return await talk(request);}catch(e){
76
+ if(!['ENOENT','ECONNREFUSED'].includes(e.code))throw e;
77
+ }
73
78
  }
74
79
  throw Object.assign(new Error('Owner alive, IPC unavailable'),{code:'MANAGER_UNAVAILABLE'});
75
80
  }
@@ -82,7 +87,7 @@ async function connectOrLaunch(request){
82
87
  try{return await talk(request,request.deadlineMs+2000);}
83
88
  catch(err){
84
89
  last=err;
85
- if(err.code==='INCOMPATIBLE_VERSION')throw err;
90
+ if(!['ENOENT','ECONNREFUSED'].includes(err.code))throw err;
86
91
  }
87
92
  }
88
93
  throw Object.assign(new Error('Supervisor did not become ready'),{code:last?.code||'MANAGER_UNAVAILABLE'});
@@ -115,8 +120,10 @@ async function runControl(action=command, params=extra){
115
120
  }catch(err){
116
121
  const known=['INCOMPATIBLE_VERSION','MANAGER_UNAVAILABLE',
117
122
  'INSECURE_STATE_DIR','TIMEOUT','UNKNOWN_RESULT'];
118
- reply=fail(known.includes(err.code)?err.code:'MANAGER_UNAVAILABLE',
119
- action,target,requestId);
123
+ const code=['INVALID_REPLY','EPIPE','ECONNRESET','ECONNABORTED']
124
+ .includes(err.code)?'UNKNOWN_RESULT'
125
+ :known.includes(err.code)?err.code:'MANAGER_UNAVAILABLE';
126
+ reply=fail(code,action,target,requestId);
120
127
  }
121
128
  emit(reply);process.exitCode=exitCode(reply);
122
129
  }
package/index.mjs CHANGED
@@ -135,9 +135,14 @@ async function runtime(){
135
135
  return platformProvider;
136
136
  }
137
137
  });
138
- mcpChild.configureMcpChild({paths:control.paths,
139
- toolCallDeadlineMs:control.toolCallDeadlineMs,
140
- PACKAGE_VERSION:control.PACKAGE_VERSION});
138
+ // The compiled Desktop Provider owns the only public allowlist. Reuse it
139
+ // for child handshake without coupling to vendor-only tools.
140
+ const desktopNamePrefix='desktop_commander__';
141
+ const allowedDesktopNames=providerDefinitions.find(p=>p.id==='desktop')
142
+ ?.names.filter(n=>n.startsWith(desktopNamePrefix))
143
+ .map(n=>n.slice(desktopNamePrefix.length))??[];
144
+ mcpChild.configureMcpChild({toolCallDeadlineMs:control.toolCallDeadlineMs,
145
+ PACKAGE_VERSION:control.PACKAGE_VERSION,allowedDesktopNames});
141
146
  tunnelAdapter.configureTunnelAdapter({paths:control.paths,
142
147
  bundledTunnel:tunnel.bundledTunnel});
143
148
  adapters.configureAdapterFactory({
@@ -241,7 +246,12 @@ async function runtime(){
241
246
  void drainAudit();
242
247
  const mcpAudit=createApiAspect('@tomflow/chatloop-tools',
243
248
  {sink:recordApi});
249
+ // Only declared providers may create a per-tool observation wrapper.
250
+ // Unknown tool names must not grow a process-lifetime cache.
251
+ const declaredToolNames=new Set(providerDefinitions.flatMap(p=>p.names));
244
252
  const callCache=new Map();
253
+ const unknownToolCall=mcpAudit.observe('mcp.unknown_tool',
254
+ coreToolRouter.call,'mcp');
245
255
  const toolRouter=Object.freeze({
246
256
  list:mcpAudit.observe('mcp.tools.list',coreToolRouter.list,'mcp'),
247
257
  listResources:mcpAudit.observe('mcp.resources.list',
@@ -249,12 +259,11 @@ async function runtime(){
249
259
  readResource:mcpAudit.observe('mcp.resources.read',
250
260
  coreToolRouter.readResource,'mcp'),
251
261
  call(name,args){
252
- const label=typeof name==='string'&&
253
- /^[a-z][A-Za-z0-9_.:-]{1,119}$/.test(name)?name:'invalid';
254
- if(!callCache.has(label))
255
- callCache.set(label,mcpAudit.observe('mcp.'+label,
262
+ if(!declaredToolNames.has(name))return unknownToolCall(name,args);
263
+ if(!callCache.has(name))
264
+ callCache.set(name,mcpAudit.observe('mcp.'+name,
256
265
  coreToolRouter.call,'mcp'));
257
- return callCache.get(label)(name,args);
266
+ return callCache.get(name)(name,args);
258
267
  }
259
268
  });
260
269
  gateway.configureGateway({
@@ -297,6 +306,21 @@ async function runtime(){
297
306
  // Public SDK entry with explicitly separated runtime roles.
298
307
  async function loadToolsCliCore(){
299
308
  const {control,tunnel,tunnelAuth,release,gateway}=await runtime();
309
+ // The root SDK is public. Never forward internal release test ports into the
310
+ // safety-critical cutover function; the official pinned artifact is mandatory.
311
+ const upgradeRuntime=async options=>{
312
+ const allowed=new Set(['args','requirePrepared','expectedArtifactSha256']);
313
+ if(!options||typeof options!=='object'||Array.isArray(options)
314
+ ||Object.keys(options).some(key=>!allowed.has(key)))
315
+ return {command:'upgrade',status:'BLOCKED',code:'INVALID_ARGUMENT'};
316
+ if(options.requirePrepared!==true||!Array.isArray(options.args)
317
+ ||options.args.length!==0
318
+ ||typeof options.expectedArtifactSha256!=='string'
319
+ ||!/^[a-f0-9]{64}$/.test(options.expectedArtifactSha256))
320
+ return {command:'upgrade',status:'BLOCKED',code:'RELEASE_ARTIFACT_PIN_REQUIRED'};
321
+ return release.upgradeRuntime({args:[],requirePrepared:true,
322
+ expectedArtifactSha256:options.expectedArtifactSha256});
323
+ };
300
324
  return apiAspect.methods(Object.freeze({
301
325
  [INTERNAL_DRAIN]:drainCliTelemetry,
302
326
  cliExtensions:apiAspect.methods(createCliCommandRouter(providerDefinitions),
@@ -322,7 +346,7 @@ async function loadToolsCliCore(){
322
346
  tunnelDoctor:tunnel.tunnelDoctor,runTunnel:tunnel.runTunnel,
323
347
  promptTunnelRuntimeKey:tunnelAuth.promptTunnelRuntimeKey,
324
348
  storeTunnelRuntimeKey:tunnelAuth.storeTunnelRuntimeKey,
325
- upgradeRuntime:release.upgradeRuntime,
349
+ upgradeRuntime,
326
350
  runtimeNeedsUpgrade:release.runtimeNeedsUpgrade,
327
351
  prepareReleaseCandidate:release.prepareReleaseCandidate
328
352
  }), 'tools','sdk');
@@ -6,13 +6,22 @@ import {randomUUID} from 'node:crypto';
6
6
  import {userInfo} from 'node:os';
7
7
  // All internal dependencies are supplied as API contracts by index.mjs.
8
8
  // Private modules never import or resolve another private implementation.
9
- let paths, toolCallDeadlineMs, PACKAGE_VERSION;
9
+ let toolCallDeadlineMs, PACKAGE_VERSION, approvedNames, expectedPublished;
10
10
  let connected=false;
11
11
  export function configureMcpChild(ports){
12
12
  if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
13
- for(const name of ['paths', 'toolCallDeadlineMs', 'PACKAGE_VERSION'])
13
+ for(const name of ['toolCallDeadlineMs','PACKAGE_VERSION','allowedDesktopNames'])
14
14
  if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
15
- ({paths, toolCallDeadlineMs, PACKAGE_VERSION}=ports);
15
+ const names=ports.allowedDesktopNames;
16
+ if(!Array.isArray(names)||!names.length||names.some(n=>typeof n!=='string')
17
+ ||new Set(names).size!==names.length)
18
+ throw Error('TOOLS_DESKTOP_ALLOWLIST_INVALID');
19
+ approvedNames=new Set(names);
20
+ const published=catalog.filter(t=>approvedNames.has(t.name));
21
+ if(published.length!==approvedNames.size)
22
+ throw Error('TOOLS_DESKTOP_CATALOG_MISMATCH');
23
+ expectedPublished=fingerprint(published);
24
+ ({toolCallDeadlineMs, PACKAGE_VERSION}=ports);
16
25
  connected=true;
17
26
  }
18
27
 
@@ -20,12 +29,19 @@ export function configureMcpChild(ports){
20
29
  const require=createRequire(import.meta.url);
21
30
  const catalog=JSON.parse(readFileSync(new URL('../desktop-commander-tools.json',import.meta.url),'utf8'));
22
31
  const fingerprint=tools=>JSON.stringify(tools.map(({name,inputSchema})=>({name,inputSchema})));
23
- const expected=fingerprint(catalog);
32
+ function publishedSchemaMatches(listed){
33
+ const published=Array.isArray(listed?.tools)
34
+ ?listed.tools.filter(t=>approvedNames.has(t?.name)):null;
35
+ return published!==null&&fingerprint(published)===expectedPublished;
36
+ }
24
37
  const err=code=>({code});
38
+ const RESPONSE_ID=/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
39
+ const MAX_PENDING_REPLIES=128;
40
+ const READ_ONLY_NAMES=new Set(['read_file','read_multiple_files','list_directory',
41
+ 'get_file_info','list_sessions','list_processes']);
25
42
  const result=(tool,before,after,outcome,error=null,pid=null,evidence=null)=>({toolId:tool.id,enabled:tool.enabled,before,after,outcome,pid,evidence,error});
26
43
  // Deadlines bound an individual caller's wait, not a child process' lifetime.
27
44
  const timeout=ctx=>Math.max(0,ctx.remaining());
28
- export const startupHandshakeBudget=ctx=>Math.max(0,ctx.remaining());
29
45
  // The Tools-owned Desktop Commander is an ordinary MCP child process of the
30
46
  // logged-in macOS account. No synthetic HOME and no GUI Terminal app.
31
47
  export function desktopCommanderEnvironment(parent=process.env,account=userInfo()){
@@ -48,14 +64,29 @@ export function createMcpChildAdapter({records,log},options={}){
48
64
  return new Promise((resolve,reject)=>{
49
65
  if(rec.exited||!rec.child.stdin.writable)return reject(Object.assign(Error('Closed'),{code:'TOOL_UNAVAILABLE'}));
50
66
  if(ms!==null&&ms<1)return reject(Object.assign(Error('Caller deadline'),{code:'TIMEOUT'}));
67
+ // A never-replying child may retain timed-out read-only probes for
68
+ // original-request correlation. Bound those callbacks without evicting
69
+ // unknown effects or dispatching another operation.
70
+ if(rec.pending.size>=MAX_PENDING_REPLIES)
71
+ return reject(Object.assign(Error('Pending MCP replies exhausted'),
72
+ {code:'MCP_PENDING_CAPACITY'}));
51
73
  const id=randomUUID();
52
74
  let settled=false, timer;
53
75
  const finish=(error,value)=>{
54
76
  clearTimeout(timer);
55
77
  rec.pending.delete(id);
56
78
  if(rec.unconfirmed.delete(id)){
57
- log('late-mcp-reply',{toolId:rec.toolId,requestId:id});
58
- if(onLate)onLate(error,value);
79
+ // An observer is not a second child-result authority. Failure to
80
+ // diagnose a late receipt must never crash the owned MCP process
81
+ // callback or erase the authoritative original request outcome.
82
+ try{
83
+ log('late-mcp-reply',{toolId:rec.toolId,requestId:id});
84
+ onLate?.(error,value);
85
+ }catch{
86
+ try{log('late-mcp-observation-gap',{toolId:rec.toolId,
87
+ status:'UNKNOWN',errorCode:'LATE_RECEIPT_OBSERVATION_FAILED'})}
88
+ catch{}
89
+ }
59
90
  }
60
91
  if(settled)return;
61
92
  settled=true;
@@ -73,37 +104,107 @@ export function createMcpChildAdapter({records,log},options={}){
73
104
  }else rec.pending.delete(id);
74
105
  reject(Object.assign(Error('Caller deadline'),{code:'TIMEOUT'}));
75
106
  },ms);
76
- rec.child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n',e=>{
77
- if(e&&rec.pending.has(id))finish(Object.assign(e,{code:'TOOL_UNAVAILABLE'}));
78
- });
107
+ const writeFailed=()=>{
108
+ if(!rec.pending.has(id))return;
109
+ if(method!=='tools/call'){
110
+ finish(Object.assign(Error('MCP transport unavailable'),
111
+ {code:'TOOL_UNAVAILABLE'}));
112
+ return;
113
+ }
114
+ // A failed pipe write can still be partially dispatched. Keep the
115
+ // exact pending ID and late-reply callback: the caller returns UNKNOWN,
116
+ // not a retryable failure, and later mutations stay fenced.
117
+ rec.state='UNKNOWN';
118
+ rec.unconfirmed.add(id);
119
+ clearTimeout(timer);
120
+ if(!settled){
121
+ settled=true;
122
+ reject(Object.assign(Error('MCP tool result unconfirmed'),
123
+ {code:'UNKNOWN_RESULT'}));
124
+ }
125
+ };
126
+ try{
127
+ rec.child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n',e=>{
128
+ if(e)writeFailed();
129
+ });
130
+ }catch{writeFailed()}
79
131
  });
80
132
  }
81
133
  function setup(tool,child){
82
- const rec={child,toolId:tool.id,pid:child.pid,state:'STARTING',exited:false,pending:new Map(),unconfirmed:new Set(),active:0};
134
+ const rec={child,toolId:tool.id,pid:child.pid,state:'STARTING',
135
+ exited:false,protocolFailed:false,pending:new Map(),
136
+ unconfirmed:new Set(),active:0};
83
137
  records.set(tool.id,rec);
84
138
  let buffer='';
139
+ const protocolFailure=code=>{
140
+ if(rec.protocolFailed)return;
141
+ rec.protocolFailed=true;
142
+ rec.state='UNKNOWN';
143
+ buffer='';
144
+ log('child-protocol-failure',{toolId:tool.id,status:'UNKNOWN',errorCode:code});
145
+ // A truncated or malformed reply does not prove a timed-out action
146
+ // failed. Settle pending callers without inventing a business result.
147
+ for(const settle of rec.pending.values())
148
+ settle(Object.assign(Error('Unverified MCP reply'),{code}));
149
+ };
85
150
  child.stdout.setEncoding('utf8'); // MCP JSON may split multibyte tool results.
86
151
  child.stdout.on('data',chunk=>{
152
+ if(rec.protocolFailed)return;
87
153
  buffer+=chunk;
88
- if(Buffer.byteLength(buffer,'utf8')>4*1024*1024){rec.state='UNKNOWN';buffer='';return;}
89
154
  let end;
90
155
  while((end=buffer.indexOf('\n'))>=0){
91
156
  const line=buffer.slice(0,end);buffer=buffer.slice(end+1);
92
- let packet;try{packet=JSON.parse(line);}catch{continue;}
157
+ if(!line.trim())continue;
158
+ if(Buffer.byteLength(line,'utf8')>4*1024*1024){
159
+ protocolFailure('UNKNOWN_RESULT');return;
160
+ }
161
+ let packet;try{packet=JSON.parse(line)}catch{
162
+ protocolFailure('UNKNOWN_RESULT');return;
163
+ }
164
+ if(!packet||typeof packet!=='object'||Array.isArray(packet)
165
+ ||packet.jsonrpc!=='2.0'){
166
+ protocolFailure('UNKNOWN_RESULT');return;
167
+ }
93
168
  if(packet.id!==undefined){
94
- const cb=rec.pending.get(String(packet.id));
95
- if(cb)packet.error?cb(Object.assign(Error(packet.error.message||'MCP error'),{code:'MCP_ERROR'})):
169
+ // No server-initiated request or ambiguous result/error frame may
170
+ // impersonate a reply to an in-flight local tool operation.
171
+ if(typeof packet.id!=='string'||!RESPONSE_ID.test(packet.id)
172
+ ||Object.hasOwn(packet,'method')
173
+ ||Object.hasOwn(packet,'result')===Object.hasOwn(packet,'error')){
174
+ protocolFailure('UNKNOWN_RESULT');return;
175
+ }
176
+ const cb=rec.pending.get(packet.id);
177
+ if(cb)packet.error?cb(Object.assign(Error('MCP error'),{code:'MCP_ERROR'})):
96
178
  cb(null,packet.result);
97
179
  }
98
180
  }
181
+ if(Buffer.byteLength(buffer,'utf8')>4*1024*1024){
182
+ protocolFailure('UNKNOWN_RESULT');
183
+ }
184
+ });
185
+ child.stdout.on('error',()=>{
186
+ protocolFailure('UNKNOWN_RESULT');
187
+ });
188
+ child.stdin.on('error',()=>{
189
+ protocolFailure('UNKNOWN_RESULT');
99
190
  });
100
191
  child.stderr.on('data',x=>log('child-stderr',{toolId:tool.id,bytes:x.length}));
101
- child.on('error',e=>{log('child-error',{toolId:tool.id,code:e.code});});
102
- child.on('exit',(code,signal)=>{
192
+ child.stderr.on('error',()=>log('child-stderr-unavailable',{toolId:tool.id}));
193
+ function onExit(code,signal){
194
+ if(rec.exited)return;
103
195
  rec.exited=true;rec.state=rec.state==='STOPPING'?'STOPPED':'FAILED';
104
- for(const settle of rec.pending.values())settle(Object.assign(Error('Child exit'),{code:'TOOL_UNAVAILABLE'}));
105
- rec.pending.clear();rec.unconfirmed.clear();log('child-exit',{toolId:tool.id,pid:rec.pid,code,signal});
196
+ for(const settle of rec.pending.values())
197
+ settle(Object.assign(Error('Child exit'),{code:'TOOL_UNAVAILABLE'}));
198
+ rec.pending.clear();rec.unconfirmed.clear();
199
+ log('child-exit',{toolId:tool.id,pid:rec.pid,code,signal});
200
+ }
201
+ child.once('error',e=>{
202
+ log('child-error',{toolId:tool.id,code:e.code});
203
+ onExit(null,null);
106
204
  });
205
+ child.once('exit',onExit);
206
+ // spawn failures may emit error + close, without an exit event.
207
+ child.once('close',onExit);
107
208
  return rec;
108
209
  }
109
210
  async function launch(tool,ctx){
@@ -132,8 +233,9 @@ export function createMcpChildAdapter({records,log},options={}){
132
233
  if(!info?.protocolVersion)throw Object.assign(Error('Handshake failed'),{code:'MCP_HANDSHAKE_FAILED'});
133
234
  child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');
134
235
  const listed=await request(rec,'tools/list',{},null);
135
- if(!listed||fingerprint(listed.tools||[])!==expected)
136
- throw Object.assign(Error('Tool schema changed'),{code:'SCHEMA_MISMATCH'});
236
+ // Only the authorized tools are a public contract; extras are unreachable.
237
+ if(!publishedSchemaMatches(listed))
238
+ throw Object.assign(Error('Published tool schema changed'),{code:'SCHEMA_MISMATCH'});
137
239
  if(rec.exited||rec.state==='STOPPING')return result(tool,before,'FAILED','START_FAILED',err('CHILD_EXIT'),rec.pid);
138
240
  rec.state='RUNNING';log('tool-start',{requestId:ctx.requestId,toolId:tool.id,pid:rec.pid});
139
241
  return result(tool,before,'RUNNING','STARTED',null,rec.pid,'MCP_TOOLS_LIST');
@@ -163,13 +265,16 @@ export function createMcpChildAdapter({records,log},options={}){
163
265
  const rec=records.get(tool.id);
164
266
  if(!rec)return result(tool,'STOPPED','STOPPED','OBSERVED',null,null,'NO_OWNED_PROCESS');
165
267
  if(rec.exited)return result(tool,rec.state,rec.state,'OBSERVED',null,null,'CHILD_EXIT');
268
+ if(rec.protocolFailed)return result(tool,rec.state,'UNKNOWN','OBSERVED',
269
+ err('UNKNOWN_RESULT'),rec.pid,'MCP_REPLY_UNVERIFIED');
166
270
  if(rec.state==='STARTING')return result(tool,'STARTING','STARTING','OBSERVED',null,rec.pid,'MCP_INITIALIZING');
167
271
  if(rec.state!=='RUNNING'&&rec.state!=='UNKNOWN')return result(tool,rec.state,'UNKNOWN','OBSERVED',err('UNKNOWN_RESULT'),rec.pid);
168
272
  if(rec.unconfirmed.size)return result(tool,'RUNNING','DEGRADED','OBSERVED',err('OPERATION_UNCONFIRMED'),rec.pid,'MCP_REPLY_PENDING');
169
273
  if(rec.active)return result(tool,'RUNNING','DEGRADED','OBSERVED',err('ACTIVE_REQUESTS'),rec.pid,'MCP_CALL_IN_FLIGHT');
170
274
  try{
171
275
  const listed=await request(rec,'tools/list',{},Math.min(timeout(ctx),1000));
172
- if(fingerprint(listed.tools||[])!==expected)throw Object.assign(Error('Changed schema'),{code:'SCHEMA_MISMATCH'});
276
+ if(!publishedSchemaMatches(listed))
277
+ throw Object.assign(Error('Changed published schema'),{code:'SCHEMA_MISMATCH'});
173
278
  rec.state='RUNNING';return result(tool,'RUNNING','RUNNING','OBSERVED',null,rec.pid,'MCP_TOOLS_LIST');
174
279
  }catch(e){
175
280
  // One unanswered health probe does not mutate the running child state.
@@ -194,15 +299,22 @@ export function createMcpChildAdapter({records,log},options={}){
194
299
  return result(tool,before,'STOPPED','STOPPED',null,null,'EXIT_CONFIRMED');
195
300
  }
196
301
  async function call(tool,name,args,ctx){
302
+ // Enforce the exact MCP Provider allowlist at the execution boundary,
303
+ // not only at tools/list. Authenticated local IPC cannot invoke hidden
304
+ // vendor tools through this child adapter.
305
+ if(!approvedNames.has(name))
306
+ throw Object.assign(Error('Unpublished tool'),{code:'UNKNOWN_TOOL'});
197
307
  const rec=records.get(tool.id);
198
- if(!rec||rec.exited||rec.state!=='RUNNING')throw Object.assign(Error('Not running'),{code:'TOOL_UNAVAILABLE'});
199
- if(!catalog.some(t=>t.name===name))throw Object.assign(Error('No such tool'),{code:'UNKNOWN_TOOL'});
200
- // A prior timed-out write may still be running. Read-only probes may still
201
- // proceed, but never enqueue another uncertain mutating operation.
202
- const harmless=new Set(['read_file','read_multiple_files','list_directory','get_file_info',
203
- 'list_sessions','list_processes','get_usage_stats','get_recent_tool_calls']);
204
- if(rec.unconfirmed.size&&!harmless.has(name))
205
- throw Object.assign(Error('Previous request outcome unconfirmed'),{code:'OPERATION_UNCONFIRMED'});
308
+ if(!rec||rec.exited)
309
+ throw Object.assign(Error('Not running'),{code:'TOOL_UNAVAILABLE'});
310
+ // Report the original write uncertainty before generic health status.
311
+ // A pipe failure may have changed the child to UNKNOWN without resolving
312
+ // its original business operation; never conceal that behind UNAVAILABLE.
313
+ if(rec.unconfirmed.size&&!READ_ONLY_NAMES.has(name))
314
+ throw Object.assign(Error('Previous request outcome unconfirmed'),
315
+ {code:'OPERATION_UNCONFIRMED'});
316
+ if(rec.state!=='RUNNING')
317
+ throw Object.assign(Error('Unverified MCP child state'),{code:'UNKNOWN_RESULT'});
206
318
  rec.active++;
207
319
  try{
208
320
  const ms=Math.max(0,Math.min(ctx.remaining(),toolCallDeadlineMs(args)-2000));
@@ -1,7 +1,7 @@
1
1
  // One Chat Loop-owned tunnel-client child, never Local Dev or a system executable.
2
2
  import {spawn} from 'node:child_process';
3
3
  import {randomUUID} from 'node:crypto';
4
- import {existsSync,lstatSync,mkdirSync,readFileSync,unlinkSync,writeFileSync} from 'node:fs';
4
+ import {lstatSync,mkdirSync,readFileSync,unlinkSync,writeFileSync} from 'node:fs';
5
5
  import {request as httpRequest} from 'node:http';
6
6
  import {homedir} from 'node:os';
7
7
  import {join} from 'node:path';
@@ -40,6 +40,9 @@ export function gatewayChildSettings(parent=process.env){
40
40
  function probe(socketPath,ms=350){
41
41
  return new Promise(resolve=>{
42
42
  const req=httpRequest({socketPath,path:'/readyz',method:'GET',timeout:ms},res=>{
43
+ // A partial HTTP response must not leave readiness pending forever.
44
+ res.once('error',()=>resolve(false));
45
+ res.once('aborted',()=>resolve(false));
43
46
  res.resume();res.once('end',()=>resolve(res.statusCode===200));
44
47
  });
45
48
  req.once('error',()=>resolve(false));
@@ -50,6 +53,10 @@ function probe(socketPath,ms=350){
50
53
  function safeUnlink(file){
51
54
  try{unlinkSync(file);}catch(e){if(e.code!=='ENOENT')throw e;}
52
55
  }
56
+ function pathPresent(file){
57
+ try{lstatSync(file);return true}
58
+ catch(e){if(e.code==='ENOENT')return false;throw e}
59
+ }
53
60
  export function createTunnelAdapter({records,log,onChildExit=()=>{}},options={}){
54
61
  const locate=options.locate||bundledTunnel;
55
62
  const spawnChild=options.spawnChild||spawn;
@@ -58,18 +65,19 @@ export function createTunnelAdapter({records,log,onChildExit=()=>{}},options={})
58
65
  const dir=join(paths().dir,'tools','tunnel');
59
66
  const marker=join(dir,'owner.json');
60
67
  const socket=join(dir,'health.sock');
61
- function isMarked(){
62
- try{lstatSync(marker);return true;}
63
- catch(e){if(e.code==='ENOENT')return false;throw e;}
64
- }
68
+ function isMarked(){return pathPresent(marker)}
65
69
  function forget(rec){
66
70
  let owned=false;
67
- try{owned=JSON.parse(readFileSync(marker,'utf8')).nonce===rec.nonce;}
68
- catch{}
71
+ try{
72
+ const st=lstatSync(marker);
73
+ if(st.isFile()&&!st.isSymbolicLink()&&!(st.mode&0o077)
74
+ &&(!process.getuid||st.uid===process.getuid()))
75
+ owned=JSON.parse(readFileSync(marker,'utf8')).nonce===rec.nonce;
76
+ }catch{}
69
77
  // If owner evidence changed, never touch a socket potentially owned by another manager.
70
78
  if(!owned)return;
71
79
  try{
72
- if(existsSync(socket)){
80
+ if(pathPresent(socket)){
73
81
  const stat=lstatSync(socket);
74
82
  if(stat.isSocket()&&(!process.getuid||stat.uid===process.getuid()))safeUnlink(socket);
75
83
  }
@@ -78,8 +86,11 @@ export function createTunnelAdapter({records,log,onChildExit=()=>{}},options={})
78
86
  }
79
87
  function validProfile(){
80
88
  try{
81
- const s=lstatSync(profile);
82
- return s.isFile()&&!s.isSymbolicLink()&&(!process.getuid||s.uid===process.getuid());
89
+ const root=lstatSync(profileDir),s=lstatSync(profile);
90
+ return root.isDirectory()&&!root.isSymbolicLink()&&!(root.mode&0o077)
91
+ &&s.isFile()&&!s.isSymbolicLink()&&!(s.mode&0o077)
92
+ &&(!process.getuid||root.uid===process.getuid()
93
+ &&s.uid===process.getuid());
83
94
  }catch{return false;}
84
95
  }
85
96
  async function inspect(t){
@@ -115,7 +126,7 @@ export function createTunnelAdapter({records,log,onChildExit=()=>{}},options={})
115
126
  if(!ds.isDirectory()||ds.isSymbolicLink()||(ds.mode&0o077)||
116
127
  (process.getuid&&ds.uid!==process.getuid()))
117
128
  return result(t,before,'UNKNOWN','START_FAILED',err('INSECURE_STATE_DIR'));
118
- if(existsSync(socket))return result(t,before,'UNKNOWN','OWNERSHIP_UNCERTAIN',err('OWNERSHIP_UNCERTAIN'),null,'STALE_HEALTH_SOCKET');
129
+ if(pathPresent(socket))return result(t,before,'UNKNOWN','OWNERSHIP_UNCERTAIN',err('OWNERSHIP_UNCERTAIN'),null,'STALE_HEALTH_SOCKET');
119
130
  const nonce=randomUUID();
120
131
  try{writeFileSync(marker,JSON.stringify({nonce,created:Date.now(),binary}),{flag:'wx',mode:0o600});}
121
132
  catch{return result(t,before,'UNKNOWN','OWNERSHIP_UNCERTAIN',err('OWNERSHIP_UNCERTAIN'));}
@@ -44,8 +44,3 @@ export function verifyContextEnvelope(req){
44
44
  if(!timingSafeEqual(expected,received))throw fail('CONTEXT_CONTROL_AUTH_FAILED');
45
45
  return req.payload;
46
46
  }
47
- export function signContextEnvelope(payload,requestId,issuedAt=Date.now()){
48
- const signed={contract:'chat-loop.context-control.v1',requestId,issuedAt,payload};
49
- return {...signed,action:'context-control',
50
- mac:sign(loadContextControlSecret(),signed)};
51
- }
@@ -122,6 +122,15 @@ export async function runContextGateway(name,args){
122
122
  if(Buffer.byteLength(request)>5*1024*1024)throw fail('REQUEST_TOO_LARGE');
123
123
  const {bin,args:argv}=invocation();
124
124
  const env={...process.env};
125
+ // Context CLI needs its own scoped Context settings, not Tunnel control
126
+ // credentials, model keys or unrelated process secrets. Do not weaken its
127
+ // exact Context Project grant or its independent write authority.
128
+ for(const key of Object.keys(env)){
129
+ if(key==='CHAT_LOOP_CONTEXT_ADMIN_ENABLE'
130
+ ||/^CHAT_LOOP_TUNNEL_/.test(key)
131
+ ||/(?:^|_)(?:API_KEY|ADMIN_KEY|ACCESS_KEY|TOKEN|SECRET|PASSWORD|PRIVATE_KEY|CREDENTIALS?)(?:_|$)/i.test(key))
132
+ delete env[key];
133
+ }
125
134
  // One opaque correlation carrier, not a permission/identity credential.
126
135
  // It follows the real MCP -> child CLI edge without modifying CLI input.
127
136
  try{
@@ -179,7 +188,11 @@ export async function runContextGateway(name,args){
179
188
  complete(fail('CONTEXT_SDK_VERSION_MISMATCH'));return;
180
189
  }
181
190
  if(response.ok!==true){
182
- complete(fail(response?.error?.code||'CONTEXT_CLI_FAILED'));return;
191
+ // CLI stderr and arbitrary error text are not a public MCP contract.
192
+ // Only a bounded typed code may cross the subprocess boundary.
193
+ const code=CODE.test(response?.error?.code||'')
194
+ ?response.error.code:'CONTEXT_CLI_FAILED';
195
+ complete(fail(code));return;
183
196
  }
184
197
  complete(null,response.result);
185
198
  });
package/lib/control.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import {connect} from 'node:net';
2
- import {existsSync, lstatSync, mkdirSync, readFileSync, statSync, unlinkSync} from 'node:fs';
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
- function lockPresent() {return existsSync(paths().lock);}
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 (!existsSync(p.lock)) return;
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
- if(readFileSync(p.lock,'utf8')!==contents)throw Object.assign(new Error('Owner changed'),{code:'MANAGER_UNAVAILABLE'});
141
- if(existsSync(p.socket)) {
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() || (process.getuid && s.uid!==process.getuid()))throw Object.assign(new Error('Unowned socket'),{code:'MANAGER_UNAVAILABLE'});
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
- ||(reply.providerVersion!==undefined
12
- &&(typeof reply.providerVersion!=='string'||!VERSION.test(reply.providerVersion))))
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??null};
23
+ providerVersion:reply.providerVersion};
22
24
  }