@tomflow/chatloop-tools 0.4.33 → 0.9.0
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 +117 -127
- package/bin/cli.mjs +48 -38
- package/bin/supervisor.mjs +4 -0
- package/index.mjs +238 -0
- package/lib/adapters/fixture.mjs +3 -2
- package/lib/adapters/index.mjs +14 -5
- package/lib/adapters/mcp-child.mjs +29 -7
- package/lib/adapters/tunnel.mjs +25 -7
- package/lib/api-aspect.mjs +190 -0
- package/lib/cli-command-router.mjs +34 -0
- package/lib/context-control-auth.mjs +12 -1
- package/lib/context-control-run.mjs +17 -79
- package/lib/context-gateway.mjs +108 -15
- package/lib/control.mjs +3 -2
- package/lib/extension-cli-contract.mjs +22 -0
- package/lib/extension-proxy.mjs +48 -19
- package/lib/gateway.mjs +46 -176
- package/lib/mcp-tool-router.mjs +60 -0
- package/lib/release-owner-preflight.mjs +41 -0
- package/lib/release.mjs +94 -49
- package/lib/{supervisor.mjs → supervisor-runtime.mjs} +143 -80
- package/lib/trace-gateway.mjs +12 -1
- package/lib/trace-observation.mjs +118 -0
- package/lib/tunnel.mjs +17 -29
- package/package.json +20 -14
- package/providers/context.mjs +20 -0
- package/providers/desktop.mjs +80 -0
- package/{lib/extension-contract.mjs → providers/extension.mjs} +36 -0
- package/providers/runtime.mjs +32 -0
- package/providers/trace.mjs +25 -0
- package/providers.generated.mjs +8 -0
- package/scripts/build-providers.mjs +69 -0
- package/lib/context-cli.mjs +0 -2
- package/lib/context-migration.mjs +0 -2
- package/lib/context-protocol.mjs +0 -2
- package/lib/task-registry-managed.mjs +0 -38
- package/lib/task-registry.mjs +0 -221
- package/node_modules/@tomflow/chatloop-context/README.md +0 -271
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -273
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -301
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -272
- package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +0 -1615
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -264
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -219
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -455
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -159
- package/node_modules/@tomflow/chatloop-context/package.json +0 -21
- package/node_modules/@tomflow/chatloop-trace/README.md +0 -13
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -259
- package/node_modules/@tomflow/chatloop-trace/package.json +0 -11
|
@@ -4,13 +4,25 @@
|
|
|
4
4
|
import {existsSync,lstatSync,readFileSync} from 'node:fs';
|
|
5
5
|
import {homedir} from 'node:os';
|
|
6
6
|
import {join,dirname} from 'node:path';
|
|
7
|
-
import {
|
|
8
|
-
|
|
7
|
+
import {loadTrustedRuntime} from '@tomflow/chatloop-context';
|
|
8
|
+
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
9
|
+
// Private modules never import or resolve another private implementation.
|
|
10
|
+
let verifyContextEnvelope;
|
|
11
|
+
let connected=false;
|
|
12
|
+
export function configureContextControlRun(ports){
|
|
13
|
+
if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
14
|
+
for(const name of ['verifyContextEnvelope'])
|
|
15
|
+
if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
|
|
16
|
+
({verifyContextEnvelope}=ports);
|
|
17
|
+
connected=true;
|
|
18
|
+
}
|
|
19
|
+
|
|
9
20
|
|
|
10
21
|
const fail=code=>Object.assign(new Error(code),{code});
|
|
11
22
|
const assert=(ok,code)=>{if(!ok)throw fail(code)};
|
|
12
23
|
const supported=new Set(['permit.consume','run.bind.initial','run.fence',
|
|
13
|
-
'run.bind.handoff','run.restore-same-owner','run.fence.terminal',
|
|
24
|
+
'run.bind.handoff','run.restore-same-owner','run.fence.terminal',
|
|
25
|
+
'run.credential.rotate','run.terminalStatus','run.reopenStatus','run.snapshot']);
|
|
14
26
|
const sessionPath=()=>join(process.env.CHAT_LOOP_CONTEXT_NATIVE_SESSION_DIR||
|
|
15
27
|
join(homedir(),'.chat-loop','session'),'active-session.json');
|
|
16
28
|
function readNativePointer(){
|
|
@@ -38,80 +50,6 @@ export async function handleContextControl(message){
|
|
|
38
50
|
assert(!['principal','role','internalAuthorized'].some(k=>Object.hasOwn(args,k)),
|
|
39
51
|
'CLIENT_AUTH_FIELD_FORBIDDEN');
|
|
40
52
|
const native=readNativePointer();
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
&& native.generation===args.generation
|
|
44
|
-
&& native.activeChatId===args.activeChatId
|
|
45
|
-
&& (native.activeChatId!==null || command==='permit.consume'&&args.kind==='START'),
|
|
46
|
-
'CONTEXT_NATIVE_BINDING_MISMATCH');
|
|
47
|
-
const allowed=parseContextAllowedProjects(process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS);
|
|
48
|
-
assert(allowed.has(native.projectId),'PROJECT_ACCESS_DENIED');
|
|
49
|
-
if(command==='run.fence')assert(native.phase==='PENDING','NATIVE_PHASE_MISMATCH');
|
|
50
|
-
if(command==='run.fence')
|
|
51
|
-
assert(args.targetGeneration===native.generation+1,'TARGET_GENERATION_MISMATCH');
|
|
52
|
-
if(['run.fence','run.fence.terminal','run.bind.initial','run.bind.handoff'].includes(command))
|
|
53
|
-
assert(args.runRef===native.sessionId+':'+native.taskId+':'+native.generation,
|
|
54
|
-
'RUN_REF_MISMATCH');
|
|
55
|
-
if(command==='permit.consume')assert(['RESERVED','PENDING'].includes(native.phase),
|
|
56
|
-
'NATIVE_PHASE_MISMATCH');
|
|
57
|
-
if(command==='run.bind.initial'||command==='run.bind.handoff')
|
|
58
|
-
assert(native.phase==='WAITING_REPLY','NATIVE_PHASE_MISMATCH');
|
|
59
|
-
if(command==='run.restore-same-owner')assert(native.phase==='RESERVED',
|
|
60
|
-
'NATIVE_PHASE_MISMATCH');
|
|
61
|
-
if(command==='run.fence.terminal')assert(native.phase==='DONE',
|
|
62
|
-
'NATIVE_PHASE_MISMATCH');
|
|
63
|
-
// Use the SAME Project identity/physical path checks as the SDK Gateway.
|
|
64
|
-
// Legacy explicit shared Store remains an opt-in transition mode; normal
|
|
65
|
-
// production resolves exactly one authorized <projectId>/context.sqlite.
|
|
66
|
-
const [{openContextProtocol},{resolveVerifiedProjectDatabase}]=await Promise.all([
|
|
67
|
-
import('./context-protocol.mjs'),
|
|
68
|
-
import('@tomflow/chatloop-context/operations')
|
|
69
|
-
]);
|
|
70
|
-
const dbFile=resolveVerifiedProjectDatabase(args.projectId);
|
|
71
|
-
const db=openContextProtocol(dbFile,{
|
|
72
|
-
principalId:'native-controlled',
|
|
73
|
-
authorizeData:(access,projectId)=>allowed.has(projectId),
|
|
74
|
-
authorizeInternal:()=>true
|
|
75
|
-
});
|
|
76
|
-
try{
|
|
77
|
-
if(!['run.terminalStatus','run.reopenStatus','run.snapshot'].includes(command)
|
|
78
|
-
&&!db.projectBusinessAuthority(args.projectId).writable)
|
|
79
|
-
throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
|
|
80
|
-
const validated={...args};
|
|
81
|
-
// No arbitrary role booleans pass through the IPC as authority;
|
|
82
|
-
// local Native projection is one required proof, Worker stays Owner.
|
|
83
|
-
delete validated.ownerCommitted;
|
|
84
|
-
delete validated.nativeCommitted;
|
|
85
|
-
switch(command){
|
|
86
|
-
case 'run.terminalStatus':
|
|
87
|
-
return db.terminalStatus(args.projectId,args.taskId);
|
|
88
|
-
case 'run.reopenStatus':
|
|
89
|
-
assert(native.phase==='DONE','NATIVE_PHASE_MISMATCH');
|
|
90
|
-
return db.reopenStatus(args.projectId,args.taskId);
|
|
91
|
-
case 'run.snapshot':
|
|
92
|
-
return db.latestCheckpoint(args.projectId,args.taskId);
|
|
93
|
-
case 'permit.consume':
|
|
94
|
-
return db.consumePermit(validated);
|
|
95
|
-
case 'run.bind.initial':
|
|
96
|
-
return db.bindInitial({...validated,ownerCommitted:true});
|
|
97
|
-
case 'run.fence':
|
|
98
|
-
return db.fence(validated);
|
|
99
|
-
case 'run.fence.terminal':
|
|
100
|
-
return db.fenceTerminal(validated);
|
|
101
|
-
case 'run.bind.handoff':
|
|
102
|
-
return db.bindHandoff({...validated,ownerCommitted:true,nativeCommitted:true});
|
|
103
|
-
case 'run.restore-same-owner':
|
|
104
|
-
// The Worker signed the exact pre-send result via the trusted Chrome
|
|
105
|
-
// Native Messaging source. Native has already CAS-restored the same
|
|
106
|
-
// session, generation, Chat and task to RESERVED; Context still
|
|
107
|
-
// verifies the original pending attempt and a NEW Continue permit.
|
|
108
|
-
assert(validated.sendState==='NOT_SENT'
|
|
109
|
-
&&typeof validated.recoveryActionToken==='string',
|
|
110
|
-
'SEND_NOT_PROVEN_ABSENT');
|
|
111
|
-
return db.restoreSameOwner({...validated,
|
|
112
|
-
sourceRunRef:native.sessionId+':'+native.taskId+':'+native.generation,
|
|
113
|
-
oldActionTokenRevoked:true,workerRestored:true,
|
|
114
|
-
nativeRestored:true,ownerStillSame:true});
|
|
115
|
-
}
|
|
116
|
-
}finally{db.close()}
|
|
53
|
+
const runtime=await loadTrustedRuntime();
|
|
54
|
+
return runtime.execute(command,args,native);
|
|
117
55
|
}
|
package/lib/context-gateway.mjs
CHANGED
|
@@ -1,15 +1,85 @@
|
|
|
1
1
|
// Thin ChatGPT MCP -> pinned npm Context CLI adapter. No SQLite domain logic here.
|
|
2
2
|
import {spawn,spawnSync} from 'node:child_process';
|
|
3
|
-
import {
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
4
|
import {existsSync} from 'node:fs';
|
|
5
5
|
import {dirname,isAbsolute,delimiter} from 'node:path';
|
|
6
|
-
import {CONTEXT_CONTRACT,CONTEXT_PACKAGE_VERSION,
|
|
7
|
-
|
|
8
|
-
parseContextAllowedProjects}
|
|
9
|
-
export {contextGatewayTools}
|
|
6
|
+
import {CONTEXT_CONTRACT,CONTEXT_PACKAGE_VERSION,contextGateway} from '@tomflow/chatloop-context';
|
|
7
|
+
const {tools:contextGatewayTools,validate:validateContextCall,
|
|
8
|
+
allowedProjects:parseContextAllowedProjects,cliPath}=contextGateway;
|
|
9
|
+
export {contextGatewayTools};
|
|
10
10
|
|
|
11
11
|
const fail=code=>Object.assign(new Error(code),{code});
|
|
12
|
-
|
|
12
|
+
// Context only emits sanitized API events. Tools routes them to the existing
|
|
13
|
+
// Supervisor Trace writer; it never opens a second log or replays a call.
|
|
14
|
+
let recordContextApiLog,readApiParent;
|
|
15
|
+
export function configureContextApiLog({record,current}){
|
|
16
|
+
if(recordContextApiLog)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
17
|
+
if(typeof record!=='function'||typeof current!=='function')
|
|
18
|
+
throw Error('TOOLS_PORT_MISSING:recordContextApiLog');
|
|
19
|
+
recordContextApiLog=record;
|
|
20
|
+
readApiParent=current;
|
|
21
|
+
}
|
|
22
|
+
const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
23
|
+
const CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
|
|
24
|
+
const API=/^[a-z][A-Za-z0-9._-]{1,89}$/;
|
|
25
|
+
const PREFIX='CHAT_LOOP_CONTEXT_API_LOG ';
|
|
26
|
+
export async function forwardContextApiLog(event,request={}){
|
|
27
|
+
// Recording is an internal Context concern. Public Trace diagnosis remains
|
|
28
|
+
// separately opt-in; disabling that MCP tool must not discard audit events.
|
|
29
|
+
if(!recordContextApiLog||process.env.CHAT_LOOP_CONTEXT_API_ENABLE!=='1'
|
|
30
|
+
||event?.contract!=='chat-loop.context-api-log.v1'
|
|
31
|
+
||!UUID.test(event.callId)||!UUID.test(event.traceId||event.callId)
|
|
32
|
+
||!UUID.test(event.spanId||event.callId)
|
|
33
|
+
||(event.parentSpanId!==null&&event.parentSpanId!==undefined
|
|
34
|
+
&&!UUID.test(event.parentSpanId))
|
|
35
|
+
||!API.test(event.api)
|
|
36
|
+
||!['BEGIN','OK','FAILED'].includes(event.phase)
|
|
37
|
+
||!['sdk','gateway','operator','trusted'].includes(event.surface)
|
|
38
|
+
||!['read','write','unknown','internal','operator'].includes(event.mode)
|
|
39
|
+
||typeof event.time!=='string'||!Number.isFinite(Date.parse(event.time))
|
|
40
|
+
||(event.phase==='BEGIN'?event.durationMs!==null
|
|
41
|
+
:!Number.isSafeInteger(event.durationMs)||event.durationMs<0)
|
|
42
|
+
||(event.phase==='FAILED'?!CODE.test(event.errorCode||'')
|
|
43
|
+
:event.errorCode!==null))return;
|
|
44
|
+
// Do not call the instrumented validator from an audit callback: that
|
|
45
|
+
// would recursively audit the audit. A single exact Context Project grant
|
|
46
|
+
// is required; public Trace MCP authorization remains independent.
|
|
47
|
+
const contextGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
|
|
48
|
+
if(typeof contextGrant!=='string'
|
|
49
|
+
||!(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).test(contextGrant))return;
|
|
50
|
+
const projectRef=event.projectRef??contextGrant;
|
|
51
|
+
if(event.taskRef!==null&&event.taskRef!==undefined
|
|
52
|
+
&&(!(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).test(event.taskRef)
|
|
53
|
+
||request?.taskId!==undefined&&request.taskId!==event.taskRef))return;
|
|
54
|
+
if(projectRef!==contextGrant
|
|
55
|
+
||(request?.projectId!==undefined&&request.projectId!==projectRef))return;
|
|
56
|
+
// The event name stays fixed. API name, surface and mode are typed fields,
|
|
57
|
+
// not concatenated strings or borrowed action/receipt identifiers.
|
|
58
|
+
try{
|
|
59
|
+
await recordContextApiLog({
|
|
60
|
+
requestId:randomUUID(),traceId:event.traceId||event.callId,
|
|
61
|
+
spanId:event.spanId||event.callId,
|
|
62
|
+
...(event.parentSpanId?{parentSpanId:event.parentSpanId}:{}),
|
|
63
|
+
projectRef,
|
|
64
|
+
...(event.taskRef?{taskRef:event.taskRef}:{}),
|
|
65
|
+
event:'context.api',
|
|
66
|
+
api:{name:event.api,surface:event.surface,mode:event.mode},
|
|
67
|
+
status:event.phase==='BEGIN'?'BEGIN':event.phase==='OK'?'CONFIRMED':'FAILED',
|
|
68
|
+
...(event.phase==='FAILED'?{errorCode:event.errorCode}:{}),
|
|
69
|
+
...(event.durationMs!==null?{durationMs:event.durationMs}:{})
|
|
70
|
+
});
|
|
71
|
+
}catch{/* Failed audit transport cannot change the Context outcome. */}
|
|
72
|
+
}
|
|
73
|
+
function parseContextLog(stderr){
|
|
74
|
+
// The entire bounded stderr capture is eligible; a fixed 24-record cap
|
|
75
|
+
// silently dropped legitimate nested API spans from a single CLI request.
|
|
76
|
+
return stderr.split('\n').filter(x=>x.startsWith(PREFIX))
|
|
77
|
+
.flatMap(line=>{
|
|
78
|
+
if(line.length>640)return [];
|
|
79
|
+
try{return [JSON.parse(line.slice(PREFIX.length))]}catch{return []}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
13
83
|
const supportedContextNode=()=>{
|
|
14
84
|
const candidate=process.env.CHAT_LOOP_CONTEXT_NODE_BIN;
|
|
15
85
|
if(!candidate)return Number(process.versions.node.split('.')[0])>=24;
|
|
@@ -34,7 +104,7 @@ export const contextGatewayEnabled=()=>{
|
|
|
34
104
|
// resolution step; it is not another trust boundary.
|
|
35
105
|
function invocation(){
|
|
36
106
|
return {bin:process.env.CHAT_LOOP_CONTEXT_NODE_BIN||process.execPath,
|
|
37
|
-
args:[
|
|
107
|
+
args:[cliPath,'request','--json']};
|
|
38
108
|
}
|
|
39
109
|
export async function runContextGateway(name,args){
|
|
40
110
|
if(!contextGatewayEnabled())throw fail('CONTEXT_API_DISABLED');
|
|
@@ -47,13 +117,26 @@ export async function runContextGateway(name,args){
|
|
|
47
117
|
if(Buffer.byteLength(request)>5*1024*1024)throw fail('REQUEST_TOO_LARGE');
|
|
48
118
|
const {bin,args:argv}=invocation();
|
|
49
119
|
const env={...process.env};
|
|
120
|
+
// One opaque correlation carrier, not a permission/identity credential.
|
|
121
|
+
// It follows the real MCP -> child CLI edge without modifying CLI input.
|
|
122
|
+
try{
|
|
123
|
+
const parent=readApiParent?.();
|
|
124
|
+
if(parent&&UUID.test(parent.traceId||'')&&UUID.test(parent.spanId||''))
|
|
125
|
+
env.CHAT_LOOP_API_PARENT=JSON.stringify(parent);
|
|
126
|
+
else delete env.CHAT_LOOP_API_PARENT;
|
|
127
|
+
}catch{delete env.CHAT_LOOP_API_PARENT}
|
|
50
128
|
if(env.CHAT_LOOP_CONTEXT_NODE_BIN&&isAbsolute(env.CHAT_LOOP_CONTEXT_NODE_BIN)){
|
|
51
129
|
env.PATH=dirname(env.CHAT_LOOP_CONTEXT_NODE_BIN)+delimiter+(env.PATH||'');
|
|
52
130
|
}
|
|
53
131
|
// Never forward MCP arguments into env, executable, package spec or a shell.
|
|
54
|
-
|
|
132
|
+
let auditText='';
|
|
133
|
+
try{return await new Promise((resolve,reject)=>{
|
|
55
134
|
const p=spawn(bin,argv,{env,stdio:['pipe','pipe','pipe'],shell:false,windowsHide:true});
|
|
56
|
-
let stdout='',
|
|
135
|
+
let stdout='',stdoutBytes=0,settled=false,started=false;
|
|
136
|
+
// CLI JSON and audit records can contain UTF-8 text. Readable#setEncoding
|
|
137
|
+
// retains incomplete multibyte sequences across arbitrary pipe chunks.
|
|
138
|
+
p.stdout.setEncoding('utf8');
|
|
139
|
+
p.stderr.setEncoding('utf8');
|
|
57
140
|
const complete=(error,result)=>{
|
|
58
141
|
if(settled)return;
|
|
59
142
|
settled=true;clearTimeout(timer);
|
|
@@ -66,14 +149,18 @@ export async function runContextGateway(name,args){
|
|
|
66
149
|
p.on('spawn',()=>{started=true});
|
|
67
150
|
p.on('error',()=>complete(fail('CONTEXT_CLI_UNAVAILABLE')));
|
|
68
151
|
p.stdout.on('data',chunk=>{
|
|
69
|
-
|
|
70
|
-
if(
|
|
71
|
-
p.kill('SIGKILL');complete(fail('CONTEXT_RESULT_UNKNOWN'));
|
|
152
|
+
stdoutBytes+=Buffer.byteLength(chunk,'utf8');
|
|
153
|
+
if(stdoutBytes>8*1024*1024){
|
|
154
|
+
p.kill('SIGKILL');complete(fail('CONTEXT_RESULT_UNKNOWN'));return;
|
|
72
155
|
}
|
|
156
|
+
stdout+=chunk;
|
|
73
157
|
});
|
|
74
158
|
p.stderr.on('data',chunk=>{
|
|
75
|
-
|
|
76
|
-
|
|
159
|
+
// Diagnostic stderr is deliberately lossy; never kill an already
|
|
160
|
+
// authorized Context operation merely because telemetry is verbose.
|
|
161
|
+
const remaining=32768-Buffer.byteLength(auditText,'utf8');
|
|
162
|
+
if(remaining>0)
|
|
163
|
+
auditText+=Buffer.from(chunk,'utf8').subarray(0,remaining).toString('utf8');
|
|
77
164
|
});
|
|
78
165
|
p.on('close',()=>{
|
|
79
166
|
if(settled)return;
|
|
@@ -93,5 +180,11 @@ export async function runContextGateway(name,args){
|
|
|
93
180
|
p.stdin.on('error',()=>{}); // A closed child still gets its final receipt checked.
|
|
94
181
|
p.stdin.end(request);
|
|
95
182
|
});
|
|
96
|
-
|
|
183
|
+
}finally{
|
|
184
|
+
// The Gateway returns the actual Context result without awaiting the
|
|
185
|
+
// Supervisor telemetry socket. Best-effort delivery is explicitly NOT
|
|
186
|
+
// a business receipt, and never causes a side-effect retry.
|
|
187
|
+
void Promise.allSettled(parseContextLog(auditText)
|
|
188
|
+
.map(event=>forwardContextApiLog(event,args)));
|
|
189
|
+
}
|
|
97
190
|
}
|
package/lib/control.mjs
CHANGED
|
@@ -75,14 +75,15 @@ export function send(request, timeout=3000) {
|
|
|
75
75
|
return new Promise((resolve,reject)=>{
|
|
76
76
|
let buf = '', done = false;
|
|
77
77
|
const socket = connect(paths().socket);
|
|
78
|
+
socket.setEncoding('utf8'); // IPC JSON may contain split Unicode text.
|
|
78
79
|
const timer = setTimeout(()=>finish(Object.assign(new Error('IPC deadline'),{code:'TIMEOUT'})),timeout);
|
|
79
80
|
function finish(err,value) {if(done)return; done=true; clearTimeout(timer); socket.destroy(); err?reject(err):resolve(value);}
|
|
80
81
|
socket.on('connect',()=>socket.write(JSON.stringify(request)+'\n'));
|
|
81
82
|
socket.on('error',err=>finish(err));
|
|
82
83
|
socket.on('end',()=>{if(!done)finish(Object.assign(new Error('Empty IPC reply'),{code:'UNKNOWN_RESULT'}));});
|
|
83
84
|
socket.on('data',chunk=>{
|
|
84
|
-
buf+=chunk
|
|
85
|
-
if(buf
|
|
85
|
+
buf+=chunk;
|
|
86
|
+
if(Buffer.byteLength(buf,'utf8')>8*1024*1024)return finish(Object.assign(new Error('IPC reply too large'),{code:'INVALID_REPLY'}));
|
|
86
87
|
const n=buf.indexOf('\n'); if(n===-1)return;
|
|
87
88
|
try{finish(null,JSON.parse(buf.slice(0,n)));}catch{finish(Object.assign(new Error('Malformed IPC reply'),{code:'INVALID_REPLY'}));}
|
|
88
89
|
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Tools' anti-corruption boundary for an independently replaceable CLI provider.
|
|
2
|
+
// No npm lookup, process, filesystem, Chrome API or business state lives here.
|
|
3
|
+
export const EXTENSION_CLI_CONTRACT='chat-loop.extension-cli.v1';
|
|
4
|
+
const VERSION=/^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$/;
|
|
5
|
+
const invalid=code=>({ok:false,code});
|
|
6
|
+
export function acceptExtensionCliReceipt(reply,command,exitCode){
|
|
7
|
+
if(!reply||typeof reply!=='object'||Array.isArray(reply)
|
|
8
|
+
||reply.contract!==EXTENSION_CLI_CONTRACT
|
|
9
|
+
||reply.event!=='RESULT'||reply.command!==command
|
|
10
|
+
||typeof reply.ok!=='boolean'
|
|
11
|
+
||(reply.providerVersion!==undefined
|
|
12
|
+
&&(typeof reply.providerVersion!=='string'||!VERSION.test(reply.providerVersion))))
|
|
13
|
+
return invalid('INVALID_EXTENSION_REPLY');
|
|
14
|
+
if(reply.ok!==true||exitCode!==0)
|
|
15
|
+
return invalid(typeof reply.error?.code==='string'
|
|
16
|
+
&&/^[A-Z][A-Z0-9_]{1,119}$/.test(reply.error.code)
|
|
17
|
+
?reply.error.code:'EXTENSION_ACTION_FAILED');
|
|
18
|
+
if(!reply.value||typeof reply.value!=='object'||Array.isArray(reply.value))
|
|
19
|
+
return invalid('INVALID_EXTENSION_REPLY');
|
|
20
|
+
return {ok:true,value:reply.value,
|
|
21
|
+
providerVersion:reply.providerVersion??null};
|
|
22
|
+
}
|
package/lib/extension-proxy.mjs
CHANGED
|
@@ -3,46 +3,75 @@
|
|
|
3
3
|
import {spawn} from 'node:child_process';
|
|
4
4
|
import {readFileSync,statSync} from 'node:fs';
|
|
5
5
|
import {tmpdir} from 'node:os';
|
|
6
|
-
|
|
7
|
-
|
|
6
|
+
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
7
|
+
// Private modules never import or resolve another private implementation.
|
|
8
|
+
let extensionCommand, validExtensionArgs, isControlTool, acceptExtensionCliReceipt, extensionTools;
|
|
9
|
+
let connected=false;
|
|
10
|
+
export function configureExtensionProxy(ports){
|
|
11
|
+
if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
12
|
+
for(const name of ['extensionCommand', 'validExtensionArgs', 'isControlTool', 'acceptExtensionCliReceipt', 'extensionTools'])
|
|
13
|
+
if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
|
|
14
|
+
({extensionCommand, validExtensionArgs, isControlTool, acceptExtensionCliReceipt, extensionTools}=ports);
|
|
15
|
+
connected=true;
|
|
16
|
+
}
|
|
17
|
+
|
|
8
18
|
|
|
9
|
-
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
|
|
19
|
+
|
|
20
|
+
// One pinned official CLI provider and one public npm bin. No @latest and
|
|
21
|
+
// no alternate provider injection through private environment variables.
|
|
22
|
+
// The package/version are exact and checked against the same Context
|
|
23
|
+
// dependency deployed with the Tools release.
|
|
24
|
+
export {extensionTools};
|
|
25
|
+
const EXTENSION_PACKAGE='@tomflow/chatloop-extension@0.4.0';
|
|
26
|
+
const EXTENSION_VERSION='0.4.0';
|
|
13
27
|
const NPX_COMMAND=process.platform==='win32'?'npx.cmd':'npx';
|
|
14
28
|
export const extensionInvocation=name=>{
|
|
15
29
|
const command=extensionCommand(name);
|
|
16
30
|
if(!command)return null;
|
|
17
|
-
return {executable:NPX_COMMAND,
|
|
31
|
+
return {executable:NPX_COMMAND,providerVersion:EXTENSION_VERSION,
|
|
18
32
|
args:['--yes','--package='+EXTENSION_PACKAGE,'chatloop-extension',...command]};
|
|
19
33
|
};
|
|
20
34
|
const fail=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
21
35
|
export async function forwardExtensionAction(name,args={}) {
|
|
36
|
+
if(!validExtensionArgs(name,args))return fail('INVALID_ARGUMENT');
|
|
22
37
|
const invocation=extensionInvocation(name);
|
|
23
|
-
if(!invocation
|
|
38
|
+
if(!invocation)return fail('EXTENSION_PROVIDER_UNTRUSTED');
|
|
24
39
|
const control=isControlTool(name);
|
|
25
40
|
if(name==='clean')invocation.args.push(String(args.tabId));
|
|
26
41
|
const response=await new Promise(resolve=>{
|
|
27
42
|
const child=spawn(invocation.executable,invocation.args,{stdio:[control?'pipe':'ignore','pipe','pipe'],
|
|
28
43
|
cwd:tmpdir(),windowsHide:true,env:process.env});
|
|
29
|
-
let stdout='',finished=false;
|
|
44
|
+
let stdout='',stdoutBytes=0,finished=false;
|
|
30
45
|
const settle=x=>{if(finished)return;finished=true;clearTimeout(timer);resolve(x);};
|
|
31
46
|
const timer=setTimeout(()=>{child.kill('SIGTERM');settle(fail('RESULT_TIMEOUT'));},name==='start'?330000:90000);
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
47
|
+
// Node data events can split a UTF-8 code point. Incremental decoding
|
|
48
|
+
// preserves the exact CLI JSON receipt (including Chinese DOM text).
|
|
49
|
+
child.stdout.setEncoding('utf8');
|
|
50
|
+
if(control){
|
|
51
|
+
// A CLI which closes stdin early must not crash the Gateway with an
|
|
52
|
+
// unhandled EPIPE; only the final CLI receipt establishes the outcome.
|
|
53
|
+
child.stdin.on('error',()=>{});
|
|
54
|
+
child.stdin.end(JSON.stringify(args));
|
|
55
|
+
}
|
|
56
|
+
child.stdout.on('data',text=>{
|
|
57
|
+
stdoutBytes+=Buffer.byteLength(text,'utf8');
|
|
58
|
+
if(stdoutBytes>9*1024*1024){
|
|
59
|
+
child.kill('SIGTERM');settle(fail('RESULT_TOO_LARGE'));return;
|
|
60
|
+
}
|
|
61
|
+
stdout+=text;
|
|
36
62
|
});
|
|
37
63
|
child.stderr.on('data',()=>{}); // stderr may contain browser details; never expose it.
|
|
38
64
|
child.on('error',()=>settle(fail('EXTENSION_CLI_UNAVAILABLE')));
|
|
39
|
-
|
|
65
|
+
// 'exit' can precede the last stdout chunk; 'close' waits until the
|
|
66
|
+
// CLI and any inherited stdio handles have closed before parsing proof.
|
|
67
|
+
child.on('close',code=>{
|
|
40
68
|
const line=stdout.trim().split('\n').filter(Boolean).at(-1);
|
|
41
69
|
let msg;try{msg=JSON.parse(line);}catch{return settle(fail('INVALID_EXTENSION_REPLY'));}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
if(
|
|
45
|
-
|
|
70
|
+
const command=name==='clean'?'extension clean '+args.tabId:extensionCommand(name).join(' ');
|
|
71
|
+
const result=acceptExtensionCliReceipt(msg,command,code);
|
|
72
|
+
if(result.ok&&result.providerVersion!==invocation.providerVersion)
|
|
73
|
+
return settle(fail('EXTENSION_PROVIDER_VERSION_MISMATCH'));
|
|
74
|
+
settle(result.ok?result.value:fail(result.code));
|
|
46
75
|
});
|
|
47
76
|
});
|
|
48
77
|
return formatExtensionResult(name,response);
|
|
@@ -70,7 +99,7 @@ export function formatExtensionResult(name,response) {
|
|
|
70
99
|
|| !['QUEUED','STATUS'].includes(proof.status))
|
|
71
100
|
return fail('INVALID_MODEL_INTENT_REPLY');
|
|
72
101
|
// Only verified, bounded identifiers can cross into the optional Trace
|
|
73
|
-
// correlation contract.
|
|
102
|
+
// correlation contract. Missing identifiers are unverified.
|
|
74
103
|
const correlated=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(proof.sessionId||'')
|
|
75
104
|
&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(proof.projectId||'')
|
|
76
105
|
&&Number.isSafeInteger(proof.generation)&&proof.generation>=0;
|