@tomflow/chatloop-tools 0.4.18 → 0.4.21

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 (32) hide show
  1. package/README.md +93 -3
  2. package/bin/cli.mjs +29 -8
  3. package/lib/approval-form-probe.mjs +55 -0
  4. package/lib/context-cli.mjs +2 -0
  5. package/lib/context-control-auth.mjs +40 -0
  6. package/lib/context-control-run.mjs +117 -0
  7. package/lib/context-gateway.mjs +97 -0
  8. package/lib/context-migration.mjs +2 -0
  9. package/lib/context-protocol.mjs +2 -0
  10. package/lib/control.mjs +2 -0
  11. package/lib/extension-contract.mjs +31 -5
  12. package/lib/extension-proxy.mjs +11 -2
  13. package/lib/gateway.mjs +102 -6
  14. package/lib/release.mjs +174 -5
  15. package/lib/supervisor.mjs +78 -3
  16. package/lib/task-registry-managed.mjs +38 -0
  17. package/lib/task-registry.mjs +221 -0
  18. package/lib/trace-gateway.mjs +99 -0
  19. package/node_modules/@tomflow/chatloop-context/README.md +204 -0
  20. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +236 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +301 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +272 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +1595 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +264 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +219 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +289 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +159 -0
  28. package/node_modules/@tomflow/chatloop-context/package.json +21 -0
  29. package/node_modules/@tomflow/chatloop-trace/README.md +13 -0
  30. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +259 -0
  31. package/node_modules/@tomflow/chatloop-trace/package.json +11 -0
  32. package/package.json +9 -3
