@tomflow/chatloop-tools 0.9.62 → 0.9.64

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 (154) hide show
  1. package/README.md +13 -1
  2. package/index.mjs +7 -7
  3. package/lib/context-control-run.mjs +23 -5
  4. package/lib/extension-proxy.mjs +29 -10
  5. package/lib/native-owner-v2.mjs +128 -0
  6. package/lib/release-health-checks.mjs +29 -5
  7. package/lib/trace-gateway.mjs +3 -1
  8. package/package.json +3 -13
  9. package/providers/extension.mjs +59 -16
  10. package/node_modules/@tomflow/chatloop-context/README.md +0 -240
  11. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -48
  12. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +0 -151
  13. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +0 -376
  14. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +0 -266
  15. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +0 -134
  16. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +0 -82
  17. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +0 -349
  18. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +0 -72
  19. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +0 -73
  20. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +0 -507
  21. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +0 -11
  22. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +0 -192
  23. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +0 -277
  24. package/node_modules/@tomflow/chatloop-context/index.mjs +0 -236
  25. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +0 -86
  26. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +0 -77
  27. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +0 -1989
  28. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +0 -69
  29. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +0 -285
  30. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -298
  31. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -286
  32. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +0 -115
  33. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +0 -51
  34. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +0 -75
  35. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +0 -262
  36. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +0 -246
  37. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +0 -147
  38. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +0 -54
  39. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +0 -375
  40. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +0 -397
  41. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +0 -183
  42. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +0 -13
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -111
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -107
  45. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +0 -118
  46. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +0 -20
  47. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +0 -316
  48. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -153
  49. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +0 -19
  50. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +0 -117
  51. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +0 -97
  52. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -169
  53. package/node_modules/@tomflow/chatloop-context/package.json +0 -40
  54. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +0 -114
  55. package/node_modules/@tomflow/chatloop-extension/README.md +0 -124
  56. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +0 -13
  57. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +0 -153
  58. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +0 -207
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +0 -1
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +0 -1
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +0 -1
  62. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +0 -1
  63. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +0 -1
  64. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +0 -1
  65. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +0 -1
  66. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +0 -1
  67. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +0 -1
  68. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +0 -1
  69. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +0 -1
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +0 -123
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +0 -183
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +0 -340
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +0 -2
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +0 -241
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +0 -393
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +0 -2
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +0 -56
  78. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +0 -9
  79. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +0 -20
  80. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +0 -77
  81. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +0 -52
  82. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +0 -295
  83. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +0 -24
  84. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +0 -2
  85. package/node_modules/@tomflow/chatloop-extension/extension/background.js +0 -17
  86. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +0 -5
  87. package/node_modules/@tomflow/chatloop-extension/extension/content.js +0 -40
  88. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +0 -9
  89. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +0 -17
  90. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +0 -6
  91. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +0 -9
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +0 -2
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +0 -275
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +0 -84
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +0 -107
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +0 -36
  97. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +0 -299
  98. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +0 -144
  99. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +0 -171
  100. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +0 -109
  101. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +0 -154
  102. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +0 -259
  103. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +0 -42
  104. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +0 -25
  105. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +0 -99
  106. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +0 -17
  107. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +0 -17
  108. package/node_modules/@tomflow/chatloop-extension/extension/session.html +0 -6
  109. package/node_modules/@tomflow/chatloop-extension/extension/start.html +0 -6
  110. package/node_modules/@tomflow/chatloop-extension/extension/status.html +0 -6
  111. package/node_modules/@tomflow/chatloop-extension/extension/text.html +0 -17
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +0 -136
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +0 -218
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +0 -124
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +0 -296
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +0 -186
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +0 -126
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +0 -230
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +0 -163
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +0 -345
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +0 -192
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +0 -161
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +0 -75
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +0 -197
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +0 -205
  126. package/node_modules/@tomflow/chatloop-extension/index.mjs +0 -71
  127. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +0 -19
  128. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +0 -82
  129. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +0 -303
  130. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +0 -83
  131. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +0 -45
  132. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +0 -115
  133. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +0 -75
  134. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +0 -185
  135. package/node_modules/@tomflow/chatloop-extension/package.json +0 -38
  136. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +0 -138
  137. package/node_modules/@tomflow/chatloop-trace/README.md +0 -118
  138. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +0 -23
  139. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +0 -22
  140. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +0 -4
  141. package/node_modules/@tomflow/chatloop-trace/index.mjs +0 -59
  142. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +0 -273
  143. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +0 -308
  144. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +0 -140
  145. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -236
  146. package/node_modules/@tomflow/chatloop-trace/package.json +0 -30
  147. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +0 -68
  148. package/node_modules/ps-list/index.d.ts +0 -76
  149. package/node_modules/ps-list/index.js +0 -366
  150. package/node_modules/ps-list/license +0 -9
  151. package/node_modules/ps-list/package.json +0 -44
  152. package/node_modules/ps-list/readme.md +0 -56
  153. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  154. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
