@tomflow/chatloop-tools 0.9.21 → 0.9.23

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 (90) hide show
  1. package/README.md +3 -1
  2. package/node_modules/@tomflow/chatloop-context/package.json +3 -3
  3. package/node_modules/@tomflow/chatloop-extension/README.md +94 -0
  4. package/node_modules/@tomflow/chatloop-extension/actions.generated.mjs +11 -0
  5. package/node_modules/@tomflow/chatloop-extension/bin/cli.mjs +141 -0
  6. package/node_modules/@tomflow/chatloop-extension/bin/native-host.mjs +109 -0
  7. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_dom.mjs +1 -0
  8. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_screenshot.mjs +1 -0
  9. package/node_modules/@tomflow/chatloop-extension/capabilities/chat_text.mjs +1 -0
  10. package/node_modules/@tomflow/chatloop-extension/capabilities/clean.mjs +1 -0
  11. package/node_modules/@tomflow/chatloop-extension/capabilities/continue.mjs +1 -0
  12. package/node_modules/@tomflow/chatloop-extension/capabilities/handoff.mjs +1 -0
  13. package/node_modules/@tomflow/chatloop-extension/capabilities/reload.mjs +1 -0
  14. package/node_modules/@tomflow/chatloop-extension/capabilities/start.mjs +1 -0
  15. package/node_modules/@tomflow/chatloop-extension/capabilities/status.mjs +1 -0
  16. package/node_modules/@tomflow/chatloop-extension/extension/actions/clean.js +120 -0
  17. package/node_modules/@tomflow/chatloop-extension/extension/actions/common.js +180 -0
  18. package/node_modules/@tomflow/chatloop-extension/extension/actions/continue.js +322 -0
  19. package/node_modules/@tomflow/chatloop-extension/extension/actions/dom.js +2 -0
  20. package/node_modules/@tomflow/chatloop-extension/extension/actions/handoff.js +378 -0
  21. package/node_modules/@tomflow/chatloop-extension/extension/actions/index.js +2 -0
  22. package/node_modules/@tomflow/chatloop-extension/extension/actions/model-intent.js +54 -0
  23. package/node_modules/@tomflow/chatloop-extension/extension/actions/read-mode.js +9 -0
  24. package/node_modules/@tomflow/chatloop-extension/extension/actions/reload.js +20 -0
  25. package/node_modules/@tomflow/chatloop-extension/extension/actions/screenshot.js +69 -0
  26. package/node_modules/@tomflow/chatloop-extension/extension/actions/start.js +287 -0
  27. package/node_modules/@tomflow/chatloop-extension/extension/actions/status.js +23 -0
  28. package/node_modules/@tomflow/chatloop-extension/extension/actions/text.js +2 -0
  29. package/node_modules/@tomflow/chatloop-extension/extension/background.js +16 -0
  30. package/node_modules/@tomflow/chatloop-extension/extension/clean.html +5 -0
  31. package/node_modules/@tomflow/chatloop-extension/extension/content.js +40 -0
  32. package/node_modules/@tomflow/chatloop-extension/extension/continue.html +9 -0
  33. package/node_modules/@tomflow/chatloop-extension/extension/dom.html +17 -0
  34. package/node_modules/@tomflow/chatloop-extension/extension/handoff.html +9 -0
  35. package/node_modules/@tomflow/chatloop-extension/extension/loop/action-catalog.generated.js +2 -0
  36. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-aspect.generated.js +275 -0
  37. package/node_modules/@tomflow/chatloop-extension/extension/loop/api-observation-queue.generated.js +76 -0
  38. package/node_modules/@tomflow/chatloop-extension/extension/loop/core.js +107 -0
  39. package/node_modules/@tomflow/chatloop-extension/extension/loop/index.js +36 -0
  40. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-approval.js +227 -0
  41. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-inspect.js +144 -0
  42. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-poll.js +171 -0
  43. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer-recovery.js +109 -0
  44. package/node_modules/@tomflow/chatloop-extension/extension/loop/observer.js +154 -0
  45. package/node_modules/@tomflow/chatloop-extension/extension/loop/resources.js +254 -0
  46. package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +42 -0
  47. package/node_modules/@tomflow/chatloop-extension/extension/popup.html +25 -0
  48. package/node_modules/@tomflow/chatloop-extension/extension/popup.js +93 -0
  49. package/node_modules/@tomflow/chatloop-extension/extension/reload.html +17 -0
  50. package/node_modules/@tomflow/chatloop-extension/extension/screenshot.html +17 -0
  51. package/node_modules/@tomflow/chatloop-extension/extension/start.html +6 -0
  52. package/node_modules/@tomflow/chatloop-extension/extension/status.html +6 -0
  53. package/node_modules/@tomflow/chatloop-extension/extension/text.html +17 -0
  54. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-result.js +136 -0
  55. package/node_modules/@tomflow/chatloop-extension/extension/worker/action-take.js +220 -0
  56. package/node_modules/@tomflow/chatloop-extension/extension/worker/admission.js +122 -0
  57. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-prepare.js +155 -0
  58. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-recovery.js +185 -0
  59. package/node_modules/@tomflow/chatloop-extension/extension/worker/adopt-result.js +120 -0
  60. package/node_modules/@tomflow/chatloop-extension/extension/worker/bootstrap.js +172 -0
  61. package/node_modules/@tomflow/chatloop-extension/extension/worker/manual.js +165 -0
  62. package/node_modules/@tomflow/chatloop-extension/extension/worker/readiness.js +244 -0
  63. package/node_modules/@tomflow/chatloop-extension/extension/worker/router.js +181 -0
  64. package/node_modules/@tomflow/chatloop-extension/extension/worker/scheduler.js +147 -0
  65. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-failure.js +197 -0
  66. package/node_modules/@tomflow/chatloop-extension/extension/worker/turn-finished.js +200 -0
  67. package/node_modules/@tomflow/chatloop-extension/index.mjs +71 -0
  68. package/node_modules/@tomflow/chatloop-extension/lib/action-routing.mjs +18 -0
  69. package/node_modules/@tomflow/chatloop-extension/lib/api-observation-queue.mjs +74 -0
  70. package/node_modules/@tomflow/chatloop-extension/lib/bridge.mjs +208 -0
  71. package/node_modules/@tomflow/chatloop-extension/lib/browser-launch.mjs +40 -0
  72. package/node_modules/@tomflow/chatloop-extension/lib/context-binding.mjs +45 -0
  73. package/node_modules/@tomflow/chatloop-extension/lib/context-ipc.mjs +111 -0
  74. package/node_modules/@tomflow/chatloop-extension/lib/owner-evidence.mjs +67 -0
  75. package/node_modules/@tomflow/chatloop-extension/lib/session-file.mjs +120 -0
  76. package/node_modules/@tomflow/chatloop-extension/package.json +38 -0
  77. package/node_modules/@tomflow/chatloop-extension/scripts/build-actions.mjs +133 -0
  78. package/node_modules/@tomflow/chatloop-trace/README.md +10 -3
  79. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +4 -2
  80. package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +109 -0
  81. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +12 -5
  82. package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
  83. package/node_modules/ps-list/index.d.ts +76 -0
  84. package/node_modules/ps-list/index.js +366 -0
  85. package/node_modules/ps-list/license +9 -0
  86. package/node_modules/ps-list/package.json +44 -0
  87. package/node_modules/ps-list/readme.md +56 -0
  88. package/node_modules/ps-list/vendor/fastlist-0.3.0-x64.exe +0 -0
  89. package/node_modules/ps-list/vendor/fastlist-0.3.0-x86.exe +0 -0
  90. package/package.json +9 -5
