@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.
Files changed (75) hide show
  1. package/README.md +6 -2
  2. package/bin/cli.mjs +12 -5
  3. package/index.mjs +60 -33
  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 +70 -45
  19. package/lib/trace-observation.mjs +5 -3
  20. package/lib/tunnel.mjs +15 -5
  21. package/node_modules/@tomflow/chatloop-context/README.md +2 -2
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +1 -1
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +1 -1
  24. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +1 -1
  25. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +2 -7
  26. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +3 -1
  27. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +8 -3
  28. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +13 -7
  29. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +12 -8
  30. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +20 -3
  31. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +8 -4
  32. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +5 -3
  33. package/node_modules/@tomflow/chatloop-context/package.json +3 -3
  34. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +14 -6
  35. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +26 -7
  36. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +6 -3
  37. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +5 -2
  38. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +22 -4
  39. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +19 -4
  40. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +4 -2
  41. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +11 -3
  42. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +2 -1
  43. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +11 -3
  44. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +10 -9
  45. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -1
  46. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +9 -3
  47. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +2 -2
  48. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +8 -10
  49. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +7 -2
  50. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +2 -1
  51. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +7 -1
  52. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +16 -5
  53. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +5 -7
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +12 -3
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +35 -21
  56. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +11 -6
  57. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +11 -3
  58. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +39 -5
  59. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +5 -1
  60. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +5 -1
  61. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +27 -3
  62. package/node_modules/@tomflow/chatloop-extension/package.json +2 -2
  63. package/node_modules/@tomflow/chatloop-trace/README.md +7 -2
  64. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +66 -36
  65. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +17 -4
  66. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +30 -6
  67. package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
  68. package/package.json +6 -6
  69. package/providers/context.mjs +5 -1
  70. package/providers/desktop.mjs +23 -6
  71. package/providers/document.mjs +31 -5
  72. package/providers/extension.mjs +6 -4
  73. package/providers/form.mjs +5 -3
  74. package/providers/runtime.mjs +14 -6
  75. 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
@@ -13,7 +13,7 @@ import {createCliCommandRouter} from './lib/cli-command-router.mjs';
13
13
  let auditPort=null;
14
14
  const auditBacklog=[];
15
15
  let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0,auditLost=0;
16
- let formObservationLost=0;
16
+ let formObservationLost=0,documentObservationLost=0;
17
17
  const OBSERVER_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;
18
18
  const localError=code=>Object.assign(Error(code),{code});
19
19
  const MAX_AUDIT_BACKLOG=1024,MAX_NO_OWNER_RETRIES=20;
