@tomflow/chatloop-tools 0.9.64 → 0.9.70

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 (175) hide show
  1. package/node_modules/@tomflow/chatloop-context/README.md +296 -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 +290 -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 +261 -0
  14. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  15. package/node_modules/@tomflow/chatloop-context/index.mjs +238 -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 +77 -0
  18. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +2036 -0
  19. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +69 -0
  20. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +338 -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 +286 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +117 -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 +134 -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 +180 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/run-cancel.mjs +68 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/run-recovery.mjs +112 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +367 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +398 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +264 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +118 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +316 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +117 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +142 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  45. package/node_modules/@tomflow/chatloop-context/package.json +38 -0
  46. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  47. package/node_modules/@tomflow/chatloop-extension/README.md +190 -0
  48. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +13 -0
  49. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +168 -0
  50. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +246 -0
  51. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  52. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  53. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  54. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  55. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  56. package/node_modules/@tomflow/chatloop-extension/capabilities/entry_test.mjs +1 -0
  57. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  58. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  59. package/node_modules/@tomflow/chatloop-extension/capabilities/session.mjs +1 -0
  60. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  61. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +123 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +183 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +390 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/actions/entry_test.js +241 -0
  67. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff-scoped.js +143 -0
  68. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +399 -0
  69. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  70. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +60 -0
  71. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  72. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  73. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +77 -0
  74. package/node_modules/@tomflow/chatloop-extension/extension/actions/session.js +95 -0
  75. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +329 -0
  76. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +38 -0
  77. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  78. package/node_modules/@tomflow/chatloop-extension/extension/background.js +33 -0
  79. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  80. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  81. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  82. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  83. package/node_modules/@tomflow/chatloop-extension/extension/entry_test.html +6 -0
  84. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  85. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  86. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  87. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +84 -0
  88. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  89. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  90. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +299 -0
  91. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  92. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +172 -0
  93. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  94. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +211 -0
  95. package/node_modules/@tomflow/chatloop-extension/extension/loop/resource-maintenance.js +159 -0
  96. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +399 -0
  97. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +43 -0
  98. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  99. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +99 -0
  100. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  101. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  102. package/node_modules/@tomflow/chatloop-extension/extension/session.html +7 -0
  103. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  104. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  105. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  106. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  107. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +218 -0
  108. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +127 -0
  109. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +296 -0
  110. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +186 -0
  111. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +126 -0
  112. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +287 -0
  113. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +163 -0
  114. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +345 -0
  115. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +209 -0
  116. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +385 -0
  117. package/node_modules/@tomflow/chatloop-extension/extension/worker/session-control.js +75 -0
  118. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-action-v2.js +278 -0
  119. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-recovery-v2.js +52 -0
  120. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-cancel-v2.js +93 -0
  121. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-continue-recovery-v2.js +78 -0
  122. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-recovery-v2.js +148 -0
  123. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-handoff-v2.js +325 -0
  124. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-hold-recovery-v2.js +109 -0
  125. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-dispatch-v2.js +220 -0
  126. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-intent-v2.js +106 -0
  127. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-owner-resolver.js +110 -0
  128. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-recover-v2.js +209 -0
  129. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-routes-v2.js +357 -0
  130. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-run-store.js +400 -0
  131. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-scheduler.js +78 -0
  132. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-start-v2.js +361 -0
  133. package/node_modules/@tomflow/chatloop-extension/extension/worker/task-terminal-v2.js +235 -0
  134. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  135. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +205 -0
  136. package/node_modules/@tomflow/chatloop-extension/index.mjs +78 -0
  137. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +19 -0
  138. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +82 -0
  139. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +378 -0
  140. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +89 -0
  141. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  142. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +122 -0
  143. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +75 -0
  144. package/node_modules/@tomflow/chatloop-extension/lib/owner-kernel-lock.mjs +106 -0
  145. package/node_modules/@tomflow/chatloop-extension/lib/owner-ledger.mjs +316 -0
  146. package/node_modules/@tomflow/chatloop-extension/lib/owner-locked-write.mjs +30 -0
  147. package/node_modules/@tomflow/chatloop-extension/lib/scoped-cancel-v2.mjs +190 -0
  148. package/node_modules/@tomflow/chatloop-extension/lib/scoped-continue-v2.mjs +214 -0
  149. package/node_modules/@tomflow/chatloop-extension/lib/scoped-handoff-v2.mjs +338 -0
  150. package/node_modules/@tomflow/chatloop-extension/lib/scoped-native-control.mjs +398 -0
  151. package/node_modules/@tomflow/chatloop-extension/lib/scoped-recovery-v2.mjs +234 -0
  152. package/node_modules/@tomflow/chatloop-extension/lib/scoped-retire-v2.mjs +70 -0
  153. package/node_modules/@tomflow/chatloop-extension/lib/scoped-terminal-v2.mjs +143 -0
  154. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +228 -0
  155. package/node_modules/@tomflow/chatloop-extension/package.json +36 -0
  156. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +138 -0
  157. package/node_modules/@tomflow/chatloop-trace/README.md +118 -0
  158. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  159. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  160. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  161. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  162. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  163. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +308 -0
  164. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +140 -0
  165. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +236 -0
  166. package/node_modules/@tomflow/chatloop-trace/package.json +28 -0
  167. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  168. package/node_modules/ps-list/index.d.ts +76 -0
  169. package/node_modules/ps-list/index.js +366 -0
  170. package/node_modules/ps-list/license +9 -0
  171. package/node_modules/ps-list/package.json +44 -0
  172. package/node_modules/ps-list/readme.md +56 -0
  173. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  174. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  175. package/package.json +12 -4