@@ -0,0 +1,133 @@
1
+ // Extension action definitions are assembled at build time, never discovered
2
+ // by a privileged running Chrome Worker or Native Host.
3
+ import {readFileSync,readdirSync,writeFileSync,unlinkSync,existsSync} from 'node:fs';
4
+ import {dirname,join,resolve} from 'node:path';
5
+ import {fileURLToPath,pathToFileURL} from 'node:url';
6
+ import {createHash} from 'node:crypto';
7
+ const root=dirname(dirname(fileURLToPath(import.meta.url)));
8
+ const fail=code=>Object.assign(Error(code),{code});
9
+ const originals=['chat_text','chat_dom','chat_screenshot','reload',
10
+ 'continue','handoff','clean','status','start'];
11
+ const privilegedKinds=Object.freeze({chat_text:'eye-read',chat_dom:'eye-read',
12
+ chat_screenshot:'eye-screenshot',reload:'eye-reload',
13
+ continue:'owner-intent',handoff:'owner-intent',clean:'owner-clean',
14
+ status:'owner-status',start:'owner-start'});
15
+ // Existing timeout and receipt projection are part of the public action
16
+ // behavior; a descriptor edit must not silently change side-effect handling.
17
+ const builtinBehavior=Object.freeze({
18
+ chat_text:[27000,true],chat_dom:[27000,true],
19
+ chat_screenshot:[27000,false],reload:[27000,false],
20
+ continue:[27000,true],handoff:[27000,true],clean:[27000,true],
21
+ status:[27000,true],start:[310000,true]
22
+ });
23
+ const builtinRoute=Object.freeze({
24
+ chat_text:['text.html','chat text'],chat_dom:['dom.html','chat dom'],
25
+ chat_screenshot:['screenshot.html','chat screenshot'],
26
+ reload:['reload.html','reload'],continue:['continue.html','continue'],
27
+ handoff:['handoff.html','handoff'],clean:['clean.html','clean'],
28
+ status:['status.html','status'],start:['start.html','start']
29
+ });
30
+ const generatedMarker='<!-- GENERATED BY build-actions.mjs -->';
31
+ export async function compileActions(source=join(root,'capabilities'),
32
+ extension=join(root,'extension')){
33
+ const files=readdirSync(source).filter(f=>f.endsWith('.mjs')).sort();
34
+ const ids=new Set(),pages=new Set(),clis=new Set(),actions=[];
35
+ if(!files.length)throw fail('EXTENSION_ACTIONS_EMPTY');
36
+ for(const file of files){
37
+ if(!/^[a-z][a-z0-9_]*\.mjs$/.test(file))
38
+ throw fail('EXTENSION_CAPABILITY_FILENAME_INVALID');
39
+ const path=join(source,file);
40
+ const hash=createHash('sha256').update(readFileSync(path)).digest('hex');
41
+ const {capability:c}=await import(pathToFileURL(path).href+'?sha256='+hash);
42
+ if(!c||c.id!==file.slice(0,-4)||
43
+ !/^[a-z][a-z0-9_]*$/.test(c.id)||
44
+ !/^[a-z][a-z0-9-]*\.html$/.test(c.page)||
45
+ !Array.isArray(c.cli)||!c.cli.length||
46
+ c.cli.some(t=>typeof t!=='string'||!/^[a-z][a-z0-9-]*$/.test(t))||
47
+ !Number.isSafeInteger(c.waitMs)||c.waitMs<1||c.waitMs>310000||
48
+ typeof c.textResult!=='boolean'||typeof c.description!=='string'||
49
+ !c.description.trim()||ids.has(c.id)||pages.has(c.page)||
50
+ clis.has(c.cli.join(' ')))
51
+ throw fail('EXTENSION_CAPABILITY_INVALID');
52
+ ids.add(c.id);pages.add(c.page);clis.add(c.cli.join(' '));
53
+ const newAction=!originals.includes(c.id);
54
+ if(!newAction && privilegedKinds[c.id]!==c.kind)
55
+ throw fail('EXTENSION_ACTION_AUTHORITY_CHANGED');
56
+ if(!newAction && (c.page!==builtinRoute[c.id][0]||
57
+ c.cli.join(' ')!==builtinRoute[c.id][1]))
58
+ throw fail('EXTENSION_BUILTIN_ROUTE_CHANGED');
59
+ if(!newAction && (c.waitMs!==builtinBehavior[c.id][0]||
60
+ c.textResult!==builtinBehavior[c.id][1]))
61
+ throw fail('EXTENSION_BUILTIN_BEHAVIOR_CHANGED');
62
+ if(newAction && !c.textResult)
63
+ throw fail('EXTENSION_READ_RESULT_REQUIRED');
64
+ if(c.kind==='eye-read'&&(!c.id.startsWith('chat_')||
65
+ !['text','dom'].includes(c.readMode)))
66
+ throw fail('EXTENSION_EYE_READ_MODE_INVALID');
67
+ if(newAction && c.kind!=='eye-read')
68
+ throw fail('EXTENSION_PRIVILEGED_ACTION_REVIEW_REQUIRED');
69
+ if((c.id==='chat_text'&&c.readMode!=='text')||
70
+ (c.id==='chat_dom'&&c.readMode!=='dom'))
71
+ throw fail('EXTENSION_BUILTIN_EYE_MODE_CHANGED');
72
+ const page=join(extension,c.page);
73
+ const generated=existsSync(page)&&
74
+ readFileSync(page,'utf8').startsWith(generatedMarker);
75
+ if(!existsSync(page) && !newAction)
76
+ throw fail('EXTENSION_ACTION_PAGE_MISSING');
77
+ if(existsSync(page)&&!generated){
78
+ const expected='actions/'+(c.id.startsWith('chat_')?c.id.slice(5):c.id)+'.js';
79
+ if(!readFileSync(page,'utf8').includes(expected))
80
+ throw fail('EXTENSION_ACTION_EXECUTOR_MISMATCH');
81
+ }
82
+ actions.push({...c,file,generated:newAction});
83
+ }
84
+ actions.sort((a,b)=>(
85
+ (originals.indexOf(a.id)<0?99:originals.indexOf(a.id))-
86
+ (originals.indexOf(b.id)<0?99:originals.indexOf(b.id))
87
+ ||a.id.localeCompare(b.id)));
88
+ const imports=actions.map((a,i)=>
89
+ "import {capability as a"+i+"} from './capabilities/"+a.file+"';").join('\n');
90
+ const node='// GENERATED by scripts/build-actions.mjs — do not edit.\n'+
91
+ imports+'\nexport const actionCapabilities=Object.freeze(['+
92
+ actions.map((_,i)=>'a'+i).join(',')+']);\n';
93
+ const eye=Object.fromEntries(actions.filter(a=>a.kind.startsWith('eye-'))
94
+ .map(a=>[a.id,{page:a.page,kind:a.kind,readMode:a.readMode??null}]));
95
+ const browser='// GENERATED by scripts/build-actions.mjs — do not edit.\n'+
96
+ 'globalThis.ChatLoopEyeCatalogV1=Object.freeze('+JSON.stringify(eye)+');\n';
97
+ const aliases={};
98
+ for(const a of actions.filter(a=>a.generated)){
99
+ aliases[a.page]=generatedMarker+'\n<!doctype html><html><head><meta charset="utf-8">'+
100
+ '<title>Chat Loop read action</title></head><body>'+
101
+ '<p id="status"></p><p id="details"></p>'+
102
+ '<script src="actions/common.js"></script>'+
103
+ '<script src="actions/read-mode.js" data-action="'+a.id+
104
+ '" data-read-mode="'+a.readMode+'"></script></body></html>\n';
105
+ }
106
+ return {node,browser,aliases};
107
+ }
108
+ async function main(){
109
+ const ext=join(root,'extension'),expected=await compileActions();
110
+ const manifest=JSON.parse(readFileSync(join(ext,'manifest.json'),'utf8'));
111
+ const pkg=JSON.parse(readFileSync(join(root,'package.json'),'utf8'));
112
+ if(manifest.version!==pkg.version||manifest.manifest_version!==3)
113
+ throw fail('EXTENSION_PACKAGE_VERSION_MISMATCH');
114
+ const targets=[[join(root,'actions.generated.mjs'),expected.node],
115
+ [join(ext,'loop','action-catalog.generated.js'),expected.browser],
116
+ ...Object.entries(expected.aliases).map(([page,html])=>[join(ext,page),html])];
117
+ const orphan=readdirSync(ext).filter(f=>f.endsWith('.html')&&
118
+ !Object.hasOwn(expected.aliases,f)&&
119
+ readFileSync(join(ext,f),'utf8').startsWith(generatedMarker));
120
+ if(process.argv.includes('--check')){
121
+ if(orphan.length||targets.some(([file,value])=>!existsSync(file)||
122
+ readFileSync(file,'utf8')!==value))
123
+ throw fail('EXTENSION_ACTIONS_STALE');
124
+ if(process.env.npm_lifecycle_event!=='prepack')
125
+ console.log('EXTENSION_ACTIONS_CURRENT');
126
+ }else{
127
+ for(const page of orphan)unlinkSync(join(ext,page));
128
+ for(const [file,value] of targets)writeFileSync(file,value);
129
+ console.log('EXTENSION_ACTIONS_BUILT');
130
+ }
131
+ }
132
+ if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))
133
+ await main();
@@ -13,8 +13,13 @@ The root exposes two data APIs, a shared AOP factory and one opt-in, non-authori
13
13
  to the existing Supervisor. The writer's own `record/recordControl`