@@ -0,0 +1,259 @@
1
+ import {randomUUID} from 'node:crypto';
2
+ import {constants as FS,createReadStream,closeSync,existsSync,fstatSync,lstatSync,openSync,writeSync,renameSync,unlinkSync} from 'node:fs';
3
+ import {createInterface} from 'node:readline';
4
+ import {dirname,isAbsolute} from 'node:path';
5
+
6
+ export const TRACE_SCHEMA_VERSION=1;
7
+ 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;
8
+ const SCOPE=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
9
+ const REF=/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
10
+ const EVENT=/^[a-z][a-z0-9_.-]{1,95}$/;
11
+ const CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
12
+ const COMPONENTS=new Set(['supervisor','gateway','context','extension','native']);
13
+ const STATUSES=new Set(['BEGIN','CONFIRMED','FAILED','UNKNOWN','BLOCKED']);
14
+ const ALLOWED=new Set(['eventId','traceId','spanId','parentSpanId','timestamp','component',
15
+ 'event','projectRef','taskRef','sessionRef','generation','requestId','actionId',
16
+ 'status','errorCode','durationMs','evidenceRef']);
17
+ const LEGACY_FIELDS=new Set(['requestId','toolId','toolName','action','scope',
18
+ 'status','reason','code','errorCode','pid','version','outcome']);
19
+ const fail=code=>Object.assign(new Error(code),{code});
20
+ const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
21
+ const isId=v=>typeof v==='string'&&UUID.test(v);
22
+ const safeScope=v=>typeof v==='string'&&SCOPE.test(v);
23
+ const safeRef=v=>typeof v==='string'&&REF.test(v);
24
+ const natural=v=>Number.isSafeInteger(v)&&v>=0;
25
+ const keys=(v,allowed)=>{
26
+ if(!object(v))throw fail('TRACE_INVALID_OBJECT');
27
+ for(const k of Object.keys(v))if(!allowed.has(k))throw fail('TRACE_INVALID_FIELD');
28
+ };
29
+ const bytes=v=>Buffer.byteLength(JSON.stringify(v),'utf8');
30
+ const nullable=(v,test,code)=>{
31
+ if(v!==undefined&&v!==null&&!test(v))throw fail(code);
32
+ return v??null;
33
+ };
34
+ export function createTrace(){return {traceId:randomUUID(),spanId:randomUUID()};}
35
+ function normalize(v,epoch,seq){
36
+ keys(v,ALLOWED);
37
+ if(!EVENT.test(v.event||'')||!COMPONENTS.has(v.component)||
38
+ !STATUSES.has(v.status))throw fail('TRACE_INVALID_EVENT');
39
+ for(const k of ['eventId','traceId','spanId'])
40
+ if(v[k]!==undefined&&!isId(v[k]))throw fail('TRACE_INVALID_ID');
41
+ const entry={
42
+ time:v.timestamp||new Date().toISOString(),
43
+ schemaVersion:TRACE_SCHEMA_VERSION,eventId:v.eventId||randomUUID(),
44
+ traceId:v.traceId||randomUUID(),spanId:v.spanId||randomUUID(),
45
+ parentSpanId:nullable(v.parentSpanId,isId,'TRACE_INVALID_ID'),
46
+ writerEpoch:epoch,writerSeq:seq,component:v.component,event:v.event,
47
+ projectRef:nullable(v.projectRef,safeScope,'TRACE_INVALID_SCOPE'),
48
+ taskRef:nullable(v.taskRef,safeRef,'TRACE_INVALID_REFERENCE'),
49
+ sessionRef:nullable(v.sessionRef,safeRef,'TRACE_INVALID_REFERENCE'),
50
+ generation:nullable(v.generation,natural,'TRACE_INVALID_NUMBER'),
51
+ requestId:nullable(v.requestId,safeRef,'TRACE_INVALID_REFERENCE'),
52
+ actionId:nullable(v.actionId,safeRef,'TRACE_INVALID_REFERENCE'),
53
+ status:v.status,errorCode:nullable(v.errorCode,x=>CODE.test(x),'TRACE_INVALID_ERROR_CODE'),
54
+ durationMs:nullable(v.durationMs,natural,'TRACE_INVALID_NUMBER'),
55
+ evidenceRef:nullable(v.evidenceRef,safeRef,'TRACE_INVALID_REFERENCE')
56
+ };
57
+ if(typeof entry.time!=='string'||entry.time.length>40||
58
+ !Number.isFinite(Date.parse(entry.time)))throw fail('TRACE_INVALID_TIMESTAMP');
59
+ if(bytes(entry)>4096)throw fail('TRACE_EVENT_TOO_LARGE');
60
+ return entry;
61
+ }
62
+ // Strict file owner, permissions, no directory creation and no symlink escapes.
63
+ function secureFile(filePath){
64
+ if(typeof filePath!=='string'||!isAbsolute(filePath))throw fail('TRACE_PATH_INVALID');
65
+ let dir;try{dir=lstatSync(dirname(filePath))}catch{throw fail('TRACE_DIRECTORY_UNAVAILABLE')}
66
+ if(!dir.isDirectory()||dir.isSymbolicLink()||(dir.mode&0o077)||
67
+ process.getuid&&dir.uid!==process.getuid())throw fail('TRACE_DIRECTORY_UNTRUSTED');
68
+ if(!existsSync(filePath))return null;
69
+ const st=lstatSync(filePath);
70
+ if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)||
71
+ process.getuid&&st.uid!==process.getuid())throw fail('TRACE_FILE_UNTRUSTED');
72
+ return st;
73
+ }
74
+ export function createTraceWriter({
75
+ filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5
76
+ }){
77
+ if(typeof enableRotation!=='boolean'||!Number.isSafeInteger(rotateBytes)||
78
+ rotateBytes<512||rotateBytes>10*1024*1024||
79
+ !Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
80
+ throw fail('TRACE_ROTATION_INVALID');
81
+ const epoch=randomUUID();let seq=0,failures=0,lastError=null,rotations=0;
82
+ const rotateIfNeeded=lineBytes=>{
83
+ // Legacy data is never moved until an operator explicitly enables
84
+ // rotation after preserving its historical evidence.
85
+ if(!enableRotation)return;
86
+ const old=secureFile(filePath);
87
+ if(!old||old.size+lineBytes<=rotateBytes)return;
88
+ const oldest=filePath+'.'+maxSegments;
89
+ if(secureFile(oldest))unlinkSync(oldest);
90
+ for(let i=maxSegments-1;i>=1;i--){
91
+ const from=filePath+'.'+i;
92
+ if(secureFile(from))renameSync(from,filePath+'.'+(i+1));
93
+ }
94
+ renameSync(filePath,filePath+'.1');
95
+ rotations++;
96
+ };
97
+ function append(entry){
98
+ let fd;
99
+ try{
100
+ rotateIfNeeded(bytes(entry)+1);
101
+ secureFile(filePath);
102
+ fd=openSync(filePath,FS.O_WRONLY|FS.O_APPEND|FS.O_CREAT|FS.O_NOFOLLOW,0o600);
103
+ const st=fstatSync(fd);
104
+ if(!st.isFile()||(st.mode&0o077)||
105
+ process.getuid&&st.uid!==process.getuid())throw fail('TRACE_FILE_UNTRUSTED');
106
+ writeSync(fd,JSON.stringify(entry)+'\n');
107
+ seq++;lastError=null;
108
+ return {eventId:entry.eventId,traceId:entry.traceId,
109
+ writerEpoch:epoch,writerSeq:seq};
110
+ }catch(e){failures++;lastError=e.code||'TRACE_WRITE_FAILED';throw e}
111
+ finally{if(fd!==undefined)closeSync(fd)}
112
+ }
113
+ const record=v=>append(normalize(v,epoch,seq+1));
114
+ const recordLegacy=(event,detail={})=>{
115
+ const safe={};
116
+ if(object(detail))for(const [k,v] of Object.entries(detail)){
117
+ if(!LEGACY_FIELDS.has(k))continue;
118
+ if(typeof v==='string'&&v.length<=128&&/^[A-Za-z0-9_.:-]+$/.test(v))
119
+ safe[k]=v;
120
+ else if(k==='pid'&&natural(v))safe[k]=v;
121
+ }
122
+ const status=safe.status==='FAILED'||/(?:error|fatal)/.test(event)?'FAILED':
123
+ safe.status==='UNKNOWN'||['PARTIAL','DEGRADED','UNCONFIRMED','TIMEOUT'].includes(safe.status)?'UNKNOWN':
124
+ safe.status==='BLOCKED'||event.includes('blocked')?'BLOCKED':'CONFIRMED';
125
+ const entry=normalize({event,component:'supervisor',status,
126
+ requestId:safeRef(safe.requestId)?safe.requestId:null,
127
+ errorCode:typeof safe.errorCode==='string'&&CODE.test(safe.errorCode)?
128
+ safe.errorCode:null},epoch,seq+1);
129
+ // Preserve only harmless historical control-result summaries; never copy
130
+ // arbitrary tool output or errors into the shared private log.
131
+ const legacyResults=Array.isArray(detail?.results)?detail.results.slice(0,12)
132
+ .filter(object).map(x=>Object.fromEntries(
133
+ ['toolId','after','outcome','errorCode'].filter(k=>
134
+ typeof x[k]==='string'&&x[k].length<=64&&
135
+ /^[A-Za-z0-9_.:-]+$/.test(x[k])).map(k=>[k,x[k]]))):null;
136
+ const combined={...entry,...safe,traceStatus:entry.status,
137
+ ...(legacyResults?{legacyResults}:{})};
138
+ if(bytes(combined)>4096)throw fail('TRACE_EVENT_TOO_LARGE');
139
+ return append(combined);
140
+ };
141
+ const health=()=>({status:lastError?'TRACE_DEGRADED':'OK',
142
+ errorCode:lastError,failures,writerEpoch:epoch,writerSeq:seq,
143
+ rotationEnabled:enableRotation,rotations});
144
+ return {record,recordLegacy,health};
145
+ }
146
+ const OUTPUT=['time','schemaVersion','eventId','traceId','spanId','parentSpanId',
147
+ 'writerEpoch','writerSeq','component','event','projectRef','taskRef','sessionRef',
148
+ 'generation','requestId','actionId','status','errorCode','durationMs','evidenceRef'];
149
+ const publicEvent=v=>Object.fromEntries(OUTPUT.map(k=>[
150
+ k,k==='status'?(v.traceStatus??v.status??null):v[k]??null
151
+ ]));
152
+ // The on-disk log is evidence, not executable truth. Reject forged/malformed
153
+ // fields at the read boundary too; do not trust a matching projectRef alone.
154
+ const validStored=v=>object(v)&&isId(v.eventId)&&isId(v.traceId)
155
+ &&isId(v.spanId)&&isId(v.writerEpoch)&&natural(v.writerSeq)
156
+ &&EVENT.test(v.event||'')&&COMPONENTS.has(v.component)
157
+ &&STATUSES.has(v.traceStatus??v.status)
158
+ &&typeof v.time==='string'&&v.time.length<=40&&Number.isFinite(Date.parse(v.time))
159
+ &&safeScope(v.projectRef)
160
+ &&['parentSpanId','taskRef','sessionRef','requestId','actionId','evidenceRef']
161
+ .every(k=>v[k]==null||(k==='parentSpanId'?isId(v[k]):safeRef(v[k])))
162
+ &&(v.errorCode==null||typeof v.errorCode==='string'&&CODE.test(v.errorCode))
163
+ &&(v.generation==null||natural(v.generation))
164
+ &&(v.durationMs==null||natural(v.durationMs));
165
+ function filterInput(v,allowed){
166
+ keys(v,new Set(['traceId','sessionRef','projectRef','maxEvents']));
167
+ if(!safeScope(v.projectRef)||!allowed.includes(v.projectRef))
168
+ throw fail('TRACE_PROJECT_ACCESS_DENIED');
169
+ if(v.traceId!==undefined&&!isId(v.traceId))throw fail('TRACE_INVALID_ID');
170
+ if(v.sessionRef!==undefined&&!safeRef(v.sessionRef))
171
+ throw fail('TRACE_INVALID_REFERENCE');
172
+ if(!v.traceId&&!v.sessionRef)throw fail('TRACE_FILTER_REQUIRED');
173
+ const maxEvents=v.maxEvents??100;
174
+ if(!Number.isSafeInteger(maxEvents)||maxEvents<1||maxEvents>200)
175
+ throw fail('TRACE_INVALID_LIMIT');
176
+ return {...v,maxEvents};
177
+ }
178
+ export function createTraceReader({filePath,allowedProjects,maxSegments=5}){
179
+ if(!Array.isArray(allowedProjects)||!allowedProjects.length||
180
+ allowedProjects.some(x=>!safeScope(x)))
181
+ throw fail('TRACE_PROJECT_SCOPE_REQUIRED');
182
+ if(!Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
183
+ throw fail('TRACE_ROTATION_INVALID');
184
+ async function query(opts){
185
+ const filter=filterInput(opts,allowedProjects);
186
+ const files=[...Array.from({length:maxSegments},(_,i)=>filePath+'.'+(maxSegments-i)),
187
+ filePath].map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
188
+ if(!files.length)return {events:[],matched:0,legacyUncorrelated:true,gapped:true,
189
+ errors:['TRACE_LOG_MISSING'],truncated:false};
190
+ if(files.reduce((sum,x)=>sum+x.stat.size,0)>64*1024*1024)
191
+ throw fail('TRACE_FILE_TOO_LARGE');
192
+ const seen=new Set(),events=[],errors=[],writerEpochs=new Set();
193
+ let matched=0,corrupt=0,legacy=0;
194
+ for(const item of files){
195
+ const fd=openSync(item.path,FS.O_RDONLY|FS.O_NOFOLLOW);
196
+ const opened=fstatSync(fd);
197
+ if(!opened.isFile()||(opened.mode&0o077)||process.getuid&&opened.uid!==process.getuid()){
198
+ closeSync(fd);throw fail('TRACE_FILE_UNTRUSTED');
199
+ }
200
+ const stream=createReadStream(item.path,{fd,autoClose:true,encoding:'utf8'});
201
+ const lines=createInterface({input:stream,crlfDelay:Infinity});
202
+ try{
203
+ for await(const line of lines){
204
+ if(!line.trim())continue;
205
+ if(Buffer.byteLength(line)>8192){corrupt++;continue}
206
+ let entry;try{entry=JSON.parse(line)}catch{corrupt++;continue}
207
+ if(entry.schemaVersion!==TRACE_SCHEMA_VERSION){legacy++;continue}
208
+ if(entry.projectRef!==filter.projectRef||
209
+ filter.traceId&&entry.traceId!==filter.traceId||
210
+ filter.sessionRef&&entry.sessionRef!==filter.sessionRef)continue;
211
+ if(!validStored(entry)){corrupt++;continue}
212
+ if(seen.has(entry.eventId))continue;
213
+ seen.add(entry.eventId);matched++;
214
+ writerEpochs.add(entry.writerEpoch);
215
+ events.push(publicEvent(entry));
216
+ if(events.length>filter.maxEvents)events.shift();
217
+ }
218
+ }finally{lines.close();stream.destroy()}
219
+ }
220
+ if(corrupt)errors.push('TRACE_MALFORMED_LINES');
221
+ return {events,matched,legacyUncorrelated:legacy>0,gapped:corrupt>0,
222
+ // A restart is not proof of loss, but evidence continuity across epochs
223
+ // cannot be asserted by a log reader alone, even with later ACKs.
224
+ writerRestartUnverified:writerEpochs.size>1,
225
+ errors,truncated:matched>filter.maxEvents};
226
+ }
227
+ async function diagnose(opts){
228
+ const result=await query(opts);
229
+ const pending=new Map(),gaps=[...result.errors];let lastConfirmed=null,unknown=false;
230
+ for(const e of result.events){
231
+ if(e.status==='CONFIRMED')lastConfirmed={
232
+ eventId:e.eventId,event:e.event,time:e.time,component:e.component
233
+ };
234
+ if(e.status==='UNKNOWN'||e.status==='BLOCKED')unknown=true;
235
+ const id=e.actionId||e.requestId;
236
+ if(id){
237
+ if(e.status==='BEGIN')pending.set(id,e.event);
238
+ if(['CONFIRMED','FAILED','UNKNOWN','BLOCKED'].includes(e.status))pending.delete(id);
239
+ }
240
+ }
241
+ if(result.truncated)gaps.push('TRACE_WINDOW_TRUNCATED');
242
+ if(result.writerRestartUnverified)gaps.push('TRACE_WRITER_RESTART_UNVERIFIED');
243
+ if(result.legacyUncorrelated)gaps.push('LEGACY_EVENTS_UNCORRELATED');
244
+ if(pending.size)gaps.push('MISSING_ACTION_RECEIPT');
245
+ if(!result.events.length)gaps.push('NO_MATCHING_EVENTS');
246
+ return {traceId:opts.traceId??null,projectRef:opts.projectRef,
247
+ inspected:result.events.length,totalMatched:result.matched,lastConfirmed,
248
+ lastEvent:result.events.at(-1)??null,unknown,gaps:[...new Set(gaps)],
249
+ confidence:gaps.length?'INCOMPLETE':'TRACE_ONLY',
250
+ retryDisposition:unknown||pending.size||gaps.length?
251
+ 'VERIFY_AUTHORITATIVE_RECEIPT_FIRST':'NO_AUTOMATIC_RETRY',
252
+ timeline:result.events};
253
+ }
254
+ return {query,diagnose,health:()=>{
255
+ const st=secureFile(filePath);
256
+ return {status:st?'READABLE':'TRACE_LOG_MISSING',
257
+ bytes:st?.size??0,projectScopes:allowedProjects.length};
258
+ }};
259
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": "@tomflow/chatloop-trace",
3
+ "version": "0.1.0",
4
+ "description": "Trace SDK and scoped read-only diagnostics for Chat Loop",
5
+ "type": "module",
6
+ "engines": {"node": ">=20"},
7
+ "publishConfig": {"access": "public"},
8
+ "exports": {".": "./lib/trace.mjs", "./package.json": "./package.json"},
9
+ "files": ["lib/", "README.md"],
10
+ "scripts": {"test": "node --test test/*.test.mjs"}
11
+ }
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.4.18",
6
+ "version": "0.4.21",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -21,7 +21,9 @@
21
21
  "test": "node --test ./test/*.test.mjs"
22
22
  },
23
23
  "dependencies": {
24
- "@wonderwhy-er/desktop-commander": "0.2.44"
24
+ "@wonderwhy-er/desktop-commander": "0.2.44",
25
+ "@tomflow/chatloop-context": "0.1.0",
26
+ "@tomflow/chatloop-trace": "0.1.0"
25
27
  },
26
28
  "engines": {
27
29
  "node": ">=20"
@@ -29,5 +31,9 @@
29
31
  "optionalDependencies": {
30
32
  "@tomflow/chatloop-tunnel-darwin-x64": "0.0.19",
31
33
  "@tomflow/chatloop-tunnel-darwin-arm64": "0.0.19"
32
- }
34
+ },
35
+ "bundleDependencies": [
36
+ "@tomflow/chatloop-context",
37
+ "@tomflow/chatloop-trace"
38
+ ]
33
39
  }