@@ -0,0 +1,236 @@
1
+ import {makeTraceReader} from './trace-reader.mjs';
2
+ import {randomUUID} from 'node:crypto';
3
+ import {constants as FS,closeSync,fstatSync,lstatSync,openSync,readSync,writeSync,renameSync,unlinkSync} from 'node:fs';
4
+ import {dirname,isAbsolute} from 'node:path';
5
+ import {createTraceRetention} from './trace-retention.mjs';
6
+
7
+ export const TRACE_SCHEMA_VERSION=2;
8
+ 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;
9
+ const SCOPE=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
10
+ const REF=/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
11
+ const EVENT=/^[a-z][a-z0-9_.-]{1,95}$/;
12
+ const CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
13
+ const COMPONENTS=new Set(['supervisor','gateway','context','extension','native']);
14
+ const STATUSES=new Set(['BEGIN','CONFIRMED','FAILED','UNKNOWN','BLOCKED']);
15
+ const ALLOWED=new Set(['eventId','traceId','spanId','parentSpanId','timestamp','component',
16
+ 'event','projectRef','taskRef','sessionRef','generation','requestId','actionId',
17
+ 'status','errorCode','durationMs','evidenceRef','api','apiName']);
18
+ const fail=code=>Object.assign(new Error(code),{code});
19
+ let eventRules=null;
20
+ // Private composition port. The npm root supplies only the generated,
21
+ // source-reviewed event contracts; callers never register runtime plugins.
22
+ export function configureTraceEvents(definitions){
23
+ if(eventRules)throw fail('TRACE_EVENTS_ALREADY_CONFIGURED');
24
+ if(!Array.isArray(definitions)||!definitions.length)
25
+ throw fail('TRACE_EVENTS_INVALID');
26
+ const rules=new Map();
27
+ for(const rule of definitions){
28
+ if(!rule||typeof rule.id!=='string'||rules.has(rule.id)||
29
+ rule.schemaVersion!==TRACE_SCHEMA_VERSION||
30
+ typeof rule.validate!=='function'||typeof rule.errorCode!=='string')
31
+ throw fail('TRACE_EVENTS_INVALID');
32
+ rules.set(rule.id,rule);
33
+ }
34
+ if(!rules.has('context.api'))throw fail('TRACE_REQUIRED_EVENT_SCHEMA_MISSING');
35
+ eventRules=rules;
36
+ }
37
+ function eventRule(v){
38
+ if(!eventRules)throw fail('TRACE_EVENTS_NOT_COMPOSED');
39
+ return eventRules.get(v.event);
40
+ }
41
+ function ruleAccepts(rule,v){
42
+ try{
43
+ // A Provider validates a read-only projection. It must never rewrite the
44
+ // caller's scope, status, identity, or the on-disk event being diagnosed.
45
+ const view={...v};
46
+ if(object(view.api))view.api=Object.freeze({...view.api});
47
+ return rule.validate(Object.freeze(view))===true;
48
+ }catch{return false}
49
+ }
50
+ function validStoredFamily(v){
51
+ // A pre-existing API observation without the original caller's IDs cannot
52
+ // be promoted into trusted correlated evidence by the Reader.
53
+ if(!validApiCorrelation(v))return false;
54
+ // The reserved api field belongs solely to the Context API event, no
55
+ // matter how permissive an additional Provider's validator may become.
56
+ if(v.schemaVersion===TRACE_SCHEMA_VERSION&&v.event!=='context.api'
57
+ &&Object.hasOwn(v,'api'))return false;
58
+ const rule=eventRule(v);
59
+ return rule ? v.schemaVersion===rule.schemaVersion&&ruleAccepts(rule,v)
60
+ :!v.event.startsWith('typed.')&&v.api==null;
61
+ }
62
+ const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
63
+ const isId=v=>typeof v==='string'&&UUID.test(v);
64
+ const validApiCorrelation=v=>!['typed.api.call','context.api'].includes(v?.event)
65
+ ||isId(v.traceId)&&isId(v.spanId)&&
66
+ (v.parentSpanId==null||isId(v.parentSpanId)&&v.parentSpanId!==v.spanId);
67
+ const safeScope=v=>typeof v==='string'&&SCOPE.test(v);
68
+ const safeRef=v=>typeof v==='string'&&REF.test(v);
69
+ const natural=v=>Number.isSafeInteger(v)&&v>=0;
70
+ const keys=(v,allowed)=>{
71
+ if(!object(v))throw fail('TRACE_INVALID_OBJECT');
72
+ for(const k of Object.keys(v))if(!allowed.has(k))throw fail('TRACE_INVALID_FIELD');
73
+ };
74
+ const bytes=v=>Buffer.byteLength(JSON.stringify(v),'utf8');
75
+ const nullable=(v,test,code)=>{
76
+ if(v!==undefined&&v!==null&&!test(v))throw fail(code);
77
+ return v??null;
78
+ };
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
+ retentionDays=30
143
+ }){
144
+ if(typeof enableRotation!=='boolean'||!Number.isSafeInteger(rotateBytes)||
145
+ rotateBytes<512||rotateBytes>10*1024*1024||
146
+ !Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5||
147
+ !Number.isSafeInteger(retentionDays)||retentionDays<1||retentionDays>3650)
148
+ throw fail('TRACE_ROTATION_INVALID');
149
+ const epoch=randomUUID();let seq=0,failures=0,lastError=null,rotations=0;
150
+ const retention=createTraceRetention({filePath,maxSegments,retentionDays,secureFile});
151
+ const terminated=(fd,size)=>{
152
+ if(size===0)return true;
153
+ const tail=Buffer.allocUnsafe(1);
154
+ return readSync(fd,tail,0,1,size-1)===1&&tail[0]===10;
155
+ };
156
+ const rotateIfNeeded=lineBytes=>{
157
+ // Legacy data is never moved until an operator explicitly enables
158
+ // rotation after preserving its historical evidence.
159
+ if(!enableRotation)return;
160
+ const old=secureFile(filePath);
161
+ if(!old||old.size+lineBytes<=rotateBytes)return;
162
+ // Rotation must not hide a torn active tail in a historical segment
163
+ // while making the next Writer append appear fully confirmed.
164
+ const source=openSync(filePath,FS.O_RDONLY|FS.O_NOFOLLOW);
165
+ try{
166
+ const actual=fstatSync(source);
167
+ if(actual.ino!==old.ino||actual.dev!==old.dev||actual.size!==old.size
168
+ ||!terminated(source,actual.size))throw fail('TRACE_UNTERMINATED_TAIL');
169
+ }finally{closeSync(source)}
170
+ const oldest=filePath+'.'+maxSegments;
171
+ if(secureFile(oldest))unlinkSync(oldest);
172
+ for(let i=maxSegments-1;i>=1;i--){
173
+ const from=filePath+'.'+i;
174
+ if(secureFile(from))renameSync(from,filePath+'.'+(i+1));
175
+ }
176
+ renameSync(filePath,filePath+'.1');
177
+ rotations++;
178
+ };
179
+ function append(entry){
180
+ let fd;
181
+ try{
182
+ rotateIfNeeded(bytes(entry)+1);
183
+ secureFile(filePath);
184
+ fd=openSync(filePath,FS.O_RDWR|FS.O_APPEND|FS.O_CREAT|FS.O_NOFOLLOW,0o600);
185
+ const st=fstatSync(fd);
186
+ if(!st.isFile()||(st.mode&0o077)||
187
+ process.getuid&&st.uid!==process.getuid())throw fail('TRACE_FILE_UNTRUSTED');
188
+ // Fail closed on a partially persisted prior record. A new append
189
+ // must never concatenate onto unverified historical JSONL evidence.
190
+ if(!terminated(fd,st.size))throw fail('TRACE_UNTERMINATED_TAIL');
191
+ const line=Buffer.from(JSON.stringify(entry)+'\n');
192
+ let written=0;
193
+ while(written<line.length){
194
+ const count=writeSync(fd,line,written,line.length-written);
195
+ if(count<=0)throw fail('TRACE_WRITE_INCOMPLETE');
196
+ written+=count;
197
+ }
198
+ seq++;lastError=null;
199
+ return {eventId:entry.eventId,traceId:entry.traceId,
200
+ writerEpoch:epoch,writerSeq:seq};
201
+ }catch(e){failures++;lastError=e.code||'TRACE_WRITE_FAILED';throw e}
202
+ finally{if(fd!==undefined)closeSync(fd)}
203
+ }
204
+ const record=v=>append(normalize(v,epoch,seq+1));
205
+ const recordControl=(event,detail={})=>{
206
+ // All sources now emit the same typed v2 event. Historical tool summaries,
207
+ // traceStatus aliases and arbitrary result columns are never written.
208
+ const status=detail?.status==='FAILED'||/(?:error|fatal)/.test(event)?'FAILED':
209
+ detail?.status==='UNKNOWN'||
210
+ ['PARTIAL','DEGRADED','UNCONFIRMED','TIMEOUT'].includes(detail?.status)?'UNKNOWN':
211
+ detail?.status==='BLOCKED'||event.includes('blocked')?'BLOCKED':'CONFIRMED';
212
+ return record({event,component:'supervisor',status,
213
+ ...(safeRef(detail?.requestId)?{requestId:detail.requestId}:{}),
214
+ ...(typeof detail?.errorCode==='string'&&CODE.test(detail.errorCode)?
215
+ {errorCode:detail.errorCode}:{})
216
+ });
217
+ };
218
+ const health=()=>{
219
+ const retained=retention.health();
220
+ // A successful later append cannot reconstruct a lost earlier event.
221
+ // Keep the writer degraded for this epoch until an independent audit.
222
+ const historyGap=failures>0?'TRACE_WRITE_HISTORY_GAP':null;
223
+ return {status:lastError||retained.error||historyGap?'TRACE_DEGRADED':'OK',
224
+ errorCode:lastError||retained.error||historyGap,failures,writerEpoch:epoch,writerSeq:seq,
225
+ rotationEnabled:enableRotation,rotations,retention:retained};
226
+ };
227
+ return {record,recordControl,health};
228
+ }
229
+
230
+ // Runtime event definitions remain bound to this exact module instance;
231
+ // dynamic import isolation in the Trace SDK must not be lost by refactoring.
232
+ export function createTraceReader(options){
233
+ return makeTraceReader(options,{TRACE_SCHEMA_VERSION,fail,validStoredFamily,
234
+ object,isId,safeScope,safeRef,natural,keys,secureFile,eventRule,
235
+ EVENT,CODE,COMPONENTS,STATUSES});
236
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "@tomflow/chatloop-trace",
3
+ "version": "0.4.6",
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
+ "prepack": "node ./scripts/build-events.mjs --check"
27
+ }
28
+ }
@@ -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[]>;