14
14
  telemetry is filtered at that boundary to prevent feedback loops. A
15
15
  standalone SDK stays installable and never creates another logging service.
16
- - `createTraceWriter({filePath})`: the Supervisor invokes
17
- `record(event)`, `recordControl(event,detail)` and `health()`.
16
+ - `createTraceWriter({filePath,retentionDays=30})`: the Supervisor invokes
17
+ `record(event)`, `recordControl(event,detail)` and `health()`. The single
18
+ Writer prunes only parseable records older than the configured retention
19
+ window at startup and daily across its active file and bounded rotation
20
+ segments. Unknown/malformed-age lines are preserved; source identity and
21
+ permissions are rechecked before atomic replacement. Retention results are
22
+ visible in `health().retention`.
18
23
  - `createTraceReader({filePath,allowedProjects})`: the Gateway invokes
19
24
  `diagnose({projectRef,traceId|sessionRef,maxEvents})`, `apiUsage({windowMinutes,limit})`
20
25
  or `health()`. `apiUsage` requires a Reader explicitly scoped to
@@ -86,7 +91,9 @@ nested result objects can enter v2 records. Existing legacy evidence is
86
91
  read-only, never migrated into a new current receipt or permission.
87
92
 
88
93
  The SDK verifies file owner, permissions, symlink safety and bounds event