@@ -1,308 +0,0 @@
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
- const MAX_TRACE_READ_BYTES=2*1024*1024*1024;
4
- const MAX_TRACE_EVENT_IDS=200_000; // Bounded dedup and API-usage state.
5
- const MAX_LINE_BYTES=8192;
6
- // readLine interfaces allocate the entire line before exposing it. A torn
7
- // log without LF may reach gigabytes; retain at most one validated line.
8
- async function* boundedLines(stream){
9
- let held='',heldBytes=0,oversize=false;
10
- for await(const chunk of stream){
11
- let start=0;
12
- while(start<chunk.length){
13
- const end=chunk.indexOf('\n',start);
14
- const part=chunk.slice(start,end<0?chunk.length:end);
15
- if(!oversize){
16
- heldBytes+=Buffer.byteLength(part,'utf8');
17
- if(heldBytes>MAX_LINE_BYTES){oversize=true;held=''}
18
- else held+=part;
19
- }
20
- if(end<0)break;
21
- yield oversize?null:held.replace(/\r$/,'');
22
- held='';heldBytes=0;oversize=false;start=end+1;
23
- }
24
- }
25
- if(oversize||held.length)yield oversize?null:held.replace(/\r$/,'');
26
- }
27
-
28
- export function makeTraceReader(options,deps){
29
- const {TRACE_SCHEMA_VERSION,fail,validStoredFamily,object,isId,safeScope,
30
- safeRef,natural,keys,secureFile,eventRule,EVENT,CODE,COMPONENTS,STATUSES}=deps;
31
- const OUTPUT=['time','schemaVersion','eventId','traceId','spanId','parentSpanId',
32
- 'writerEpoch','writerSeq','component','event','projectRef','taskRef','sessionRef',
33
- 'generation','requestId','actionId','status','errorCode','durationMs','api','apiName','evidenceRef'];
34
- const publicEvent=v=>Object.fromEntries(OUTPUT.flatMap(k=>{
35
- const value=k==='status'
36
- ?(v.schemaVersion===1?v.traceStatus??v.status:v.status):v[k];
37
- return value===undefined||value===null?[]:[[k,value]];
38
- }));
39
- // The on-disk log is evidence, not executable truth. Reject forged/malformed
40
- // fields at the read boundary too; do not trust a matching projectRef alone.
41
- const STORED_FIELDS=new Set(['time','schemaVersion','eventId','traceId',
42
- 'spanId','parentSpanId','writerEpoch','writerSeq','component','event',
43
- 'projectRef','taskRef','sessionRef','generation','requestId','actionId',
44
- 'status','errorCode','durationMs','api','apiName','evidenceRef']);
45
- const validStored=v=>object(v)
46
- &&(v.schemaVersion===1||v.schemaVersion===TRACE_SCHEMA_VERSION)
47
- &&(v.schemaVersion===1||Object.keys(v).every(k=>STORED_FIELDS.has(k)))
48
- &&isId(v.eventId)&&isId(v.traceId)
49
- &&isId(v.spanId)&&isId(v.writerEpoch)&&natural(v.writerSeq)
50
- &&EVENT.test(v.event||'')&&COMPONENTS.has(v.component)
51
- &&STATUSES.has(v.schemaVersion===1?v.traceStatus??v.status:v.status)
52
- &&typeof v.time==='string'&&v.time.length<=40&&Number.isFinite(Date.parse(v.time))
53
- &&safeScope(v.projectRef)
54
- &&['parentSpanId','taskRef','sessionRef','requestId','actionId','evidenceRef']
55
- .every(k=>v[k]==null||(k==='parentSpanId'?isId(v[k]):safeRef(v[k])))
56
- &&(v.errorCode==null||typeof v.errorCode==='string'&&CODE.test(v.errorCode))
57
- &&(v.generation==null||natural(v.generation))
58
- &&(v.durationMs==null||natural(v.durationMs))
59
- &&(v.event==='typed.api.call'||!Object.hasOwn(v,'apiName'))
60
- &&validStoredFamily(v);
61
- function filterInput(v,allowed){
62
- keys(v,new Set(['traceId','sessionRef','projectRef','maxEvents']));
63
- if(!safeScope(v.projectRef)||!allowed.includes(v.projectRef))
64
- throw fail('TRACE_PROJECT_ACCESS_DENIED');
65
- if(v.traceId!==undefined&&!isId(v.traceId))throw fail('TRACE_INVALID_ID');
66
- if(v.sessionRef!==undefined&&!safeRef(v.sessionRef))
67
- throw fail('TRACE_INVALID_REFERENCE');
68
- if(!v.traceId&&!v.sessionRef)throw fail('TRACE_FILTER_REQUIRED');
69
- const maxEvents=v.maxEvents??100;
70
- if(!Number.isSafeInteger(maxEvents)||maxEvents<1||maxEvents>200)
71
- throw fail('TRACE_INVALID_LIMIT');
72
- return {...v,maxEvents};
73
- }
74
- function createTraceReader({filePath,allowedProjects,maxSegments=5}){
75
- if(!Array.isArray(allowedProjects)||!allowedProjects.length||
76
- allowedProjects.some(x=>!safeScope(x)))
77
- throw fail('TRACE_PROJECT_SCOPE_REQUIRED');
78
- if(!Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
79
- throw fail('TRACE_ROTATION_INVALID');
80
- // Both diagnosis and API usage use the same secured segment inventory
81
- // and aggregate read budget. No second enumeration policy can drift.
82
- const scopedFiles=()=>{
83
- const files=[...Array.from({length:maxSegments},(_,i)=>
84
- filePath+'.'+(maxSegments-i)),filePath]
85
- .map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
86
- if(files.reduce((total,x)=>total+x.stat.size,0)>MAX_TRACE_READ_BYTES)
87
- throw fail('TRACE_FILE_TOO_LARGE');
88
- return files;
89
- };
90
- const openVerifiedStream=item=>{
91
- const fd=openSync(item.path,FS.O_RDONLY|FS.O_NOFOLLOW);
92
- try{
93
- const opened=fstatSync(fd);
94
- if(!opened.isFile()||(opened.mode&0o077)
95
- ||process.getuid&&opened.uid!==process.getuid())
96
- throw fail('TRACE_FILE_UNTRUSTED');
97
- return createReadStream(item.path,{fd,autoClose:true,encoding:'utf8'});
98
- }catch(error){
99
- closeSync(fd);
100
- throw error;
101
- }
102
- };
103
- async function query(opts){
104
- const filter=filterInput(opts,allowedProjects);
105
- const files=scopedFiles();
106
- if(!files.length)return {events:[],matched:0,legacyUncorrelated:true,gapped:true,
107
- errors:['TRACE_LOG_MISSING'],truncated:false};
108
- const seen=new Set(),events=[],errors=[],writerEpochs=new Set();
109
- let matched=0,corrupt=0,legacy=0;
110
- for(const item of files){
111
- const stream=openVerifiedStream(item);
112
- try{
113
- for await(const line of boundedLines(stream)){
114
- if(line===null){corrupt++;continue}
115
- if(!line.trim())continue
116
- let entry;try{entry=JSON.parse(line)}catch{corrupt++;continue}
117
- if(!object(entry)){corrupt++;continue}
118
- // v1 is retained read-only evidence, never rewritten or promoted to
119
- // the new typed API contract; unknown schemas stay untrusted.
120
- if(entry.schemaVersion!==TRACE_SCHEMA_VERSION&&entry.schemaVersion!==1){
121
- legacy++;continue;
122
- }
123
- if(entry.projectRef!==filter.projectRef||
124
- filter.traceId&&entry.traceId!==filter.traceId||
125
- filter.sessionRef&&entry.sessionRef!==filter.sessionRef)continue;
126
- if(!validStored(entry)){corrupt++;continue}
127
- if(seen.has(entry.eventId))continue;
128
- if(seen.size>=MAX_TRACE_EVENT_IDS)throw fail('TRACE_EVENT_CAPACITY');
129
- seen.add(entry.eventId);matched++;
130
- writerEpochs.add(entry.writerEpoch);
131
- events.push(publicEvent(entry));
132
- if(events.length>filter.maxEvents)events.shift();
133
- }
134
- }finally{stream.destroy()}
135
- }
136
- if(corrupt)errors.push('TRACE_MALFORMED_LINES');
137
- return {events,matched,legacyUncorrelated:legacy>0,gapped:corrupt>0,
138
- // A restart is not proof of loss, but evidence continuity across epochs
139
- // cannot be asserted by a log reader alone, even with later ACKs.
140
- writerRestartUnverified:writerEpochs.size>1,
141
- errors,truncated:matched>filter.maxEvents};
142
- }
143
- async function diagnose(opts){
144
- const result=await query(opts);
145
- const pending=new Map(),gaps=[...result.errors],unmatchedApiTerminals=[];
146
- let lastConfirmed=null,unknown=false;
147
- for(const e of result.events){
148
- if(e.status==='CONFIRMED')lastConfirmed={
149
- eventId:e.eventId,event:e.event,time:e.time,component:e.component
150
- };
151
- if(e.status==='UNKNOWN'||e.status==='BLOCKED')unknown=true;
152
- // V2 API BEGIN and terminal always share one spanId, even when
153
- // several sibling APIs share the same traceId. V1 used traceId.
154
- const apiCall=e.event==='context.api'||e.event==='typed.api.call';
155
- const id=apiCall?(e.schemaVersion===1?e.traceId:e.spanId):
156
- e.actionId||e.requestId;
157
- if(!id)continue;
158
- if(e.status==='BEGIN'){
159
- if(pending.has(id)&&apiCall)gaps.push('DUPLICATE_API_BEGIN');
160
- pending.set(id,{event:e.event,apiCall,apiName:e.apiName||
161
- e.api?.name||null,spanId:e.spanId,beginTime:e.time});
162
- }else if(['CONFIRMED','FAILED','UNKNOWN','BLOCKED'].includes(e.status)){
163
- if(apiCall&&!pending.has(id)&&!result.truncated)
164
- unmatchedApiTerminals.push({event:e.event,spanId:e.spanId});
165
- pending.delete(id);
166
- }
167
- }
168
- const incompleteApiSpans=[...pending.values()].filter(x=>x.apiCall)
169
- .slice(0,30);
170
- if(incompleteApiSpans.length)gaps.push('MISSING_API_TERMINAL');
171
- if(unmatchedApiTerminals.length)gaps.push('ORPHAN_API_TERMINAL');
172
- if(result.truncated)gaps.push('TRACE_WINDOW_TRUNCATED');
173
- if(result.writerRestartUnverified)gaps.push('TRACE_WRITER_RESTART_UNVERIFIED');
174
- if(result.legacyUncorrelated)gaps.push('LEGACY_EVENTS_UNCORRELATED');
175
- if(pending.size)gaps.push('MISSING_ACTION_RECEIPT');
176
- if(!result.events.length)gaps.push('NO_MATCHING_EVENTS');
177
- return {traceId:opts.traceId??null,projectRef:opts.projectRef,
178
- inspected:result.events.length,totalMatched:result.matched,lastConfirmed,
179
- incompleteApiSpans,unmatchedApiTerminals:unmatchedApiTerminals.slice(0,30),
180
- lastEvent:result.events.at(-1)??null,unknown,gaps:[...new Set(gaps)],
181
- confidence:gaps.length?'INCOMPLETE':'TRACE_ONLY',
182
- retryDisposition:unknown||pending.size||gaps.length?
183
- 'VERIFY_AUTHORITATIVE_RECEIPT_FIRST':'NO_AUTOMATIC_RETRY',
184
- timeline:result.events};
185
- }
186
- // Operational API usage is a sanitized system-local observation view.
187
- // It cannot read business projects, arguments, results or raw chat data.
188
- async function apiUsage({windowMinutes=60,limit=100}={}){
189
- if(!allowedProjects.includes('api_system'))
190
- throw fail('TRACE_PROJECT_ACCESS_DENIED');
191
- if(!Number.isSafeInteger(windowMinutes)||windowMinutes<1||windowMinutes>1440
192
- ||!Number.isSafeInteger(limit)||limit<1||limit>200)
193
- throw fail('TRACE_INVALID_LIMIT');
194
- const now=Date.now(),since=now-windowMinutes*60000;
195
- const sinceIso=new Date(since).toISOString();
196
- const calls=new Map(),seenEvents=new Set();
197
- const files=scopedFiles();
198
- let malformed=0;
199
- for(const item of files){
200
- const stream=openVerifiedStream(item);
201
- try{
202
- for await(const line of boundedLines(stream)){
203
- if(line===null){malformed++;continue}
204
- if(!line.trim())continue
205
- // The Writer's canonical v2 JSONL places ISO time first. Skip
206
- // expired history before JSON.parse/event validation; this is a
207
- // per-record filter, NOT an early file stop, so out-of-order
208
- // timestamps and multiple retained segments stay observable.
209
- // Noncanonical/malformed rows still use the normal read path.
210
- if(line.startsWith('{"time":"')){
211
- const stamp=line.slice(9,33);
212
- if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(stamp)
213
- &&line[33]==='"'&&stamp<sinceIso)continue;
214
- }
215
- let v;try{v=JSON.parse(line)}catch{malformed++;continue}
216
- // New event families provide their own safe usage projection.
217
- // A Provider never acquires access to a Project by being registered.
218
- if(!allowedProjects.includes(v?.projectRef))continue;
219
- const rule=eventRule(v);
220
- if(typeof rule?.usageName!=='function')continue;
221
- if(!['BEGIN','CONFIRMED','FAILED'].includes(v.status))continue;
222
- if(!validStored(v)){malformed++;continue}
223
- const time=Date.parse(v.time);
224
- if(!Number.isFinite(time)||time<since||time>now+60000)continue;
225
- // Deduplicate only events inside the requested usage window.
226
- // Old history cannot consume the memory budget of this query.
227
- if(seenEvents.has(v.eventId))continue;
228
- if(seenEvents.size>=MAX_TRACE_EVENT_IDS)
229
- throw fail('TRACE_EVENT_CAPACITY');
230
- seenEvents.add(v.eventId);
231
- let name;
232
- try{
233
- const view={...v};
234
- if(object(view.api))view.api=Object.freeze({...view.api});
235
- name=rule.usageName(Object.freeze(view));
236
- }catch{malformed++;continue}
237
- if(typeof name!=='string'||
238
- !/^[a-zA-Z][a-zA-Z0-9_.:-]{1,126}$/.test(name)||
239
- // New typed families cannot impersonate an existing MCP, Context,
240
- // Extension, Trace or Tunnel API in a usage report.
241
- !['context.api','typed.api.call'].includes(rule.id)
242
- &&!name.startsWith(rule.id+'.')){
243
- malformed++;continue
244
- }
245
- // V2 root and child API calls both use their own stable spanId.
246
- // Grouping V2 roots by shared traceId can silently hide an orphan
247
- // BEGIN when another sibling succeeds. V1 used traceId.
248
- const callKey=v.schemaVersion===1?v.traceId:v.spanId;
249
- const key=v.projectRef+':'+v.event+':'+callKey;
250
- const call=calls.get(key)||{api:name,begin:false,end:null,durationMs:null};
251
- if(call.api!==name){malformed++;continue}
252
- if(v.status==='BEGIN')call.begin=true;
253
- if(v.status==='CONFIRMED'||v.status==='FAILED'){
254
- if(call.end&&call.end!==v.status)call.end='UNKNOWN';
255
- else if(!call.end)call.end=v.status;
256
- if(Number.isSafeInteger(v.durationMs))
257
- call.durationMs=v.durationMs;
258
- }
259
- calls.set(key,call);
260
- }
261
- }finally{stream.destroy()}
262
- }
263
- // Count calls by their BEGIN inside the time window, never by the
264
- // number of log records. An unmatched completion is not a new API call.
265
- const counts=new Map();
266
- let orphanCompletions=0;
267
- for(const call of calls.values()){
268
- if(!call.begin){if(call.end)orphanCompletions++;continue}
269
- const entry=counts.get(call.api)||{api:call.api,calls:0,
270
- success:0,failures:0,incomplete:0,totalDurationMs:0,durationSamples:0,
271
- maxDurationMs:0};
272
- entry.calls++;
273
- if(call.end==='CONFIRMED')entry.success++;
274
- else if(call.end==='FAILED')entry.failures++;
275
- else entry.incomplete++;
276
- if(call.end&&!['UNKNOWN'].includes(call.end)
277
- &&Number.isSafeInteger(call.durationMs)){
278
- entry.totalDurationMs+=call.durationMs;
279
- entry.durationSamples++;
280
- entry.maxDurationMs=Math.max(entry.maxDurationMs,call.durationMs);
281
- }
282
- counts.set(call.api,entry);
283
- }
284
- const all=[...counts.values()].map(({totalDurationMs,durationSamples,...entry})=>({
285
- ...entry,avgDurationMs:durationSamples
286
- ?Number((totalDurationMs/durationSamples).toFixed(2)):null,
287
- maxDurationMs:durationSamples?entry.maxDurationMs:null
288
- }));
289
- all.sort((a,b)=>b.calls-a.calls||a.api.localeCompare(b.api));
290
- const api=all.slice(0,limit).map(entry=>({
291
- ...entry,callsPerMinute:Number((entry.calls/windowMinutes).toFixed(3))
292
- }));
293
- return {scope:'api_system',windowMinutes,
294
- calls:all.reduce((n,x)=>n+x.calls,0),
295
- success:all.reduce((n,x)=>n+x.success,0),
296
- failures:all.reduce((n,x)=>n+x.failures,0),
297
- incomplete:all.reduce((n,x)=>n+x.incomplete,0),
298
- orphanCompletions,api,malformed,limited:all.length>limit,
299
- source:files.length?'TRACE_ONLY':'TRACE_LOG_MISSING'};
300
- }
301
- return {query,diagnose,apiUsage,health:()=>{
302
- const st=secureFile(filePath);
303
- return {status:st?'READABLE':'TRACE_LOG_MISSING',
304
- bytes:st?.size??0,projectScopes:allowedProjects.length};
305
- }};
306
- }
307
- return createTraceReader(options);
308
- }
@@ -1,140 +0,0 @@
1
- import {randomUUID} from 'node:crypto';
2
- import {constants as FS,closeSync,fstatSync,fsyncSync,lstatSync,openSync,readSync,writeSync,renameSync,unlinkSync} from 'node:fs';
3
-
4
- const sameFile=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size
5
- &&a.mtimeMs===b.mtimeMs;
6
- const writeAll=(fd,buffer)=>{
7
- let offset=0;
8
- while(offset<buffer.length){
9
- const count=writeSync(fd,buffer,offset,buffer.length-offset);
10
- if(count<=0)throw Object.assign(Error('TRACE_RETENTION_WRITE_INCOMPLETE'),
11
- {code:'TRACE_RETENTION_WRITE_INCOMPLETE'});
12
- offset+=count;
13
- }
14
- };
15
- function pruneFile(filePath,cutoff,secureFile){
16
- const before=secureFile(filePath);
17
- if(!before)return {droppedRecords:0,droppedBytes:0,pruned:false};
18
- const input=openSync(filePath,FS.O_RDONLY|FS.O_NOFOLLOW);
19
- let output,temp;
20
- try{
21
- const opened=fstatSync(input);
22
- if(!opened.isFile()||(opened.mode&0o077)||
23
- process.getuid&&opened.uid!==process.getuid()||!sameFile(before,opened))
24
- throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
25
- {code:'TRACE_RETENTION_SOURCE_CHANGED'});
26
- const chunk=Buffer.allocUnsafe(64*1024),newline=Buffer.from([10]);
27
- let position=0,pending=Buffer.alloc(0),longLine=false,processedBytes=0;
28
- let droppedRecords=0,droppedBytes=0,keptRecords=0;
29
- // Do not copy an entire retained log every day if nothing has expired.
30
- // The first expired record triggers an exact, bounded prefix copy; all
31
- // earlier bytes remain untouched until then.
32
- const beginRewrite=()=>{
33
- if(output!==undefined)return;
34
- temp=filePath+'.retention-'+randomUUID();
35
- output=openSync(temp,FS.O_WRONLY|FS.O_CREAT|FS.O_EXCL|FS.O_NOFOLLOW,0o600);
36
- const copy=Buffer.allocUnsafe(64*1024);
37
- for(let offset=0;offset<processedBytes;){
38
- const n=readSync(input,copy,0,Math.min(copy.length,processedBytes-offset),offset);
39
- if(!n)throw Object.assign(Error('TRACE_RETENTION_READ_INCOMPLETE'),
40
- {code:'TRACE_RETENTION_READ_INCOMPLETE'});
41
- writeAll(output,copy.subarray(0,n));
42
- offset+=n;
43
- }
44
- };
45
- const keepLine=(line,terminated=true)=>{
46
- let expired=false;
47
- if(line.length<=8192){
48
- try{
49
- const value=JSON.parse(line.toString('utf8'));
50
- const timestamp=Date.parse(value?.time);
51
- expired=Number.isFinite(timestamp)&&timestamp<cutoff;
52
- }catch{}
53
- }
54
- if(expired){
55
- beginRewrite();droppedRecords++;droppedBytes+=line.length+(terminated?1:0);
56
- }else{
57
- // An unterminated, possibly torn final record is historical evidence.
58
- // Retention must never invent an absent final LF.
59
- if(output!==undefined){
60
- writeAll(output,line);
61
- if(terminated)writeAll(output,newline);
62
- }
63
- keptRecords++;
64
- }
65
- processedBytes+=line.length+(terminated?1:0);
66
- };
67
- while(position<before.size){
68
- const count=readSync(input,chunk,0,Math.min(chunk.length,before.size-position),position);
69
- if(!count)throw Object.assign(Error('TRACE_RETENTION_READ_INCOMPLETE'),
70
- {code:'TRACE_RETENTION_READ_INCOMPLETE'});
71
- position+=count;
72
- let start=0;
73
- while(start<count){
74
- const end=chunk.indexOf(10,start);
75
- if(longLine){
76
- const next=end<0?count:end+1;
77
- if(output!==undefined)writeAll(output,chunk.subarray(start,next));
78
- processedBytes+=next-start;
79
- if(end<0){start=count;continue;}
80
- longLine=false;start=next;continue;
81
- }
82
- if(end<0){
83
- const part=chunk.subarray(start,count);
84
- if(pending.length+part.length>8192){
85
- if(output!==undefined){writeAll(output,pending);writeAll(output,part);}
86
- processedBytes+=pending.length+part.length;
87
- pending=Buffer.alloc(0);longLine=true;keptRecords++;
88
- }else pending=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
89
- start=count;continue;
90
- }
91
- const part=chunk.subarray(start,end);
92
- const line=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
93
- if(line.length>8192){
94
- if(output!==undefined){writeAll(output,line);writeAll(output,newline);}
95
- processedBytes+=line.length+1;keptRecords++;
96
- }else keepLine(line);
97
- pending=Buffer.alloc(0);start=end+1;
98
- }
99
- }
100
- // longLine already copied its exact bytes. Its final LF, when present,
101
- // was copied in the read loop; do not append another one at EOF.
102
- if(!longLine&&pending.length)keepLine(pending,false);
103
- const after=fstatSync(input),current=lstatSync(filePath);
104
- if(!sameFile(before,after)||!sameFile(before,current))
105
- throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
106
- {code:'TRACE_RETENTION_SOURCE_CHANGED'});
107
- if(!droppedRecords)return {droppedRecords,droppedBytes,pruned:false};
108
- fsyncSync(output);closeSync(output);output=undefined;
109
- closeSync(input);
110
- if(!keptRecords){unlinkSync(filePath);unlinkSync(temp);temp=null;}
111
- else{renameSync(temp,filePath);temp=null;}
112
- return {droppedRecords,droppedBytes,pruned:true};
113
- }finally{
114
- try{closeSync(input)}catch{}
115
- if(output!==undefined)try{closeSync(output)}catch{}
116
- if(temp)try{unlinkSync(temp)}catch{}
117
- }
118
- }
119
- export function createTraceRetention({filePath,maxSegments,retentionDays,secureFile}){
120
- const state={days:retentionDays,droppedRecords:0,droppedBytes:0,
121
- prunedFiles:0,lastRunAt:null,error:null};
122
- const prune=()=>{
123
- const cutoff=Date.now()-retentionDays*24*60*60*1000;
124
- const paths=[...Array.from({length:maxSegments},(_,i)=>filePath+'.'+(i+1)),filePath];
125
- state.error=null;
126
- for(const path of paths){
127
- try{
128
- const result=pruneFile(path,cutoff,secureFile);
129
- state.droppedRecords+=result.droppedRecords;
130
- state.droppedBytes+=result.droppedBytes;
131
- if(result.pruned)state.prunedFiles++;
132
- }catch(error){state.error=error.code||'TRACE_RETENTION_FAILED';}
133
- }
134
- state.lastRunAt=new Date().toISOString();
135
- };
136
- prune();
137
- const timer=setInterval(prune,24*60*60*1000);
138
- timer.unref?.();
139
- return {health:()=>({...state})};
140
- }