@@ -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({
@@ -168,8 +173,9 @@ async function runtime(){
168
173
  const traceTalk=async request=>{
169
174
  const result=await control.talk(request);
170
175
  if(request?.action!=='__trace_health'||!result?.traceHealth)return result;
171
- const health={...result.traceHealth,formObservationLost};
172
- if(formObservationLost>0&&health.status==='OK')health.status='TRACE_DEGRADED';
176
+ const health={...result.traceHealth,formObservationLost,documentObservationLost};
177
+ if((formObservationLost>0||documentObservationLost>0)
178
+ &&health.status==='OK')health.status='TRACE_DEGRADED';
173
179
  return {...result,traceHealth:health};
174
180
  };
175
181
  traceGateway.configureTraceGateway({paths:control.paths,
@@ -185,29 +191,31 @@ async function runtime(){
185
191
  subscribeContextApiLog(event=>contextGateway.forwardContextApiLog(event));
186
192
  // One statically generated provider composition, shared by tools/list and
187
193
  // tools/call. Adding an independent provider never edits this Gateway.
194
+ const appObserver=(kind,idKey,lost)=>({
195
+ observe:async payload=>{
196
+ const parent=apiAspect.current();
197
+ if(!parent||!OBSERVER_UUID.test(parent.traceId||'')
198
+ ||!OBSERVER_UUID.test(parent.spanId||''))
199
+ throw localError(kind+'_TRACE_PARENT_MISSING');
200
+ const result=await control.talk({
201
+ contract:control.CONTRACT,action:'__trace_observation',
202
+ requestId:randomUUID(),event:payload.event,
203
+ status:payload.status||'CONFIRMED',
204
+ traceId:parent.traceId,spanId:parent.spanId,
205
+ projectRef:'api_system',sessionRef:payload.traceRef,
206
+ evidenceRef:payload[idKey],
207
+ ...(payload.errorCode?{errorCode:payload.errorCode}:{})
208
+ },1800);
209
+ if(result?.status!=='OK'||!OBSERVER_UUID.test(result.eventId||''))
210
+ throw localError(result?.error?.code||kind+'_TRACE_OBSERVATION_UNCONFIRMED');
211
+ return result;
212
+ },lost
213
+ });
188
214
  const coreToolRouter=createMcpToolRouter(providerDefinitions,{
189
215
  control,release:releaseApi,terminal:terminalPolicy,context:contextGateway,
190
- form:{
191
- observe:async payload=>{
192
- const parent=apiAspect.current();
193
- if(!parent||!OBSERVER_UUID.test(parent.traceId||'')
194
- ||!OBSERVER_UUID.test(parent.spanId||''))
195
- throw localError('FORM_TRACE_PARENT_MISSING');
196
- const result=await control.talk({
197
- contract:control.CONTRACT,action:'__trace_observation',
198
- requestId:randomUUID(),event:payload.event,
199
- status:payload.status||'CONFIRMED',
200
- traceId:parent.traceId,spanId:parent.spanId,
201
- projectRef:'api_system',sessionRef:payload.traceRef,
202
- evidenceRef:payload.formId,
203
- ...(payload.errorCode?{errorCode:payload.errorCode}:{})
204
- },1800);
205
- if(result?.status!=='OK'||!OBSERVER_UUID.test(result.eventId||''))
206
- throw localError(result?.error?.code||'FORM_TRACE_OBSERVATION_UNCONFIRMED');
207
- return result;
208
- },
209
- lost:()=>{formObservationLost++}
210
- },trace:traceGateway,
216
+ form:appObserver('FORM','formId',()=>{formObservationLost++}),
217
+ document:appObserver('DOCUMENT','documentId',()=>{documentObservationLost++}),
218
+ trace:traceGateway,
211
219
  extension:{
212
220
  forwardExtensionAction:extensionProxy.forwardExtensionAction,
213
221
  observeExtensionResult:traceGateway.observeExtensionResult
@@ -238,7 +246,12 @@ async function runtime(){
238
246
  void drainAudit();
239
247
  const mcpAudit=createApiAspect('@tomflow/chatloop-tools',
240
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));
241
252
  const callCache=new Map();
253
+ const unknownToolCall=mcpAudit.observe('mcp.unknown_tool',
254
+ coreToolRouter.call,'mcp');
242
255
  const toolRouter=Object.freeze({
243
256
  list:mcpAudit.observe('mcp.tools.list',coreToolRouter.list,'mcp'),
244
257
  listResources:mcpAudit.observe('mcp.resources.list',
@@ -246,12 +259,11 @@ async function runtime(){
246
259
  readResource:mcpAudit.observe('mcp.resources.read',
247
260
  coreToolRouter.readResource,'mcp'),
248
261
  call(name,args){
249
- const label=typeof name==='string'&&
250
- /^[a-z][A-Za-z0-9_.:-]{1,119}$/.test(name)?name:'invalid';
251
- if(!callCache.has(label))
252
- 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,
253
265
  coreToolRouter.call,'mcp'));
254
- return callCache.get(label)(name,args);
266
+ return callCache.get(name)(name,args);
255
267
  }
256
268
  });
257
269
  gateway.configureGateway({
@@ -294,6 +306,21 @@ async function runtime(){
294
306
  // Public SDK entry with explicitly separated runtime roles.
295
307
  async function loadToolsCliCore(){
296
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
+ };
297
324
  return apiAspect.methods(Object.freeze({
298
325
  [INTERNAL_DRAIN]:drainCliTelemetry,
299
326
  cliExtensions:apiAspect.methods(createCliCommandRouter(providerDefinitions),
@@ -319,7 +346,7 @@ async function loadToolsCliCore(){
319
346
  tunnelDoctor:tunnel.tunnelDoctor,runTunnel:tunnel.runTunnel,
320
347
  promptTunnelRuntimeKey:tunnelAuth.promptTunnelRuntimeKey,
321
348
  storeTunnelRuntimeKey:tunnelAuth.storeTunnelRuntimeKey,
322
- upgradeRuntime:release.upgradeRuntime,
349
+ upgradeRuntime,
323
350
  runtimeNeedsUpgrade:release.runtimeNeedsUpgrade,
324
351
  prepareReleaseCandidate:release.prepareReleaseCandidate
325
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
  });