89
- and query sizes. Diagnostics expose truncation, corrupted lines, writer
94
+ and query sizes. Scoped readers stream logs up to 2 GiB without loading the
95
+ full JSONL file into memory; the default 30-day Writer retention keeps normal
96
+ operational history within that read bound. Diagnostics expose truncation, corrupted lines, writer
90
97
  restarts, legacy records and pending receipts as **uncertainty**. They never
91
98
  grant approval, Context write rights, Owner transfer or automatic retry.
92
99
  A missing or interrupted Writer must be checked against the authoritative
@@ -2,6 +2,8 @@
2
2
  import {constants as FS,createReadStream,closeSync,fstatSync,openSync} from 'node:fs';
3
3
  import {createInterface} from 'node:readline';
4
4
 
5
+ const MAX_TRACE_READ_BYTES=2*1024*1024*1024;
6
+
5
7
  export function makeTraceReader(options,deps){
6
8
  const {TRACE_SCHEMA_VERSION,fail,validStoredFamily,object,isId,safeScope,
7
9
  safeRef,natural,keys,secureFile,eventRule,EVENT,CODE,COMPONENTS,STATUSES}=deps;
@@ -60,7 +62,7 @@ export function makeTraceReader(options,deps){
60
62
  filePath].map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
61
63
  if(!files.length)return {events:[],matched:0,legacyUncorrelated:true,gapped:true,
62
64
  errors:['TRACE_LOG_MISSING'],truncated:false};
63
- if(files.reduce((sum,x)=>sum+x.stat.size,0)>64*1024*1024)
65
+ if(files.reduce((sum,x)=>sum+x.stat.size,0)>MAX_TRACE_READ_BYTES)
64
66
  throw fail('TRACE_FILE_TOO_LARGE');
65
67
  const seen=new Set(),events=[],errors=[],writerEpochs=new Set();
66
68
  let matched=0,corrupt=0,legacy=0;
@@ -157,7 +159,7 @@ export function makeTraceReader(options,deps){
157
159
  const files=[...Array.from({length:maxSegments},(_,i)=>
158
160
  filePath+'.'+(maxSegments-i)),filePath]
159
161
  .map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
160
- if(files.reduce((n,x)=>n+x.stat.size,0)>64*1024*1024)
162
+ if(files.reduce((n,x)=>n+x.stat.size,0)>MAX_TRACE_READ_BYTES)
161
163
  throw fail('TRACE_FILE_TOO_LARGE');
162
164
  let malformed=0;
163
165
  for(const item of files){
@@ -0,0 +1,109 @@
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)offset+=writeSync(fd,buffer,offset,buffer.length-offset);
9
+ };
10
+ function pruneFile(filePath,cutoff,secureFile){
11
+ const before=secureFile(filePath);
12
+ if(!before)return {droppedRecords:0,droppedBytes:0,pruned:false};
13
+ const input=openSync(filePath,FS.O_RDONLY|FS.O_NOFOLLOW);
14
+ let output,temp;
15
+ try{
16
+ const opened=fstatSync(input);
17
+ if(!opened.isFile()||(opened.mode&0o077)||
18
+ process.getuid&&opened.uid!==process.getuid()||!sameFile(before,opened))
19
+ throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
20
+ {code:'TRACE_RETENTION_SOURCE_CHANGED'});
21
+ temp=filePath+'.retention-'+randomUUID();
22
+ output=openSync(temp,FS.O_WRONLY|FS.O_CREAT|FS.O_EXCL|FS.O_NOFOLLOW,0o600);
23
+ const chunk=Buffer.allocUnsafe(64*1024),newline=Buffer.from([10]);
24
+ let position=0,pending=Buffer.alloc(0),longLine=false;
25
+ let droppedRecords=0,droppedBytes=0,keptRecords=0;
26
+ const keepLine=(line,terminated=true)=>{
27
+ let expired=false;
28
+ if(line.length<=8192){
29
+ try{
30
+ const value=JSON.parse(line.toString('utf8'));
31
+ const timestamp=Date.parse(value?.time);
32
+ expired=Number.isFinite(timestamp)&&timestamp<cutoff;
33
+ }catch{}
34
+ }
35
+ if(expired){droppedRecords++;droppedBytes+=line.length+(terminated?1:0);}
36
+ else{writeAll(output,line);writeAll(output,newline);keptRecords++;}
37
+ };
38
+ while(position<before.size){
39
+ const count=readSync(input,chunk,0,Math.min(chunk.length,before.size-position),position);
40
+ if(!count)throw Object.assign(Error('TRACE_RETENTION_READ_INCOMPLETE'),
41
+ {code:'TRACE_RETENTION_READ_INCOMPLETE'});
42
+ position+=count;
43
+ let start=0;
44
+ while(start<count){
45
+ const end=chunk.indexOf(10,start);
46
+ if(longLine){
47
+ const next=end<0?count:end+1;
48
+ writeAll(output,chunk.subarray(start,next));
49
+ if(end<0){start=count;continue;}
50
+ longLine=false;start=next;continue;
51
+ }
52
+ if(end<0){
53
+ const part=chunk.subarray(start,count);
54
+ if(pending.length+part.length>8192){
55
+ writeAll(output,pending);writeAll(output,part);
56
+ pending=Buffer.alloc(0);longLine=true;keptRecords++;
57
+ }else pending=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
58
+ start=count;continue;
59
+ }
60
+ const part=chunk.subarray(start,end);
61
+ const line=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
62
+ if(line.length>8192){writeAll(output,line);writeAll(output,newline);keptRecords++;}
63
+ else keepLine(line);
64
+ pending=Buffer.alloc(0);start=end+1;
65
+ }
66
+ }
67
+ if(longLine)writeAll(output,newline);
68
+ else if(pending.length)keepLine(pending,false);
69
+ const after=fstatSync(input),current=lstatSync(filePath);
70
+ if(!sameFile(before,after)||!sameFile(before,current))
71
+ throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
72
+ {code:'TRACE_RETENTION_SOURCE_CHANGED'});
73
+ if(!droppedRecords){
74
+ closeSync(output);output=undefined;unlinkSync(temp);temp=null;
75
+ return {droppedRecords,droppedBytes,pruned:false};
76
+ }
77
+ fsyncSync(output);closeSync(output);output=undefined;
78
+ closeSync(input);
79
+ if(!keptRecords){unlinkSync(filePath);unlinkSync(temp);temp=null;}
80
+ else{renameSync(temp,filePath);temp=null;}
81
+ return {droppedRecords,droppedBytes,pruned:true};
82
+ }finally{
83
+ try{closeSync(input)}catch{}
84
+ if(output!==undefined)try{closeSync(output)}catch{}
85
+ if(temp)try{unlinkSync(temp)}catch{}
86
+ }
87
+ }
88
+ export function createTraceRetention({filePath,maxSegments,retentionDays,secureFile}){
89
+ const state={days:retentionDays,droppedRecords:0,droppedBytes:0,
90
+ prunedFiles:0,lastRunAt:null,error:null};
91
+ const prune=()=>{
92
+ const cutoff=Date.now()-retentionDays*24*60*60*1000;
93
+ const paths=[...Array.from({length:maxSegments},(_,i)=>filePath+'.'+(i+1)),filePath];
94
+ state.error=null;
95
+ for(const path of paths){
96
+ try{
97
+ const result=pruneFile(path,cutoff,secureFile);
98
+ state.droppedRecords+=result.droppedRecords;
99
+ state.droppedBytes+=result.droppedBytes;
100
+ if(result.pruned)state.prunedFiles++;
101
+ }catch(error){state.error=error.code||'TRACE_RETENTION_FAILED';}
102
+ }
103
+ state.lastRunAt=new Date().toISOString();
104
+ };
105
+ prune();
106
+ const timer=setInterval(prune,24*60*60*1000);
107
+ timer.unref?.();
108
+ return {health:()=>({...state})};
109
+ }
@@ -2,6 +2,7 @@ import {makeTraceReader} from './trace-reader.mjs';
2
2
  import {randomUUID} from 'node:crypto';
