@tomflow/chatloop-tools 0.9.20 → 0.9.22

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 (137) hide show
  1. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  2. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  3. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  4. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  5. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  6. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  7. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  8. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  13. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  16. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  17. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  21. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  43. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  44. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  45. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  46. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  47. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  48. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  49. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  50. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  51. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  109. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  110. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  111. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  112. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  113. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  114. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  115. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  116. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  117. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  118. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  119. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  120. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  121. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  122. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  123. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  124. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  125. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  126. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  127. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  128. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  129. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  130. package/node_modules/ps-list/index.d.ts +76 -0
  131. package/node_modules/ps-list/index.js +366 -0
  132. package/node_modules/ps-list/license +9 -0
  133. package/node_modules/ps-list/package.json +44 -0
  134. package/node_modules/ps-list/readme.md +56 -0
  135. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  136. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  137. package/package.json +10 -2
@@ -0,0 +1,265 @@
1
+ // Trace Reader: bounded, scoped, read-only diagnostic and API usage views.
2
+ import {constants as FS,createReadStream,closeSync,fstatSync,openSync} from 'node:fs';
3
+ import {createInterface} from 'node:readline';
4
+
5
+ export function makeTraceReader(options,deps){
6
+ const {TRACE_SCHEMA_VERSION,fail,validStoredFamily,object,isId,safeScope,
7
+ safeRef,natural,keys,secureFile,eventRule,EVENT,CODE,COMPONENTS,STATUSES}=deps;
8
+ const OUTPUT=['time','schemaVersion','eventId','traceId','spanId','parentSpanId',
9
+ 'writerEpoch','writerSeq','component','event','projectRef','taskRef','sessionRef',
10
+ 'generation','requestId','actionId','status','errorCode','durationMs','api','apiName','evidenceRef'];
11
+ const publicEvent=v=>Object.fromEntries(OUTPUT.flatMap(k=>{
12
+ const value=k==='status'
13
+ ?(v.schemaVersion===1?v.traceStatus??v.status:v.status):v[k];
14
+ return value===undefined||value===null?[]:[[k,value]];
15
+ }));
16
+ // The on-disk log is evidence, not executable truth. Reject forged/malformed
17
+ // fields at the read boundary too; do not trust a matching projectRef alone.
18
+ const STORED_FIELDS=new Set(['time','schemaVersion','eventId','traceId',
19
+ 'spanId','parentSpanId','writerEpoch','writerSeq','component','event',
20
+ 'projectRef','taskRef','sessionRef','generation','requestId','actionId',
21
+ 'status','errorCode','durationMs','api','apiName','evidenceRef']);
22
+ const validStored=v=>object(v)
23
+ &&(v.schemaVersion===1||v.schemaVersion===TRACE_SCHEMA_VERSION)
24
+ &&(v.schemaVersion===1||Object.keys(v).every(k=>STORED_FIELDS.has(k)))
25
+ &&isId(v.eventId)&&isId(v.traceId)
26
+ &&isId(v.spanId)&&isId(v.writerEpoch)&&natural(v.writerSeq)
27
+ &&EVENT.test(v.event||'')&&COMPONENTS.has(v.component)
28
+ &&STATUSES.has(v.schemaVersion===1?v.traceStatus??v.status:v.status)
29
+ &&typeof v.time==='string'&&v.time.length<=40&&Number.isFinite(Date.parse(v.time))
30
+ &&safeScope(v.projectRef)
31
+ &&['parentSpanId','taskRef','sessionRef','requestId','actionId','evidenceRef']
32
+ .every(k=>v[k]==null||(k==='parentSpanId'?isId(v[k]):safeRef(v[k])))
33
+ &&(v.errorCode==null||typeof v.errorCode==='string'&&CODE.test(v.errorCode))
34
+ &&(v.generation==null||natural(v.generation))
35
+ &&(v.durationMs==null||natural(v.durationMs))
36
+ &&(v.event==='typed.api.call'||!Object.hasOwn(v,'apiName'))
37
+ &&validStoredFamily(v);
38
+ function filterInput(v,allowed){
39
+ keys(v,new Set(['traceId','sessionRef','projectRef','maxEvents']));
40
+ if(!safeScope(v.projectRef)||!allowed.includes(v.projectRef))
41
+ throw fail('TRACE_PROJECT_ACCESS_DENIED');
42
+ if(v.traceId!==undefined&&!isId(v.traceId))throw fail('TRACE_INVALID_ID');
43
+ if(v.sessionRef!==undefined&&!safeRef(v.sessionRef))
44
+ throw fail('TRACE_INVALID_REFERENCE');
45
+ if(!v.traceId&&!v.sessionRef)throw fail('TRACE_FILTER_REQUIRED');
46
+ const maxEvents=v.maxEvents??100;
47
+ if(!Number.isSafeInteger(maxEvents)||maxEvents<1||maxEvents>200)
48
+ throw fail('TRACE_INVALID_LIMIT');
49
+ return {...v,maxEvents};
50
+ }
51
+ function createTraceReader({filePath,allowedProjects,maxSegments=5}){
52
+ if(!Array.isArray(allowedProjects)||!allowedProjects.length||
53
+ allowedProjects.some(x=>!safeScope(x)))
54
+ throw fail('TRACE_PROJECT_SCOPE_REQUIRED');
55
+ if(!Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
56
+ throw fail('TRACE_ROTATION_INVALID');
57
+ async function query(opts){
58
+ const filter=filterInput(opts,allowedProjects);
59
+ const files=[...Array.from({length:maxSegments},(_,i)=>filePath+'.'+(maxSegments-i)),
60
+ filePath].map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
61
+ if(!files.length)return {events:[],matched:0,legacyUncorrelated:true,gapped:true,
62
+ errors:['TRACE_LOG_MISSING'],truncated:false};
63
+ if(files.reduce((sum,x)=>sum+x.stat.size,0)>64*1024*1024)
64
+ throw fail('TRACE_FILE_TOO_LARGE');
65
+ const seen=new Set(),events=[],errors=[],writerEpochs=new Set();
66
+ let matched=0,corrupt=0,legacy=0;
67
+ for(const item of files){
68
+ const fd=openSync(item.path,FS.O_RDONLY|FS.O_NOFOLLOW);
69
+ const opened=fstatSync(fd);
70
+ if(!opened.isFile()||(opened.mode&0o077)||process.getuid&&opened.uid!==process.getuid()){
71
+ closeSync(fd);throw fail('TRACE_FILE_UNTRUSTED');
72
+ }
73
+ const stream=createReadStream(item.path,{fd,autoClose:true,encoding:'utf8'});
74
+ const lines=createInterface({input:stream,crlfDelay:Infinity});
75
+ try{
76
+ for await(const line of lines){
77
+ if(!line.trim())continue;
78
+ if(Buffer.byteLength(line)>8192){corrupt++;continue}
79
+ let entry;try{entry=JSON.parse(line)}catch{corrupt++;continue}
80
+ // v1 is retained read-only evidence, never rewritten or promoted to
81
+ // the new typed API contract; unknown schemas stay untrusted.
82
+ if(entry.schemaVersion!==TRACE_SCHEMA_VERSION&&entry.schemaVersion!==1){
83
+ legacy++;continue;
84
+ }
85
+ if(entry.projectRef!==filter.projectRef||
86
+ filter.traceId&&entry.traceId!==filter.traceId||
87
+ filter.sessionRef&&entry.sessionRef!==filter.sessionRef)continue;
88
+ if(!validStored(entry)){corrupt++;continue}
89
+ if(seen.has(entry.eventId))continue;
90
+ seen.add(entry.eventId);matched++;
91
+ writerEpochs.add(entry.writerEpoch);
92
+ events.push(publicEvent(entry));
93
+ if(events.length>filter.maxEvents)events.shift();
94
+ }
95
+ }finally{lines.close();stream.destroy()}
96
+ }
97
+ if(corrupt)errors.push('TRACE_MALFORMED_LINES');
98
+ return {events,matched,legacyUncorrelated:legacy>0,gapped:corrupt>0,
99
+ // A restart is not proof of loss, but evidence continuity across epochs
100
+ // cannot be asserted by a log reader alone, even with later ACKs.
101
+ writerRestartUnverified:writerEpochs.size>1,
102
+ errors,truncated:matched>filter.maxEvents};
103
+ }
104
+ async function diagnose(opts){
105
+ const result=await query(opts);
106
+ const pending=new Map(),gaps=[...result.errors],unmatchedApiTerminals=[];
107
+ let lastConfirmed=null,unknown=false;
108
+ for(const e of result.events){
109
+ if(e.status==='CONFIRMED')lastConfirmed={
110
+ eventId:e.eventId,event:e.event,time:e.time,component:e.component
111
+ };
112
+ if(e.status==='UNKNOWN'||e.status==='BLOCKED')unknown=true;
113
+ // V2 API BEGIN and terminal always share one spanId, even when
114
+ // several sibling APIs share the same traceId. V1 used traceId.
115
+ const apiCall=e.event==='context.api'||e.event==='typed.api.call';
116
+ const id=apiCall?(e.schemaVersion===1?e.traceId:e.spanId):
117
+ e.actionId||e.requestId;
118
+ if(!id)continue;
119
+ if(e.status==='BEGIN'){
120
+ if(pending.has(id)&&apiCall)gaps.push('DUPLICATE_API_BEGIN');
121
+ pending.set(id,{event:e.event,apiCall,apiName:e.apiName||
122
+ e.api?.name||null,spanId:e.spanId,beginTime:e.time});
123
+ }else if(['CONFIRMED','FAILED','UNKNOWN','BLOCKED'].includes(e.status)){
124
+ if(apiCall&&!pending.has(id)&&!result.truncated)
125
+ unmatchedApiTerminals.push({event:e.event,spanId:e.spanId});
126
+ pending.delete(id);
127
+ }
128
+ }
129
+ const incompleteApiSpans=[...pending.values()].filter(x=>x.apiCall)
130
+ .slice(0,30);
131
+ if(incompleteApiSpans.length)gaps.push('MISSING_API_TERMINAL');
132
+ if(unmatchedApiTerminals.length)gaps.push('ORPHAN_API_TERMINAL');
133
+ if(result.truncated)gaps.push('TRACE_WINDOW_TRUNCATED');
134
+ if(result.writerRestartUnverified)gaps.push('TRACE_WRITER_RESTART_UNVERIFIED');
135
+ if(result.legacyUncorrelated)gaps.push('LEGACY_EVENTS_UNCORRELATED');
136
+ if(pending.size)gaps.push('MISSING_ACTION_RECEIPT');
137
+ if(!result.events.length)gaps.push('NO_MATCHING_EVENTS');
138
+ return {traceId:opts.traceId??null,projectRef:opts.projectRef,
139
+ inspected:result.events.length,totalMatched:result.matched,lastConfirmed,
140
+ incompleteApiSpans,unmatchedApiTerminals:unmatchedApiTerminals.slice(0,30),
141
+ lastEvent:result.events.at(-1)??null,unknown,gaps:[...new Set(gaps)],
142
+ confidence:gaps.length?'INCOMPLETE':'TRACE_ONLY',
143
+ retryDisposition:unknown||pending.size||gaps.length?
144
+ 'VERIFY_AUTHORITATIVE_RECEIPT_FIRST':'NO_AUTOMATIC_RETRY',
145
+ timeline:result.events};
146
+ }
147
+ // Operational API usage is a sanitized system-local observation view.
148
+ // It cannot read business projects, arguments, results or raw chat data.
149
+ async function apiUsage({windowMinutes=60,limit=100}={}){
150
+ if(!allowedProjects.includes('api_system'))
151
+ throw fail('TRACE_PROJECT_ACCESS_DENIED');
152
+ if(!Number.isSafeInteger(windowMinutes)||windowMinutes<1||windowMinutes>1440
153
+ ||!Number.isSafeInteger(limit)||limit<1||limit>200)
154
+ throw fail('TRACE_INVALID_LIMIT');
155
+ const now=Date.now(),since=now-windowMinutes*60000;
156
+ const calls=new Map(),seenEvents=new Set();
157
+ const files=[...Array.from({length:maxSegments},(_,i)=>
158
+ filePath+'.'+(maxSegments-i)),filePath]
159
+ .map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
160
+ if(files.reduce((n,x)=>n+x.stat.size,0)>64*1024*1024)
161
+ throw fail('TRACE_FILE_TOO_LARGE');
162
+ let malformed=0;
163
+ for(const item of files){
164
+ const fd=openSync(item.path,FS.O_RDONLY|FS.O_NOFOLLOW);
165
+ const opened=fstatSync(fd);
166
+ if(!opened.isFile()||(opened.mode&0o077)
167
+ ||process.getuid&&opened.uid!==process.getuid()){
168
+ closeSync(fd);throw fail('TRACE_FILE_UNTRUSTED');
169
+ }
170
+ const stream=createReadStream(item.path,{fd,autoClose:true,encoding:'utf8'});
171
+ const lines=createInterface({input:stream,crlfDelay:Infinity});
172
+ try{
173
+ for await(const line of lines){
174
+ if(!line.trim())continue;
175
+ if(Buffer.byteLength(line)>8192){malformed++;continue}
176
+ let v;try{v=JSON.parse(line)}catch{malformed++;continue}
177
+ // New event families provide their own safe usage projection.
178
+ // A Provider never acquires access to a Project by being registered.
179
+ if(!allowedProjects.includes(v?.projectRef))continue;
180
+ const rule=eventRule(v);
181
+ if(typeof rule?.usageName!=='function')continue;
182
+ if(!['BEGIN','CONFIRMED','FAILED'].includes(v.status))continue;
183
+ if(!validStored(v)){malformed++;continue}
184
+ if(seenEvents.has(v.eventId))continue;
185
+ seenEvents.add(v.eventId);
186
+ const time=Date.parse(v.time);
187
+ if(!Number.isFinite(time)||time<since||time>now+60000)continue;
188
+ let name;
189
+ try{
190
+ const view={...v};
191
+ if(object(view.api))view.api=Object.freeze({...view.api});
192
+ name=rule.usageName(Object.freeze(view));
193
+ }catch{malformed++;continue}
194
+ if(typeof name!=='string'||
195
+ !/^[a-zA-Z][a-zA-Z0-9_.:-]{1,126}$/.test(name)||
196
+ // New typed families cannot impersonate an existing MCP, Context,
197
+ // Extension, Trace or Tunnel API in a usage report.
198
+ !['context.api','typed.api.call'].includes(rule.id)
199
+ &&!name.startsWith(rule.id+'.')){
200
+ malformed++;continue
201
+ }
202
+ // V2 root and child API calls both use their own stable spanId.
203
+ // Grouping V2 roots by shared traceId can silently hide an orphan
204
+ // BEGIN when another sibling succeeds. V1 used traceId.
205
+ const callKey=v.schemaVersion===1?v.traceId:v.spanId;
206
+ const key=v.projectRef+':'+v.event+':'+callKey;
207
+ const call=calls.get(key)||{api:name,begin:false,end:null,durationMs:null};
208
+ if(call.api!==name){malformed++;continue}
209
+ if(v.status==='BEGIN')call.begin=true;
210
+ if(v.status==='CONFIRMED'||v.status==='FAILED'){
211
+ if(call.end&&call.end!==v.status)call.end='UNKNOWN';
212
+ else if(!call.end)call.end=v.status;
213
+ if(Number.isSafeInteger(v.durationMs))
214
+ call.durationMs=v.durationMs;
215
+ }
216
+ calls.set(key,call);
217
+ }
218
+ }finally{lines.close();stream.destroy()}
219
+ }
220
+ // Count calls by their BEGIN inside the time window, never by the
221
+ // number of log records. An unmatched completion is not a new API call.
222
+ const counts=new Map();
223
+ let orphanCompletions=0;
224
+ for(const call of calls.values()){
225
+ if(!call.begin){if(call.end)orphanCompletions++;continue}
226
+ const entry=counts.get(call.api)||{api:call.api,calls:0,
227
+ success:0,failures:0,incomplete:0,totalDurationMs:0,durationSamples:0,
228
+ maxDurationMs:0};
229
+ entry.calls++;
230
+ if(call.end==='CONFIRMED')entry.success++;
231
+ else if(call.end==='FAILED')entry.failures++;
232
+ else entry.incomplete++;
233
+ if(call.end&&!['UNKNOWN'].includes(call.end)
234
+ &&Number.isSafeInteger(call.durationMs)){
235
+ entry.totalDurationMs+=call.durationMs;
236
+ entry.durationSamples++;
237
+ entry.maxDurationMs=Math.max(entry.maxDurationMs,call.durationMs);
238
+ }
239
+ counts.set(call.api,entry);
240
+ }
241
+ const all=[...counts.values()].map(({totalDurationMs,durationSamples,...entry})=>({
242
+ ...entry,avgDurationMs:durationSamples
243
+ ?Number((totalDurationMs/durationSamples).toFixed(2)):null,
244
+ maxDurationMs:durationSamples?entry.maxDurationMs:null
245
+ }));
246
+ all.sort((a,b)=>b.calls-a.calls||a.api.localeCompare(b.api));
247
+ const api=all.slice(0,limit).map(entry=>({
248
+ ...entry,callsPerMinute:Number((entry.calls/windowMinutes).toFixed(3))
249
+ }));
250
+ return {scope:'api_system',windowMinutes,
251
+ calls:all.reduce((n,x)=>n+x.calls,0),
252
+ success:all.reduce((n,x)=>n+x.success,0),
253
+ failures:all.reduce((n,x)=>n+x.failures,0),
254
+ incomplete:all.reduce((n,x)=>n+x.incomplete,0),
255
+ orphanCompletions,api,malformed,limited:all.length>limit,
256
+ source:files.length?'TRACE_ONLY':'TRACE_LOG_MISSING'};
257
+ }
258
+ return {query,diagnose,apiUsage,health:()=>{
259
+ const st=secureFile(filePath);
260
+ return {status:st?'READABLE':'TRACE_LOG_MISSING',
261
+ bytes:st?.size??0,projectScopes:allowedProjects.length};
262
+ }};
263
+ }
264
+ return createTraceReader(options);
265
+ }
@@ -0,0 +1,205 @@
1
+ import {makeTraceReader} from './trace-reader.mjs';
2
+ import {randomUUID} from 'node:crypto';
3
+ import {constants as FS,closeSync,fstatSync,lstatSync,openSync,writeSync,renameSync,unlinkSync} from 'node:fs';
4
+ import {dirname,isAbsolute} from 'node:path';
5
+
6
+ export const TRACE_SCHEMA_VERSION=2;
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','api','apiName']);
17
+ const fail=code=>Object.assign(new Error(code),{code});
18
+ let eventRules=null;
19
+ // Private composition port. The npm root supplies only the generated,
20
+ // source-reviewed event contracts; callers never register runtime plugins.
21
+ export function configureTraceEvents(definitions){
22
+ if(eventRules)throw fail('TRACE_EVENTS_ALREADY_CONFIGURED');
23
+ if(!Array.isArray(definitions)||!definitions.length)
24
+ throw fail('TRACE_EVENTS_INVALID');
25
+ const rules=new Map();
26
+ for(const rule of definitions){
27
+ if(!rule||typeof rule.id!=='string'||rules.has(rule.id)||
28
+ rule.schemaVersion!==TRACE_SCHEMA_VERSION||
29
+ typeof rule.validate!=='function'||typeof rule.errorCode!=='string')
30
+ throw fail('TRACE_EVENTS_INVALID');
31
+ rules.set(rule.id,rule);
32
+ }
33
+ if(!rules.has('context.api'))throw fail('TRACE_REQUIRED_EVENT_SCHEMA_MISSING');
34
+ eventRules=rules;
35
+ }
36
+ function eventRule(v){
37
+ if(!eventRules)throw fail('TRACE_EVENTS_NOT_COMPOSED');
38
+ return eventRules.get(v.event);
39
+ }
40
+ function ruleAccepts(rule,v){
41
+ try{
42
+ // A Provider validates a read-only projection. It must never rewrite the
43
+ // caller's scope, status, identity, or the on-disk event being diagnosed.
44
+ const view={...v};
45
+ if(object(view.api))view.api=Object.freeze({...view.api});
46
+ return rule.validate(Object.freeze(view))===true;
47
+ }catch{return false}
48
+ }
49
+ function validStoredFamily(v){
50
+ // A pre-existing API observation without the original caller's IDs cannot
51
+ // be promoted into trusted correlated evidence by the Reader.
52
+ if(!validApiCorrelation(v))return false;
53
+ // The reserved api field belongs solely to the Context API event, no
54
+ // matter how permissive an additional Provider's validator may become.
55
+ if(v.schemaVersion===TRACE_SCHEMA_VERSION&&v.event!=='context.api'
56
+ &&Object.hasOwn(v,'api'))return false;
57
+ const rule=eventRule(v);
58
+ return rule ? v.schemaVersion===rule.schemaVersion&&ruleAccepts(rule,v)
59
+ :!v.event.startsWith('typed.')&&v.api==null;
60
+ }
61
+ const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
62
+ const isId=v=>typeof v==='string'&&UUID.test(v);
63
+ const validApiCorrelation=v=>!['typed.api.call','context.api'].includes(v?.event)
64
+ ||isId(v.traceId)&&isId(v.spanId)&&
65
+ (v.parentSpanId==null||isId(v.parentSpanId)&&v.parentSpanId!==v.spanId);
66
+ const safeScope=v=>typeof v==='string'&&SCOPE.test(v);
67
+ const safeRef=v=>typeof v==='string'&&REF.test(v);
68
+ const natural=v=>Number.isSafeInteger(v)&&v>=0;
69
+ const keys=(v,allowed)=>{
70
+ if(!object(v))throw fail('TRACE_INVALID_OBJECT');
71
+ for(const k of Object.keys(v))if(!allowed.has(k))throw fail('TRACE_INVALID_FIELD');
72
+ };
73
+ const bytes=v=>Buffer.byteLength(JSON.stringify(v),'utf8');
74
+ const nullable=(v,test,code)=>{
75
+ if(v!==undefined&&v!==null&&!test(v))throw fail(code);
76
+ return v??null;
77
+ };
78
+ export function createTrace(){return {traceId:randomUUID(),spanId:randomUUID()};}
79
+ function normalize(v,epoch,seq){
80
+ keys(v,ALLOWED);
81
+ if(!EVENT.test(v.event||'')||!COMPONENTS.has(v.component)||
82
+ !STATUSES.has(v.status))throw fail('TRACE_INVALID_EVENT');
83
+ // Event-family-specific contracts validate the same canonical v2 envelope
84
+ // in Writer and Reader. A generic event must not impersonate an API call.
85
+ if(v.event!=='context.api'&&Object.hasOwn(v,'api'))
86
+ throw fail('TRACE_INVALID_API');
87
+ if(v.event!=='typed.api.call'&&Object.hasOwn(v,'apiName'))
88
+ throw fail('TRACE_INVALID_API_USAGE');
89
+ const rule=eventRule(v);
90
+ if(!rule&&v.event.startsWith('typed.'))
91
+ throw fail('TRACE_EVENT_UNREGISTERED');
92
+ if(rule ? !ruleAccepts(rule,v) : v.api!==undefined)
93
+ throw fail(rule?.errorCode||'TRACE_INVALID_API');
94
+ // NEVER fabricate a trace/span for an API call. This check is shared by
95
+ // all six npm consumers through the sole Trace Writer/Reader contract.
96
+ if(!validApiCorrelation(v))throw fail('TRACE_INVALID_API_CORRELATION');
97
+ for(const k of ['eventId','traceId','spanId'])
98
+ if(v[k]!==undefined&&!isId(v[k]))throw fail('TRACE_INVALID_ID');
99
+ const entry={
100
+ time:v.timestamp===undefined?new Date().toISOString():v.timestamp,
101
+ schemaVersion:TRACE_SCHEMA_VERSION,eventId:v.eventId||randomUUID(),
102
+ traceId:v.traceId||randomUUID(),spanId:v.spanId||randomUUID(),
103
+ parentSpanId:nullable(v.parentSpanId,isId,'TRACE_INVALID_ID'),
104
+ writerEpoch:epoch,writerSeq:seq,component:v.component,event:v.event,
105
+ projectRef:nullable(v.projectRef,safeScope,'TRACE_INVALID_SCOPE'),
106
+ taskRef:nullable(v.taskRef,safeRef,'TRACE_INVALID_REFERENCE'),
107
+ sessionRef:nullable(v.sessionRef,safeRef,'TRACE_INVALID_REFERENCE'),
108
+ generation:nullable(v.generation,natural,'TRACE_INVALID_NUMBER'),
109
+ requestId:nullable(v.requestId,safeRef,'TRACE_INVALID_REFERENCE'),
110
+ actionId:nullable(v.actionId,safeRef,'TRACE_INVALID_REFERENCE'),
111
+ status:v.status,errorCode:nullable(v.errorCode,x=>CODE.test(x),'TRACE_INVALID_ERROR_CODE'),
112
+ durationMs:nullable(v.durationMs,natural,'TRACE_INVALID_NUMBER'),
113
+ api:v.api?{name:v.api.name,surface:v.api.surface,mode:v.api.mode}:null,
114
+ apiName:v.apiName??null,
115
+ evidenceRef:nullable(v.evidenceRef,safeRef,'TRACE_INVALID_REFERENCE')
116
+ };
117
+ if(typeof entry.time!=='string'||entry.time.length>40||
118
+ !Number.isFinite(Date.parse(entry.time)))throw fail('TRACE_INVALID_TIMESTAMP');
119
+ // JSONL must stay lean: omit absent optional columns, never serialize
120
+ // redundant null fields. Read projections can still expose stable nulls.
121
+ const compact=Object.fromEntries(Object.entries(entry).filter(([,v])=>v!==null));
122
+ if(bytes(compact)>4096)throw fail('TRACE_EVENT_TOO_LARGE');
123
+ return compact;
124
+ }
125
+ // Strict file owner, permissions, no directory creation and no symlink escapes.
126
+ function secureFile(filePath){
127
+ if(typeof filePath!=='string'||!isAbsolute(filePath))throw fail('TRACE_PATH_INVALID');
128
+ let dir;try{dir=lstatSync(dirname(filePath))}catch{throw fail('TRACE_DIRECTORY_UNAVAILABLE')}
129
+ if(!dir.isDirectory()||dir.isSymbolicLink()||(dir.mode&0o077)||
130
+ process.getuid&&dir.uid!==process.getuid())throw fail('TRACE_DIRECTORY_UNTRUSTED');
131
+ let st;
132
+ try{st=lstatSync(filePath)}
133
+ catch(e){if(e.code==='ENOENT')return null;throw e}
134
+ // existsSync follows symlinks: a dangling link must not be mistaken for an
135
+ // absent log or rotation segment and silently discarded from diagnosis.
136
+ if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)||
137
+ process.getuid&&st.uid!==process.getuid())throw fail('TRACE_FILE_UNTRUSTED');
138
+ return st;
139
+ }
140
+ export function createTraceWriter({
141
+ filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5
142
+ }){
143
+ if(typeof enableRotation!=='boolean'||!Number.isSafeInteger(rotateBytes)||
144
+ rotateBytes<512||rotateBytes>10*1024*1024||
145
+ !Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
146
+ throw fail('TRACE_ROTATION_INVALID');
147
+ const epoch=randomUUID();let seq=0,failures=0,lastError=null,rotations=0;
148
+ const rotateIfNeeded=lineBytes=>{
149
+ // Legacy data is never moved until an operator explicitly enables
150
+ // rotation after preserving its historical evidence.
151
+ if(!enableRotation)return;
152
+ const old=secureFile(filePath);
153
+ if(!old||old.size+lineBytes<=rotateBytes)return;
154
+ const oldest=filePath+'.'+maxSegments;
155
+ if(secureFile(oldest))unlinkSync(oldest);
156
+ for(let i=maxSegments-1;i>=1;i--){
157
+ const from=filePath+'.'+i;
158
+ if(secureFile(from))renameSync(from,filePath+'.'+(i+1));
159
+ }
160
+ renameSync(filePath,filePath+'.1');
161
+ rotations++;
162
+ };
163
+ function append(entry){
164
+ let fd;
165
+ try{
166
+ rotateIfNeeded(bytes(entry)+1);
167
+ secureFile(filePath);
168
+ fd=openSync(filePath,FS.O_WRONLY|FS.O_APPEND|FS.O_CREAT|FS.O_NOFOLLOW,0o600);
169
+ const st=fstatSync(fd);
170
+ if(!st.isFile()||(st.mode&0o077)||
171
+ process.getuid&&st.uid!==process.getuid())throw fail('TRACE_FILE_UNTRUSTED');
172
+ writeSync(fd,JSON.stringify(entry)+'\n');
173
+ seq++;lastError=null;
174
+ return {eventId:entry.eventId,traceId:entry.traceId,
175
+ writerEpoch:epoch,writerSeq:seq};
176
+ }catch(e){failures++;lastError=e.code||'TRACE_WRITE_FAILED';throw e}
177
+ finally{if(fd!==undefined)closeSync(fd)}
178
+ }
179
+ const record=v=>append(normalize(v,epoch,seq+1));
180
+ const recordControl=(event,detail={})=>{
181
+ // All sources now emit the same typed v2 event. Historical tool summaries,
182
+ // traceStatus aliases and arbitrary result columns are never written.
183
+ const status=detail?.status==='FAILED'||/(?:error|fatal)/.test(event)?'FAILED':
184
+ detail?.status==='UNKNOWN'||
185
+ ['PARTIAL','DEGRADED','UNCONFIRMED','TIMEOUT'].includes(detail?.status)?'UNKNOWN':
186
+ detail?.status==='BLOCKED'||event.includes('blocked')?'BLOCKED':'CONFIRMED';
187
+ return record({event,component:'supervisor',status,
188
+ ...(safeRef(detail?.requestId)?{requestId:detail.requestId}:{}),
189
+ ...(typeof detail?.errorCode==='string'&&CODE.test(detail.errorCode)?
190
+ {errorCode:detail.errorCode}:{})
191
+ });
192
+ };
193
+ const health=()=>({status:lastError?'TRACE_DEGRADED':'OK',
194
+ errorCode:lastError,failures,writerEpoch:epoch,writerSeq:seq,
195
+ rotationEnabled:enableRotation,rotations});
196
+ return {record,recordControl,health};
197
+ }
198
+
199
+ // Runtime event definitions remain bound to this exact module instance;
200
+ // dynamic import isolation in the Trace SDK must not be lost by refactoring.
201
+ export function createTraceReader(options){
202
+ return makeTraceReader(options,{TRACE_SCHEMA_VERSION,fail,validStoredFamily,
203
+ object,isId,safeScope,safeRef,natural,keys,secureFile,eventRule,
204
+ EVENT,CODE,COMPONENTS,STATUSES});
205
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@tomflow/chatloop-trace",
3
+ "version": "0.4.4",
4
+ "description": "Trace SDK and scoped read-only diagnostics for Chat Loop",
5
+ "type": "module",
6
+ "engines": {
7
+ "node": ">=20"
8
+ },
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "exports": {
13
+ ".": "./index.mjs"
14
+ },
15
+ "files": [
16
+ "index.mjs",
17
+ "events.generated.mjs",
18
+ "events/",
19
+ "scripts/",
20
+ "lib/",
21
+ "README.md"
22
+ ],
23
+ "scripts": {
24
+ "build:events": "node ./scripts/build-events.mjs",
25
+ "build:events:check": "node ./scripts/build-events.mjs --check",
26
+ "pretest": "node ./scripts/build-events.mjs --check",
27
+ "prepack": "node ./scripts/build-events.mjs --check",
28
+ "test": "node --test test/*.test.mjs"
29
+ }
30
+ }
@@ -0,0 +1,68 @@
1
+ // Deterministic Trace event-family contracts. No runtime plugin discovery,
2
+ // user-controlled module loading or extra log writers.
3
+ import {createHash} from 'node:crypto';
4
+ import {readFileSync,readdirSync,writeFileSync} from 'node:fs';
5
+ import {dirname,join,resolve} from 'node:path';
6
+ import {fileURLToPath,pathToFileURL} from 'node:url';
7
+ const root=dirname(dirname(fileURLToPath(import.meta.url)));
8
+ const fail=code=>Object.assign(Error(code),{code});
9
+ const ident=/^[a-z][a-z0-9._-]{1,95}$/;
10
+ const errCode=/^TRACE_[A-Z0-9_]{1,95}$/;
11
+ export async function compileTraceEvents(source=join(root,'events')){
12
+ const files=readdirSync(source).filter(file=>file.endsWith('.mjs')).sort();
13
+ if(!files.length)throw fail('TRACE_EVENTS_EMPTY');
14
+ const ids=new Set(),entries=[];
15
+ let requiredApi=null;
16
+ for(const file of files){
17
+ if(!/^[a-z][a-z0-9._-]*\.mjs$/.test(file))
18
+ throw fail('TRACE_EVENT_FILENAME_INVALID');
19
+ const path=resolve(source,file);
20
+ const hash=createHash('sha256').update(readFileSync(path)).digest('hex');
21
+ const {capability:p}=await import(pathToFileURL(path).href+'?sha256='+hash);
22
+ if(!p||p.id!==file.slice(0,-4)||!ident.test(p.id)||ids.has(p.id)||
23
+ p.schemaVersion!==2||typeof p.validate!=='function'||
24
+ typeof p.description!=='string'||!p.description.trim()||
25
+ (p.usageName!==undefined&&typeof p.usageName!=='function')||
26
+ !errCode.test(p.errorCode||''))
27
+ throw fail('TRACE_EVENT_CAPABILITY_INVALID');
28
+ if(p.id!=='context.api'&&!p.id.startsWith('typed.'))
29
+ throw fail('TRACE_EVENT_NAMESPACE_INVALID');
30
+ ids.add(p.id);
31
+ if(p.id==='context.api')requiredApi=p;
32
+ entries.push(file);
33
+ }
34
+ if(!ids.has('context.api'))
35
+ throw fail('TRACE_REQUIRED_EVENT_SCHEMA_MISSING');
36
+ // The original sensitive Context API event cannot quietly become generic
37
+ // when a provider is removed, weakened, or mistakenly renamed.
38
+ const api=requiredApi;
39
+ const valid={component:'context',event:'context.api',status:'BEGIN',
40
+ api:{name:'task.open',surface:'sdk',mode:'read'}};
41
+ if(!api.validate(valid)||
42
+ api.validate({...valid,status:'UNKNOWN'})||
43
+ api.validate({...valid,component:'extension'})||
44
+ api.validate({...valid,api:{...valid.api,secret:'raw'}})||
45
+ api.validate({...valid,api:{...valid.api,name:'secret chat text'}}))
46
+ throw fail('TRACE_REQUIRED_EVENT_SCHEMA_INVALID');
47
+ const imports=entries.map((file,i)=>
48
+ "import {capability as e"+i+"} from './events/"+file+"';").join('\n');
49
+ return '// GENERATED by scripts/build-events.mjs — do not edit.\n'+imports+
50
+ '\nexport const eventCapabilities=Object.freeze(['+
51
+ entries.map((_,i)=>'e'+i).join(',')+']);\n';
52
+ }
53
+ async function main(){
54
+ const expected=await compileTraceEvents();
55
+ const target=join(root,'events.generated.mjs');
56
+ if(process.argv.includes('--check')){
57
+ let actual;
58
+ try{actual=readFileSync(target,'utf8')}catch{}
59
+ if(actual!==expected)throw fail('TRACE_EVENTS_BUILD_STALE');
60
+ if(process.env.npm_lifecycle_event!=='prepack')
61
+ console.log('TRACE_EVENTS_CURRENT');
62
+ }else{
63
+ writeFileSync(target,expected);
64
+ console.log('TRACE_EVENTS_BUILT');
65
+ }
66
+ }
67
+ if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))
68
+ await main();
@@ -0,0 +1,76 @@
1
+ export type Options = {
2
+ /**
3
+ Include other users' processes as well as your own.
4
+
5
+ On Windows this has no effect and will always be the user's own processes.
6
+
7
+ @default true
8
+ */
9
+ readonly all?: boolean;
10
+ };
11
+
12
+ export type ProcessDescriptor = {
13
+ readonly pid: number;
14
+ readonly name: string;
15
+ readonly ppid: number;
16
+
17
+ /**
18
+ Full command line with arguments.
19
+
20
+ Not supported on Windows.
21
+ */
22
+ readonly cmd?: string;
23
+
24
+ /**
25
+ CPU usage as a percentage (0-100).
26
+
27
+ Not supported on Windows.
28
+ */
29
+ readonly cpu?: number;
30
+
31
+ /**
32
+ Memory usage as a percentage (0-100).
33
+
34
+ Not supported on Windows.
35
+ */
36
+ readonly memory?: number;
37
+
38
+ /**
39
+ User ID of the process owner.
40
+
41
+ Not supported on Windows.
42
+ */
43
+ readonly uid?: number;
44
+
45
+ /**
46
+ Best-effort attempt to get the full executable path.
47
+ - Linux: Reads from `/proc/{pid}/exe` when available
48
+ - macOS: Extracted from command line when possible
49
+ - Falls back to `comm` (which may be truncated)
50
+
51
+ Not supported on Windows.
52
+ */
53
+ readonly path?: string;
54
+
55
+ /**
56
+ The date and time when the process was started.
57
+
58
+ Not supported on Windows. May be `undefined` if the date cannot be parsed.
59
+ */
60
+ readonly startTime?: Date;
61
+ };
62
+
63
+ /**
64
+ Get running processes.
65
+
66
+ @returns A list of running processes.
67
+
68
+ @example
69
+ ```
70
+ import psList from 'ps-list';
71
+
72
+ console.log(await psList());
73
+ //=> [{pid: 3213, name: 'node', cmd: 'node test.js', ppid: 1, uid: 501, cpu: 0.1, memory: 1.5, path: '/usr/local/bin/node', startTime: 2025-01-15T10:30:00.000Z}, …]
74
+ ```
75
+ */
76
+ export default function psList(options?: Options): Promise<ProcessDescriptor[]>;