@tomflow/chatloop-tools 0.9.44 → 0.9.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -2
- package/bin/cli.mjs +12 -5
- package/index.mjs +59 -12
- package/lib/adapters/mcp-child.mjs +142 -30
- package/lib/adapters/tunnel.mjs +22 -11
- package/lib/context-control-auth.mjs +0 -5
- package/lib/context-gateway.mjs +14 -1
- package/lib/control.mjs +27 -8
- package/lib/extension-cli-contract.mjs +5 -3
- package/lib/extension-proxy.mjs +80 -10
- package/lib/gateway.mjs +20 -8
- package/lib/release-health-checks.mjs +49 -12
- package/lib/release-owner-preflight.mjs +1 -2
- package/lib/release-upgrade.mjs +6 -2
- package/lib/release.mjs +27 -6
- package/lib/supervisor-observability.mjs +2 -2
- package/lib/supervisor-runtime.mjs +96 -33
- package/lib/trace-gateway.mjs +64 -42
- package/lib/tunnel.mjs +15 -5
- package/node_modules/@tomflow/chatloop-context/README.md +2 -2
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +1 -1
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +1 -1
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +1 -1
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +2 -7
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +3 -1
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +8 -3
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +13 -7
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +12 -8
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +20 -3
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +8 -4
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +5 -3
- package/node_modules/@tomflow/chatloop-context/package.json +3 -3
- package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +14 -6
- package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +26 -7
- package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +6 -3
- package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +5 -2
- package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +22 -4
- package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +19 -4
- package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +4 -2
- package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +11 -3
- package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +2 -1
- package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +11 -3
- package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +10 -9
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -1
- package/node_modules/@tomflow/chatloop-extension/extension/popup.js +9 -3
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +2 -2
- package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +8 -10
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +7 -2
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +2 -1
- package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +7 -1
- package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +16 -5
- package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +5 -7
- package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +12 -3
- package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +35 -21
- package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +11 -6
- package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +11 -3
- package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +39 -5
- package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +5 -1
- package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +5 -1
- package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +27 -3
- package/node_modules/@tomflow/chatloop-extension/package.json +2 -2
- package/node_modules/@tomflow/chatloop-trace/README.md +7 -2
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +66 -36
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +17 -4
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +30 -6
- package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
- package/package.json +9 -9
- package/providers/context.mjs +5 -1
- package/providers/desktop.mjs +23 -6
- package/providers/document.mjs +5 -3
- package/providers/extension.mjs +6 -4
- package/providers/form.mjs +5 -3
- package/providers/runtime.mjs +14 -6
- package/providers/trace.mjs +3 -2
package/README.md
CHANGED
|
@@ -23,6 +23,9 @@ With an exact authorized Context Project grant it also aggregates that
|
|
|
23
23
|
Project's sanitized `context.api` events. Counts, success, failure,
|
|
24
24
|
incomplete calls and calls per minute are grouped by named entrypoint and
|
|
25
25
|
deduplicated by call/span ID; unmatched completions are reported separately.
|
|
26
|
+
An MCP tool response with `isError:true` is recorded as a FAILED API span while
|
|
27
|
+
its original MCP result remains unchanged; unknown tool names use the bounded
|
|
28
|
+
`mcp.unknown_tool` observation, not an invented per-name API.
|
|
26
29
|
Nested calls share a soft `traceId` and retain unique `spanId/parentSpanId`,
|
|
27
30
|
including a sanitized MCP-to-Context-CLI parent handoff.
|
|
28
31
|
It never starts a Supervisor, opens a browser, replays a call, or reads model
|
|
@@ -62,10 +65,10 @@ activation condition, scoped call adapter and optional CLI commands.
|
|
|
62
65
|
The seven built-in Providers are:
|
|
63
66
|
|
|
64
67
|
- `desktop`: allowlisted Desktop Commander tools and isolated fixtures
|
|
65
|
-
- `extension`: official pinned
|
|
68
|
+
- `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
69
|
- `runtime`: exact-request receipt lookup without replay
|
|
67
70
|
- `context`: independent Context SDK read/write schemas and fixed CLI
|
|
68
|
-
- `trace`: Project-scoped diagnosis and SOFT stage observations
|
|
71
|
+
- `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. App kind remains `UNVERIFIED` when no matching event is found. Diagnosis separates `writerHealth` (Supervisor Writer status) from `gatewayHealth` (including process-wide App observation loss); loss counters appear under `globalObservationWarnings` and are never assigned to a particular Project/Form/Document as an invented `gap`. Missing actual App parent API spans remain scoped gaps. A rendered but unsubmitted Form has no submit event to expect. Source event timestamps remain ISO UTC; operator reports must label their display timezone. These are soft API/UI observations, not authenticated clicks, user-message identity or business approvals.
|
|
69
72
|
- 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
73
|
- 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
74
|
|
|
@@ -126,6 +129,10 @@ SourceUnit files remain migration evidence, not alternate current facts.
|
|
|
126
129
|
- `npm test` runs isolated package and Gateway regression tests.
|
|
127
130
|
- Workspace `npm run check` verifies API boundaries, source syntax,
|
|
128
131
|
documentation links, and both Context/Tools generated compositions.
|
|
132
|
+
Its default repository checker also invokes `test/plugin-contract.test.mjs`
|
|
133
|
+
through `node --test`. Use the root `npm run check:static` to run those
|
|
134
|
+
source/manifest guards **without executing test cases**; the default
|
|
135
|
+
`npm run check` retains the contract test for normal release validation.
|
|
129
136
|
- Workspace `npm run pack:tools -- <existing-output-directory>` produces
|
|
130
137
|
an offline, version-pinned Tools tarball containing the declared Context
|
|
131
138
|
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
|
-
|
|
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){
|
|
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
|
|
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
|
-
|
|
119
|
-
|
|
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
|
-
|
|
139
|
-
|
|
140
|
-
|
|
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,7 +173,12 @@ 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
|
-
|
|
176
|
+
// Supervisor Writer health is authoritative for persisted spans.
|
|
177
|
+
// Local App loss counters describe this Gateway process, not the Writer
|
|
178
|
+
// or any individual Form/Document traceRef. Preserve both dimensions.
|
|
179
|
+
const health={...result.traceHealth,
|
|
180
|
+
writerStatus:result.traceHealth.status,
|
|
181
|
+
formObservationLost,documentObservationLost};
|
|
172
182
|
if((formObservationLost>0||documentObservationLost>0)
|
|
173
183
|
&&health.status==='OK')health.status='TRACE_DEGRADED';
|
|
174
184
|
return {...result,traceHealth:health};
|
|
@@ -241,20 +251,42 @@ async function runtime(){
|
|
|
241
251
|
void drainAudit();
|
|
242
252
|
const mcpAudit=createApiAspect('@tomflow/chatloop-tools',
|
|
243
253
|
{sink:recordApi});
|
|
254
|
+
// Only declared providers may create a per-tool observation wrapper.
|
|
255
|
+
// Unknown tool names must not grow a process-lifetime cache.
|
|
256
|
+
const declaredToolNames=new Set(providerDefinitions.flatMap(p=>p.names));
|
|
244
257
|
const callCache=new Map();
|
|
258
|
+
// MCP isError is a legitimate provider result, but it represents a
|
|
259
|
+
// failed tool operation. Observe FAILED without changing the MCP reply.
|
|
260
|
+
const observeTool=name=>mcpAudit.observe(name,async(tool,args)=>{
|
|
261
|
+
const result=await coreToolRouter.call(tool,args);
|
|
262
|
+
if(result?.isError===true){
|
|
263
|
+
const error=Object.assign(Error('MCP_TOOL_ERROR'),{
|
|
264
|
+
code:'MCP_TOOL_ERROR',toolResult:result});
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
return result;
|
|
268
|
+
},'mcp');
|
|
269
|
+
const unknownToolCall=observeTool('mcp.unknown_tool');
|
|
245
270
|
const toolRouter=Object.freeze({
|
|
246
271
|
list:mcpAudit.observe('mcp.tools.list',coreToolRouter.list,'mcp'),
|
|
247
272
|
listResources:mcpAudit.observe('mcp.resources.list',
|
|
248
273
|
coreToolRouter.listResources,'mcp'),
|
|
249
274
|
readResource:mcpAudit.observe('mcp.resources.read',
|
|
250
275
|
coreToolRouter.readResource,'mcp'),
|
|
251
|
-
call(name,args){
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
callCache.
|
|
256
|
-
|
|
257
|
-
return
|
|
276
|
+
async call(name,args){
|
|
277
|
+
let observed=unknownToolCall;
|
|
278
|
+
if(declaredToolNames.has(name)){
|
|
279
|
+
if(!callCache.has(name))callCache.set(name,observeTool('mcp.'+name));
|
|
280
|
+
observed=callCache.get(name);
|
|
281
|
+
}
|
|
282
|
+
try{return await observed(name,args)}
|
|
283
|
+
catch(error){
|
|
284
|
+
// The synthetic observation failure carries the exact existing
|
|
285
|
+
// MCP result; never convert it into a second tool invocation.
|
|
286
|
+
if(error?.code==='MCP_TOOL_ERROR'&&error.toolResult?.isError===true)
|
|
287
|
+
return error.toolResult;
|
|
288
|
+
throw error;
|
|
289
|
+
}
|
|
258
290
|
}
|
|
259
291
|
});
|
|
260
292
|
gateway.configureGateway({
|
|
@@ -297,6 +329,21 @@ async function runtime(){
|
|
|
297
329
|
// Public SDK entry with explicitly separated runtime roles.
|
|
298
330
|
async function loadToolsCliCore(){
|
|
299
331
|
const {control,tunnel,tunnelAuth,release,gateway}=await runtime();
|
|
332
|
+
// The root SDK is public. Never forward internal release test ports into the
|
|
333
|
+
// safety-critical cutover function; the official pinned artifact is mandatory.
|
|
334
|
+
const upgradeRuntime=async options=>{
|
|
335
|
+
const allowed=new Set(['args','requirePrepared','expectedArtifactSha256']);
|
|
336
|
+
if(!options||typeof options!=='object'||Array.isArray(options)
|
|
337
|
+
||Object.keys(options).some(key=>!allowed.has(key)))
|
|
338
|
+
return {command:'upgrade',status:'BLOCKED',code:'INVALID_ARGUMENT'};
|
|
339
|
+
if(options.requirePrepared!==true||!Array.isArray(options.args)
|
|
340
|
+
||options.args.length!==0
|
|
341
|
+
||typeof options.expectedArtifactSha256!=='string'
|
|
342
|
+
||!/^[a-f0-9]{64}$/.test(options.expectedArtifactSha256))
|
|
343
|
+
return {command:'upgrade',status:'BLOCKED',code:'RELEASE_ARTIFACT_PIN_REQUIRED'};
|
|
344
|
+
return release.upgradeRuntime({args:[],requirePrepared:true,
|
|
345
|
+
expectedArtifactSha256:options.expectedArtifactSha256});
|
|
346
|
+
};
|
|
300
347
|
return apiAspect.methods(Object.freeze({
|
|
301
348
|
[INTERNAL_DRAIN]:drainCliTelemetry,
|
|
302
349
|
cliExtensions:apiAspect.methods(createCliCommandRouter(providerDefinitions),
|
|
@@ -322,7 +369,7 @@ async function loadToolsCliCore(){
|
|
|
322
369
|
tunnelDoctor:tunnel.tunnelDoctor,runTunnel:tunnel.runTunnel,
|
|
323
370
|
promptTunnelRuntimeKey:tunnelAuth.promptTunnelRuntimeKey,
|
|
324
371
|
storeTunnelRuntimeKey:tunnelAuth.storeTunnelRuntimeKey,
|
|
325
|
-
upgradeRuntime
|
|
372
|
+
upgradeRuntime,
|
|
326
373
|
runtimeNeedsUpgrade:release.runtimeNeedsUpgrade,
|
|
327
374
|
prepareReleaseCandidate:release.prepareReleaseCandidate
|
|
328
375
|
}), '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
|
|
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 ['
|
|
13
|
+
for(const name of ['toolCallDeadlineMs','PACKAGE_VERSION','allowedDesktopNames'])
|
|
14
14
|
if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
|
|
15
|
-
|
|
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
|
-
|
|
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
|
-
|
|
58
|
-
|
|
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
|
-
|
|
77
|
-
if(
|
|
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',
|
|
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
|
-
|
|
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
|
-
|
|
95
|
-
|
|
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',
|
|
102
|
-
|
|
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())
|
|
105
|
-
|
|
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
|
-
|
|
136
|
-
|
|
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(
|
|
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
|
|
199
|
-
|
|
200
|
-
//
|
|
201
|
-
//
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
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));
|
package/lib/adapters/tunnel.mjs
CHANGED
|
@@ -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 {
|
|
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{
|
|
68
|
-
|
|
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(
|
|
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
|
|
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(
|
|
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
|
-
}
|
package/lib/context-gateway.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
});
|