3
3
  import {constants as FS,closeSync,fstatSync,lstatSync,openSync,writeSync,renameSync,unlinkSync} from 'node:fs';
4
4
  import {dirname,isAbsolute} from 'node:path';
5
+ import {createTraceRetention} from './trace-retention.mjs';
5
6
 
6
7
  export const TRACE_SCHEMA_VERSION=2;
7
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;
@@ -138,13 +139,16 @@ function secureFile(filePath){
138
139
  return st;
139
140
  }
140
141
  export function createTraceWriter({
141
- filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5
142
+ filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5,
143
+ retentionDays=30
142
144
  }){
143
145
  if(typeof enableRotation!=='boolean'||!Number.isSafeInteger(rotateBytes)||
144
146
  rotateBytes<512||rotateBytes>10*1024*1024||
145
- !Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
147
+ !Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5||
148
+ !Number.isSafeInteger(retentionDays)||retentionDays<1||retentionDays>3650)
146
149
  throw fail('TRACE_ROTATION_INVALID');
147
150
  const epoch=randomUUID();let seq=0,failures=0,lastError=null,rotations=0;
151
+ const retention=createTraceRetention({filePath,maxSegments,retentionDays,secureFile});
148
152
  const rotateIfNeeded=lineBytes=>{
149
153
  // Legacy data is never moved until an operator explicitly enables
150
154
  // rotation after preserving its historical evidence.
@@ -190,9 +194,12 @@ export function createTraceWriter({
190
194
  {errorCode:detail.errorCode}:{})
191
195
  });
192
196
  };
193
- const health=()=>({status:lastError?'TRACE_DEGRADED':'OK',
194
- errorCode:lastError,failures,writerEpoch:epoch,writerSeq:seq,
195
- rotationEnabled:enableRotation,rotations});
197
+ const health=()=>{
198
+ const retained=retention.health();
199
+ return {status:lastError||retained.error?'TRACE_DEGRADED':'OK',
200
+ errorCode:lastError||retained.error,failures,writerEpoch:epoch,writerSeq:seq,
201
+ rotationEnabled:enableRotation,rotations,retention:retained};
202
+ };
196
203
  return {record,recordControl,health};
197
204
  }
198
205
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-trace",
3
- "version": "0.4.4",
3
+ "version": "0.4.5",
4
4
  "description": "Trace SDK and scoped read-only diagnostics for Chat Loop",
5
5
  "type": "module",
6
6
  "engines": {
@@ -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[]>;