@tomflow/chatloop-tools 0.9.19 → 0.9.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -3
- package/index.mjs +49 -9
- package/lib/supervisor-observability.mjs +157 -0
- package/lib/supervisor-runtime.mjs +14 -111
- package/lib/trace-gateway.mjs +90 -11
- package/lib/trace-observation.mjs +17 -8
- package/node_modules/@tomflow/chatloop-context/README.md +240 -0
- package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
- package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
- package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
- package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
- package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
- package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
- package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
- package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
- package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
- package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
- package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
- package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
- package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
- package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
- package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
- package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
- package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
- package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
- package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
- package/node_modules/@tomflow/chatloop-context/package.json +40 -0
- package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
- package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
- package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
- package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
- package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
- package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
- package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
- package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
- package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
- package/package.json +5 -1
- package/providers/form.mjs +85 -206
- package/providers/trace.mjs +5 -2
- package/ui/form/review-app.js +59 -44
- package/ui/form/review.html +1 -1
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// This module declares ports; index.mjs is the only dependency assembler.
|
|
2
|
+
// No implementation module imports another implementation module.
|
|
3
|
+
let openContextProtocol, allowedProjects, resolveVerifiedProjectDatabase;
|
|
4
|
+
let connected=false;
|
|
5
|
+
export function configureTrustedRun(capabilities){
|
|
6
|
+
if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
|
|
7
|
+
for(const name of ['openContextProtocol', 'allowedProjects', 'resolveVerifiedProjectDatabase']){
|
|
8
|
+
if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
|
|
9
|
+
}
|
|
10
|
+
({openContextProtocol, allowedProjects, resolveVerifiedProjectDatabase}=capabilities);
|
|
11
|
+
connected=true;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// Trusted Native run domain facade: one validated operation, no raw SQLite
|
|
15
|
+
// handle, path resolver, credential generator or arbitrary Core method export.
|
|
16
|
+
// The caller must first verify the signed Supervisor IPC and Native projection.
|
|
17
|
+
// This package still enforces the Project grant, domain command list, and CAS.
|
|
18
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
19
|
+
const assert=(ok,code)=>{if(!ok)throw fail(code)};
|
|
20
|
+
const supported=new Set(['permit.consume','run.bind.initial','run.fence',
|
|
21
|
+
'run.bind.handoff','run.restore-same-owner','run.fence.terminal',
|
|
22
|
+
'run.credential.rotate','run.terminalStatus','run.reopenStatus','run.snapshot']);
|
|
23
|
+
|
|
24
|
+
export function executeTrustedRun(command,args,native){
|
|
25
|
+
assert(supported.has(command)&&args&&typeof args==='object'
|
|
26
|
+
&&!Array.isArray(args)&&native&&typeof native==='object',
|
|
27
|
+
'CONTEXT_COMMAND_INVALID');
|
|
28
|
+
assert(!['principal','role','internalAuthorized','ownerCommitted',
|
|
29
|
+
'nativeCommitted'].some(k=>Object.hasOwn(args,k)),
|
|
30
|
+
'CLIENT_AUTH_FIELD_FORBIDDEN');
|
|
31
|
+
assert(native.projectId===args.projectId && native.taskId===args.taskId
|
|
32
|
+
&& native.sessionId===args.sessionId
|
|
33
|
+
&& native.generation===args.generation
|
|
34
|
+
&& native.activeChatId===args.activeChatId
|
|
35
|
+
&& (native.activeChatId!==null || command==='permit.consume'&&args.kind==='START'),
|
|
36
|
+
'CONTEXT_NATIVE_BINDING_MISMATCH');
|
|
37
|
+
const allowed=allowedProjects();
|
|
38
|
+
assert(allowed.has(native.projectId),'PROJECT_ACCESS_DENIED');
|
|
39
|
+
if(command==='run.fence'){
|
|
40
|
+
assert(native.phase==='PENDING','NATIVE_PHASE_MISMATCH');
|
|
41
|
+
assert(args.targetGeneration===native.generation+1,'TARGET_GENERATION_MISMATCH');
|
|
42
|
+
}
|
|
43
|
+
if(['run.fence','run.fence.terminal','run.bind.initial','run.bind.handoff',
|
|
44
|
+
'run.credential.rotate'].includes(command))
|
|
45
|
+
assert(args.runRef===native.sessionId+':'+native.taskId+':'+native.generation,
|
|
46
|
+
'RUN_REF_MISMATCH');
|
|
47
|
+
if(command==='permit.consume')
|
|
48
|
+
assert(['RESERVED','PENDING'].includes(native.phase),'NATIVE_PHASE_MISMATCH');
|
|
49
|
+
if(['run.bind.initial','run.bind.handoff'].includes(command))
|
|
50
|
+
assert(native.phase==='WAITING_REPLY','NATIVE_PHASE_MISMATCH');
|
|
51
|
+
if(command==='run.credential.rotate')
|
|
52
|
+
assert(native.phase==='PENDING','NATIVE_PHASE_MISMATCH');
|
|
53
|
+
if(command==='run.restore-same-owner')
|
|
54
|
+
assert(native.phase==='RESERVED','NATIVE_PHASE_MISMATCH');
|
|
55
|
+
if(command==='run.fence.terminal'||command==='run.reopenStatus')
|
|
56
|
+
assert(native.phase==='DONE','NATIVE_PHASE_MISMATCH');
|
|
57
|
+
|
|
58
|
+
const file=resolveVerifiedProjectDatabase(args.projectId);
|
|
59
|
+
const db=openContextProtocol(file,{principalId:'native-controlled',
|
|
60
|
+
authorizeData:(_access,p)=>allowed.has(p),authorizeInternal:()=>true});
|
|
61
|
+
try{
|
|
62
|
+
if(!['run.terminalStatus','run.reopenStatus','run.snapshot'].includes(command)
|
|
63
|
+
&&!db.projectBusinessAuthority(args.projectId).writable)
|
|
64
|
+
throw fail('PROJECT_CUTOVER_NOT_VERIFIED');
|
|
65
|
+
switch(command){
|
|
66
|
+
case 'run.terminalStatus':return db.terminalStatus(args.projectId,args.taskId);
|
|
67
|
+
case 'run.reopenStatus':return db.reopenStatus(args.projectId,args.taskId);
|
|
68
|
+
case 'run.snapshot':return db.latestCheckpoint(args.projectId,args.taskId);
|
|
69
|
+
case 'permit.consume':return db.consumePermit(args);
|
|
70
|
+
case 'run.credential.rotate':return db.rotateCredential(args);
|
|
71
|
+
case 'run.bind.initial':return db.bindInitial({...args,ownerCommitted:true});
|
|
72
|
+
case 'run.fence':return db.fence(args);
|
|
73
|
+
case 'run.fence.terminal':return db.fenceTerminal(args);
|
|
74
|
+
case 'run.bind.handoff':
|
|
75
|
+
return db.bindHandoff({...args,ownerCommitted:true,nativeCommitted:true});
|
|
76
|
+
case 'run.restore-same-owner':
|
|
77
|
+
assert(args.sendState==='NOT_SENT'
|
|
78
|
+
&&typeof args.recoveryActionToken==='string',
|
|
79
|
+
'SEND_NOT_PROVEN_ABSENT');
|
|
80
|
+
return db.restoreSameOwner({...args,
|
|
81
|
+
sourceRunRef:native.sessionId+':'+native.taskId+':'+native.generation,
|
|
82
|
+
oldActionTokenRevoked:true,workerRestored:true,
|
|
83
|
+
nativeRestored:true,ownerStillSame:true});
|
|
84
|
+
}
|
|
85
|
+
}finally{db.close()}
|
|
86
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
// Operator-only Workspace ownership. Never imported by ordinary MCP.
|
|
2
|
+
import {createHash} from 'node:crypto';
|
|
3
|
+
import {readdirSync,lstatSync,realpathSync,existsSync,mkdirSync,rmdirSync} from 'node:fs';
|
|
4
|
+
import {isAbsolute,join,relative,sep} from 'node:path';
|
|
5
|
+
import {createInterface} from 'node:readline/promises';
|
|
6
|
+
// This module declares ports; index.mjs is the only dependency assembler.
|
|
7
|
+
// No implementation module imports another implementation module.
|
|
8
|
+
let openContextProtocol, contextRoot, dispatchContextCall, allowedProjects;
|
|
9
|
+
let connected=false;
|
|
10
|
+
export function configureWorkspaceOperator(capabilities){
|
|
11
|
+
if(connected)throw Error('CONTEXT_MODULE_ALREADY_COMPOSED');
|
|
12
|
+
for(const name of ['openContextProtocol', 'contextRoot', 'dispatchContextCall', 'allowedProjects']){
|
|
13
|
+
if(capabilities?.[name]===undefined)throw Error('CONTEXT_MODULE_PORT_MISSING:'+name);
|
|
14
|
+
}
|
|
15
|
+
({openContextProtocol, contextRoot, dispatchContextCall, allowedProjects}=capabilities);
|
|
16
|
+
connected=true;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const ID=/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/;
|
|
20
|
+
const fail=code=>Object.assign(new Error(code),{code});
|
|
21
|
+
const assert=(ok,code)=>{if(!ok)throw fail(code)};
|
|
22
|
+
const overlap=(a,b)=>a===b||[relative(a,b),relative(b,a)]
|
|
23
|
+
.some(r=>r!==''&&r!=='..'&&!r.startsWith('..'+sep)&&!isAbsolute(r));
|
|
24
|
+
const trustedDir=path=>{
|
|
25
|
+
const s=lstatSync(path);
|
|
26
|
+
assert(s.isDirectory()&&!s.isSymbolicLink()&&!(s.mode&0o077)
|
|
27
|
+
&&(!process.getuid||s.uid===process.getuid()),'CONTEXT_ROOT_UNTRUSTED');
|
|
28
|
+
};
|
|
29
|
+
export function canonicalWorkspaceRefs(paths,{allowEmpty=false}={}){
|
|
30
|
+
assert(Array.isArray(paths)&&paths.length<=16&&(allowEmpty||paths.length>0),
|
|
31
|
+
'WORKSPACE_BINDING_INVALID');
|
|
32
|
+
const refs=paths.map(path=>{
|
|
33
|
+
assert(typeof path==='string'&&path.length<=4096&&isAbsolute(path),
|
|
34
|
+
'WORKSPACE_INVALID');
|
|
35
|
+
let real,st;
|
|
36
|
+
try{st=lstatSync(path);real=realpathSync(path)}
|
|
37
|
+
catch{throw fail('WORKSPACE_UNVERIFIED')}
|
|
38
|
+
assert(st.isDirectory()&&!st.isSymbolicLink(),'WORKSPACE_SYMLINK_REJECTED');
|
|
39
|
+
return real;
|
|
40
|
+
});
|
|
41
|
+
for(let i=0;i<refs.length;i++)for(let j=0;j<i;j++)
|
|
42
|
+
assert(!overlap(refs[i],refs[j]),'WORKSPACE_SCOPE_OVERLAP');
|
|
43
|
+
return refs;
|
|
44
|
+
}
|
|
45
|
+
export function confirmationPhrase(action,projectId,revision,refs){
|
|
46
|
+
const hash=createHash('sha256').update(JSON.stringify(
|
|
47
|
+
{action,projectId,revision,refs})).digest('hex').slice(0,12);
|
|
48
|
+
return 'CONFIRM '+action+' '+projectId+' '+hash;
|
|
49
|
+
}
|
|
50
|
+
export async function confirmWorkspaceOperator(action,projectId,revision,refs){
|
|
51
|
+
if(!process.stdin.isTTY||!process.stderr.isTTY)throw fail('OPERATOR_TTY_REQUIRED');
|
|
52
|
+
const phrase=confirmationPhrase(action,projectId,revision,refs);
|
|
53
|
+
const rl=createInterface({input:process.stdin,output:process.stderr,terminal:true});
|
|
54
|
+
try{
|
|
55
|
+
process.stderr.write('Local operator approval only. Project: '+projectId+
|
|
56
|
+
'\nAction: '+action+'\nReviewed paths:\n'+
|
|
57
|
+
(refs.length?refs.map(x=>' '+x).join('\n'):' (clear all)')+'\n');
|
|
58
|
+
const answer=await rl.question('Type '+phrase+' to authorize: ');
|
|
59
|
+
assert(answer===phrase,'OPERATOR_CONFIRMATION_MISMATCH');
|
|
60
|
+
}finally{rl.close()}
|
|
61
|
+
}
|
|
62
|
+
export function withWorkspaceRegistryLock(root,fn){
|
|
63
|
+
trustedDir(root);
|
|
64
|
+
const lock=join(root,'.project-register.lock');
|
|
65
|
+
try{mkdirSync(lock,{mode:0o700})}catch{throw fail('PROJECT_REGISTRY_BUSY')}
|
|
66
|
+
// Async backups must retain the same global lock through atomic publication.
|
|
67
|
+
let deferred=false;
|
|
68
|
+
try{
|
|
69
|
+
const result=fn();
|
|
70
|
+
if(result&&typeof result.then==='function'){
|
|
71
|
+
deferred=true;
|
|
72
|
+
return result.finally(()=>rmdirSync(lock));
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
}finally{if(!deferred)rmdirSync(lock)}
|
|
76
|
+
}
|
|
77
|
+
// Scan all physical project directories, not just the current MCP grant.
|
|
78
|
+
// An ungranted Project can still own the same Workspace. Do not auto-pick.
|
|
79
|
+
export function assertWorkspaceUnclaimed(root,projectId,refs){
|
|
80
|
+
for(const dir of readdirSync(root,{withFileTypes:true})){
|
|
81
|
+
if(!ID.test(dir.name)||dir.name===projectId)continue;
|
|
82
|
+
assert(dir.isDirectory()&&!dir.isSymbolicLink(),'PROJECT_DIRECTORY_UNTRUSTED');
|
|
83
|
+
const file=join(root,dir.name,'context.sqlite');
|
|
84
|
+
assert(existsSync(file),'PROJECT_IDENTITY_UNVERIFIED');
|
|
85
|
+
const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
|
|
86
|
+
authorizeData:()=>true});
|
|
87
|
+
let list;
|
|
88
|
+
try{list=db.projectList()}finally{db.close()}
|
|
89
|
+
assert(list.length===1&&list[0].projectId===dir.name,'PROJECT_IDENTITY_MISMATCH');
|
|
90
|
+
for(const existing of list[0].sharedContext?.workspaceRefs??[]){
|
|
91
|
+
assert(typeof existing==='string'&&isAbsolute(existing),'WORKSPACE_BINDING_INVALID');
|
|
92
|
+
let canonical;
|
|
93
|
+
try{canonical=realpathSync(existing)}catch{canonical=existing}
|
|
94
|
+
for(const current of refs)
|
|
95
|
+
assert(!overlap(canonical,current),'WORKSPACE_OWNERSHIP_CONFLICT');
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
export async function rebindProjectWorkspaces({
|
|
100
|
+
projectId,expectedProjectRevision,expectedStoreEpoch,writeRequestId,workspaces
|
|
101
|
+
}){
|
|
102
|
+
assert(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE==='1','ADMIN_REQUIRED');
|
|
103
|
+
assert(ID.test(projectId||'')&&allowedProjects().has(projectId),'PROJECT_ACCESS_DENIED');
|
|
104
|
+
assert(Number.isSafeInteger(expectedProjectRevision)&&expectedProjectRevision>=1,
|
|
105
|
+
'PROJECT_REVISION_REQUIRED');
|
|
106
|
+
assert(typeof expectedStoreEpoch==='string'&&expectedStoreEpoch.length>=10,
|
|
107
|
+
'STORE_EPOCH_REQUIRED');
|
|
108
|
+
assert(typeof writeRequestId==='string'&&writeRequestId.length>=8&&
|
|
109
|
+
writeRequestId.length<=128,'REQUEST_ID_REQUIRED');
|
|
110
|
+
const refs=canonicalWorkspaceRefs(workspaces,{allowEmpty:true});
|
|
111
|
+
const root=contextRoot();
|
|
112
|
+
trustedDir(root);
|
|
113
|
+
// First pass has no write side effects. Confirmation is bound to exact refs.
|
|
114
|
+
const before=await dispatchContextCall('chat_loop_context_get',
|
|
115
|
+
{operation:'project.open',projectId});
|
|
116
|
+
assert(before.project.projectRevision===expectedProjectRevision,
|
|
117
|
+
'PROJECT_VERSION_CONFLICT');
|
|
118
|
+
assert(before.storeEpoch===expectedStoreEpoch,'STALE_EPOCH');
|
|
119
|
+
assert(!before.project.archived,'PROJECT_ARCHIVED');
|
|
120
|
+
assert(before.authority.writable===true,'PROJECT_CUTOVER_NOT_VERIFIED');
|
|
121
|
+
await confirmWorkspaceOperator('BIND',projectId,expectedProjectRevision,refs);
|
|
122
|
+
return withWorkspaceRegistryLock(root,()=>{
|
|
123
|
+
// Re-read under the *same* global lock as project register; Core CAS
|
|
124
|
+
// protects concurrent business writes that do not take this lock.
|
|
125
|
+
assertWorkspaceUnclaimed(root,projectId,refs);
|
|
126
|
+
const current=canonicalWorkspaceRefs(workspaces,{allowEmpty:true});
|
|
127
|
+
assert(JSON.stringify(current)===JSON.stringify(refs),'WORKSPACE_CHANGED');
|
|
128
|
+
const file=join(root,projectId,'context.sqlite');
|
|
129
|
+
const db=openContextProtocol(file,{principalId:'local-operator',
|
|
130
|
+
authorizeData:(_mode,p)=>p===projectId,
|
|
131
|
+
authorizeAdmin:(op,p)=>op==='project.bind'&&p===projectId});
|
|
132
|
+
try{
|
|
133
|
+
const ids=db.projectList();
|
|
134
|
+
assert(ids.length===1&&ids[0].projectId===projectId,
|
|
135
|
+
'PROJECT_IDENTITY_MISMATCH');
|
|
136
|
+
assert(db.projectBusinessAuthority(projectId).writable===true,
|
|
137
|
+
'PROJECT_CUTOVER_NOT_VERIFIED');
|
|
138
|
+
const receipt=db.projectPatch({projectId,expectedProjectRevision,
|
|
139
|
+
expectedStoreEpoch,writeRequestId,sharedContext:{workspaceRefs:refs}});
|
|
140
|
+
const after=db.projectGet(projectId);
|
|
141
|
+
assert(after.projectRevision===receipt.projectRevision&&
|
|
142
|
+
JSON.stringify(after.sharedContext.workspaceRefs)===JSON.stringify(refs),
|
|
143
|
+
'WORKSPACE_RECEIPT_UNVERIFIED');
|
|
144
|
+
return {...receipt,projectId,workspaceRefs:refs,storeEpoch:expectedStoreEpoch,
|
|
145
|
+
writeRequestId};
|
|
146
|
+
}finally{db.close()}
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Read-only recovery for an operator write whose CLI result was lost.
|
|
151
|
+
// Receipt uses the SAME local-operator principal, not the model MCP principal.
|
|
152
|
+
export async function readOperatorWorkspaceReceipt({projectId,storeEpoch,writeRequestId}){
|
|
153
|
+
assert(process.env.CHAT_LOOP_CONTEXT_ADMIN_ENABLE==='1','ADMIN_REQUIRED');
|
|
154
|
+
assert(ID.test(projectId||'')&&allowedProjects().has(projectId),'PROJECT_ACCESS_DENIED');
|
|
155
|
+
assert(typeof storeEpoch==='string'&&storeEpoch.length>=10,'STORE_EPOCH_REQUIRED');
|
|
156
|
+
assert(typeof writeRequestId==='string'&&writeRequestId.length>=8&&
|
|
157
|
+
writeRequestId.length<=128,'REQUEST_ID_REQUIRED');
|
|
158
|
+
const opened=await dispatchContextCall('chat_loop_context_get',
|
|
159
|
+
{operation:'project.open',projectId});
|
|
160
|
+
assert(opened.storeEpoch===storeEpoch,'STALE_EPOCH');
|
|
161
|
+
const file=join(contextRoot(),projectId,'context.sqlite');
|
|
162
|
+
const db=openContextProtocol(file,{readOnly:true,principalId:'local-operator',
|
|
163
|
+
authorizeData:(_mode,p)=>p===projectId});
|
|
164
|
+
try{
|
|
165
|
+
return {projectId,storeEpoch,writeRequestId,
|
|
166
|
+
receipt:db.requestStatus({projectId,storeEpoch,writeRequestId}),
|
|
167
|
+
project:db.projectGet(projectId)};
|
|
168
|
+
}finally{db.close()}
|
|
169
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tomflow/chatloop-context",
|
|
3
|
+
"version": "0.6.11",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"engines": {
|
|
10
|
+
"node": ">=24"
|
|
11
|
+
},
|
|
12
|
+
"bin": {
|
|
13
|
+
"chatloop-context": "./bin/cli.mjs"
|
|
14
|
+
},
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./index.mjs"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"index.mjs",
|
|
20
|
+
"capabilities.generated.mjs",
|
|
21
|
+
"capabilities/",
|
|
22
|
+
"lib/",
|
|
23
|
+
"bin/",
|
|
24
|
+
"scripts/",
|
|
25
|
+
"README.md",
|
|
26
|
+
"docs/"
|
|
27
|
+
],
|
|
28
|
+
"scripts": {
|
|
29
|
+
"test": "node --test ./test/*.test.mjs",
|
|
30
|
+
"build:capabilities": "node ./scripts/build-capabilities.mjs",
|
|
31
|
+
"build:capabilities:check": "node ./scripts/build-capabilities.mjs --check",
|
|
32
|
+
"prepack": "node ./scripts/build-capabilities.mjs --check",
|
|
33
|
+
"pretest": "node ./scripts/build-capabilities.mjs --check"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"ps-list": "9.0.0",
|
|
37
|
+
"@tomflow/chatloop-extension": "0.4.11",
|
|
38
|
+
"@tomflow/chatloop-trace": "0.4.4"
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// Deterministic, build-time Context capability composition.
|
|
2
|
+
// Source of truth: capabilities/<id>.mjs. Runtime never scans directories.
|
|
3
|
+
import {readdirSync,readFileSync,writeFileSync} 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
|
+
|
|
8
|
+
const ROOT=dirname(dirname(fileURLToPath(import.meta.url)));
|
|
9
|
+
const ID=/^[a-z][a-z0-9-]{0,63}$/;
|
|
10
|
+
const METHOD=/^[a-z][a-z0-9-]*\.[a-zA-Z0-9._-]+$/;
|
|
11
|
+
const ADAPTERS=new Set(['sdk.methods.list','sdk.methods.describe','project.resolve',
|
|
12
|
+
'project.list','project.open','task.open']);
|
|
13
|
+
const failure=code=>Object.assign(Error(code),{code});
|
|
14
|
+
const object=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
|
15
|
+
|
|
16
|
+
export async function compileCapabilities(sourceDir=join(ROOT,'capabilities')){
|
|
17
|
+
const files=readdirSync(sourceDir).filter(s=>s.endsWith('.mjs')).sort();
|
|
18
|
+
if(!files.length)throw failure('CAPABILITY_EMPTY');
|
|
19
|
+
const caps=[],seenIds=new Set(),seenMethods=new Set();
|
|
20
|
+
for(const name of files){
|
|
21
|
+
if(!/^[a-z][a-z0-9-]*\.mjs$/.test(name))throw failure('CAPABILITY_FILENAME_INVALID');
|
|
22
|
+
const path=resolve(sourceDir,name);
|
|
23
|
+
const fingerprint=createHash('sha256').update(readFileSync(path)).digest('hex');
|
|
24
|
+
const {capability:c}=await import(pathToFileURL(path).href+'?sha256='+fingerprint);
|
|
25
|
+
if(!object(c)||!ID.test(c.id)||name!==c.id+'.mjs'||seenIds.has(c.id)
|
|
26
|
+
||!Number.isSafeInteger(c.version)||c.version<1
|
|
27
|
+
||typeof c.purpose!=='string'||!c.purpose.length
|
|
28
|
+
||typeof c.startWith!=='string'||!Array.isArray(c.methods)||!c.methods.length)
|
|
29
|
+
throw failure('CAPABILITY_DECLARATION_INVALID');
|
|
30
|
+
seenIds.add(c.id);
|
|
31
|
+
for(const m of c.methods){
|
|
32
|
+
if(!object(m)||!METHOD.test(m.id)||m.group!==c.id
|
|
33
|
+
||!m.id.startsWith(c.id+'.')||seenMethods.has(m.id)
|
|
34
|
+
||(m.order!==undefined&&(!Number.isSafeInteger(m.order)||m.order<0))
|
|
35
|
+
||!['read','write'].includes(m.mode)||typeof m.description!=='string'
|
|
36
|
+
||!object(m.inputSchema)||m.inputSchema.type!=='object'
|
|
37
|
+
||m.inputSchema.additionalProperties!==false
|
|
38
|
+
||!Array.isArray(m.inputSchema.required)
|
|
39
|
+
||!m.inputSchema.required.includes('operation')
|
|
40
|
+
||!object(m.inputSchema.properties)
|
|
41
|
+
||m.inputSchema.properties.operation?.const!==m.id
|
|
42
|
+
||m.inputSchema.required.some(k=>!Object.hasOwn(m.inputSchema.properties,k))
|
|
43
|
+
||!object(m.route))throw failure('CAPABILITY_METHOD_INVALID');
|
|
44
|
+
seenMethods.add(m.id);
|
|
45
|
+
if(m.route.kind==='adapter'){
|
|
46
|
+
if(!ADAPTERS.has(m.id)||m.route.name!==m.id)
|
|
47
|
+
throw failure('CAPABILITY_ADAPTER_NOT_ALLOWED');
|
|
48
|
+
}else if(m.route.kind==='core'){
|
|
49
|
+
if(!/^[a-zA-Z][a-zA-Z0-9]*$/.test(m.route.method)
|
|
50
|
+
||!Array.isArray(m.route.params)
|
|
51
|
+
||m.route.params.some(p=>!(typeof p==='string'||
|
|
52
|
+
object(p)&&Object.keys(p).length===1&&object(p.$object))))
|
|
53
|
+
throw failure('CAPABILITY_CORE_ROUTE_INVALID');
|
|
54
|
+
}else if(m.route.kind==='module'){
|
|
55
|
+
// Unreviewed custom business writes must not bypass Core's CAS/receipt.
|
|
56
|
+
// A new writer must first acquire an explicitly reviewed receipt port.
|
|
57
|
+
if(m.mode!=='read'||!m.inputSchema.required.includes('projectId')
|
|
58
|
+
||typeof c.execute!=='function')
|
|
59
|
+
throw failure('CAPABILITY_CUSTOM_PERMISSION_INVALID');
|
|
60
|
+
}else throw failure('CAPABILITY_ROUTE_INVALID');
|
|
61
|
+
}
|
|
62
|
+
if(!c.methods.some(m=>m.id===c.startWith))
|
|
63
|
+
throw failure('CAPABILITY_START_METHOD_INVALID');
|
|
64
|
+
caps.push(c);
|
|
65
|
+
}
|
|
66
|
+
const flattened=caps.flatMap(c=>c.methods);
|
|
67
|
+
const explicitOrders=flattened.filter(m=>m.order!==undefined).map(m=>m.order);
|
|
68
|
+
if(new Set(explicitOrders).size!==explicitOrders.length)
|
|
69
|
+
throw failure('CAPABILITY_METHOD_ORDER_DUPLICATE');
|
|
70
|
+
// Existing APIs retain their published presentation order. New capability
|
|
71
|
+
// methods need no global position: the compiler deterministically appends
|
|
72
|
+
// them by ID, so adding a group never edits another group's declarations.
|
|
73
|
+
let nextOrder=Math.max(-1,...explicitOrders)+1;
|
|
74
|
+
const assigned=new Map(flattened.filter(m=>m.order===undefined)
|
|
75
|
+
.sort((a,b)=>a.id.localeCompare(b.id))
|
|
76
|
+
.map(m=>[m.id,nextOrder++]));
|
|
77
|
+
const methods=flattened.map(m=>{
|
|
78
|
+
const {id,group,mode,description,inputSchema,route,lifecycle}=m;
|
|
79
|
+
return {id,group,mode,description,inputSchema,route,
|
|
80
|
+
order:m.order??assigned.get(id),...(lifecycle?{lifecycle}:{})};
|
|
81
|
+
}).sort((a,b)=>a.order-b.order);
|
|
82
|
+
const groups=caps.map(c=>({
|
|
83
|
+
id:c.id,purpose:c.purpose,startWith:c.startWith,
|
|
84
|
+
order:Math.min(...methods.filter(m=>m.group===c.id).map(m=>m.order))
|
|
85
|
+
})).sort((a,b)=>a.order-b.order);
|
|
86
|
+
const json=JSON.stringify({groups,methods},null,2)+'\n';
|
|
87
|
+
const imports=files.map((file,i)=>
|
|
88
|
+
"import {capability as c"+i+"} from './capabilities/"+file+"';").join('\n');
|
|
89
|
+
const js='// GENERATED from capabilities/*.mjs. Do not edit.\n'+
|
|
90
|
+
imports+'\nexport const capabilities=Object.freeze(['+
|
|
91
|
+
files.map((_,i)=>'c'+i).join(',')+']);\n';
|
|
92
|
+
return {json,js,groups,methods};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function main(){
|
|
96
|
+
const {json,js,methods}=await compileCapabilities();
|
|
97
|
+
const targets=[
|
|
98
|
+
[join(ROOT,'lib/capability-catalog.generated.json'),json],
|
|
99
|
+
[join(ROOT,'capabilities.generated.mjs'),js]
|
|
100
|
+
];
|
|
101
|
+
if(process.argv.includes('--check')){
|
|
102
|
+
for(const [file,expected] of targets){
|
|
103
|
+
let actual;try{actual=readFileSync(file,'utf8')}catch{}
|
|
104
|
+
if(actual!==expected)throw failure('CAPABILITY_BUILD_STALE:'+file);
|
|
105
|
+
}
|
|
106
|
+
if(process.env.npm_lifecycle_event!=='prepack')
|
|
107
|
+
console.log('CAPABILITIES_CURRENT '+methods.length);
|
|
108
|
+
}else{
|
|
109
|
+
for(const [file,value] of targets)writeFileSync(file,value);
|
|
110
|
+
console.log('CAPABILITIES_BUILT '+methods.length);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url))
|
|
114
|
+
await main();
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# @tomflow/chatloop-trace
|
|
2
|
+
|
|
3
|
+
Trace is the **read-only evidence/observation domain**, not a business
|
|
4
|
+
authorization, receipt authority, browser driver or second job scheduler.
|
|
5
|
+
The existing Tools Supervisor remains the sole authoritative Trace JSONL
|
|
6
|
+
writer; Tools Trace Gateway provides scoped diagnosis only.
|
|
7
|
+
|
|
8
|
+
## Public npm SDK
|
|
9
|
+
|
|
10
|
+
The root exposes two data APIs, a shared AOP factory and one opt-in, non-authoritative observation port:
|
|
11
|
+
|
|
12
|
+
- `subscribeTraceApiLog(listener)`: Tools attaches a best-effort collector
|
|
13
|
+
to the existing Supervisor. The writer's own `record/recordControl`
|
|
14
|
+
telemetry is filtered at that boundary to prevent feedback loops. A
|
|
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()`.
|
|
18
|
+
- `createTraceReader({filePath,allowedProjects})`: the Gateway invokes
|
|
19
|
+
`diagnose({projectRef,traceId|sessionRef,maxEvents})`, `apiUsage({windowMinutes,limit})`
|
|
20
|
+
or `health()`. `apiUsage` requires a Reader explicitly scoped to
|
|
21
|
+
`api_system` and returns only grouped method names, counts, success/failure
|
|
22
|
+
totals and calls/minute; it never returns request content.
|
|
23
|
+
No raw `query`, no CLI, service, daemon, additional storage or Browser Owner.
|
|
24
|
+
|
|
25
|
+
The Trace SDK source version is specified by its package manifest. Existing Tools versions retain
|
|
26
|
+
their independently pinned Trace version until separately verified and
|
|
27
|
+
upgraded; tests here do not prove a deployed Supervisor changed.
|
|
28
|
+
|
|
29
|
+
## Event contracts and extension
|
|
30
|
+
|
|
31
|
+
`events/<event-id>.mjs` owns the schema-v2 domain-specific validator,
|
|
32
|
+
error code and human purpose for a typed event family. The single
|
|
33
|
+
`scripts/build-events.mjs` command composes these **at build time** into
|
|
34
|
+
`events.generated.mjs`; `index.mjs` injects the static catalog into
|
|
35
|
+
the private Writer/Reader implementation. No runtime scanning, external
|
|
36
|
+
registration, secondary hand-maintained API catalog or duplicated validation
|
|
37
|
+
between writing and reading.
|
|
38
|
+
|
|
39
|
+
New typed event families must use the `typed.*` namespace. Removing a
|
|
40
|
+
specialized module makes that typed event **unregistered**: the Writer rejects
|
|
41
|
+
it, and the Reader treats old/forged matching lines as untrusted. Historical
|
|
42
|
+
generic event names retain their established read/write behavior.
|
|
43
|
+
|
|
44
|
+
The canonical envelope also reserves the `api` field exclusively for
|
|
45
|
+
`context.api`. **No newly declared typed event can claim API metadata**, even
|
|
46
|
+
with a permissive validator. Each validator receives a read-only copy of the
|
|
47
|
+
event: it cannot rewrite an event's `projectRef`, status or identifiers during
|
|
48
|
+
writing or diagnosis. A family may declare a `usageName(event)` projection
|
|
49
|
+
to join scoped API usage aggregation without modifying Reader's event dispatch.
|
|
50
|
+
New typed families must namespace projected names under their own family ID;
|
|
51
|
+
this does not add Project permissions or authorize actions.
|
|
52
|
+
|
|
53
|
+
The built-in `context.api` event is protected: it requires
|
|
54
|
+
`component=context`, status `BEGIN/CONFIRMED/FAILED`, and only
|
|
55
|
+
`api:{name,surface,mode}` with validated values. Removing or weakening
|
|
56
|
+
this contract blocks the build. Generic events cannot add `api` or new
|
|
57
|
+
arbitrary payload fields. Additional event families can constrain the
|
|
58
|
+
**same reviewed v2 envelope** without modifying the Writer/Reader Core.
|
|
59
|
+
Adding new envelope fields or granting new write authority is a separate
|
|
60
|
+
schema/security change, not a plugin escape hatch.
|
|
61
|
+
|
|
62
|
+
To add a typed event contract:
|
|
63
|
+
|
|
64
|
+
1. Create `events/<id>.mjs` exporting
|
|
65
|
+
`capability={id,schemaVersion:2,errorCode,description,validate(v)}`
|
|
66
|
+
(and optional `usageName(v)` for safe usage aggregation).
|
|
67
|
+
2. Run `npm run build:events`; it regenerates the only static catalog.
|
|
68
|
+
3. Run `npm run build:events:check`, `npm test` and workspace `npm run check`.
|
|
69
|
+
|
|
70
|
+
`test/event-composition.test.mjs` verifies that a temporary additional
|
|
71
|
+
event contract is accepted by **both** the Writer and the Reader and can be
|
|
72
|
+
removed without modifying existing Core code. Malformed or unauthorized
|
|
73
|
+
event-family records are rejected in both directions.
|
|
74
|
+
|
|
75
|
+
## Immutable observability boundaries
|
|
76
|
+
|
|
77
|
+
All newly written records use schema v2 with a bounded, canonical JSONL
|
|
78
|
+
envelope: `time`, `eventId`, `traceId`, `spanId`, optional
|
|
79
|
+
`parentSpanId`, `writerEpoch`, `writerSeq`, `component`, `event`,
|
|
80
|
+
`status`, scoped `projectRef/taskRef/sessionRef`, `generation`,
|
|
81
|
+
`requestId/actionId/evidenceRef`, optional `api`, `durationMs`,
|
|
82
|
+
and `errorCode`.
|
|
83
|
+
|
|
84
|
+
No user content, cookies, credentials, raw tool arguments or arbitrary
|
|
85
|
+
nested result objects can enter v2 records. Existing legacy evidence is
|
|
86
|
+
read-only, never migrated into a new current receipt or permission.
|
|
87
|
+
|
|
88
|
+
The SDK verifies file owner, permissions, symlink safety and bounds event
|
|
89
|
+
and query sizes. Diagnostics expose truncation, corrupted lines, writer
|
|
90
|
+
restarts, legacy records and pending receipts as **uncertainty**. They never
|
|
91
|
+
grant approval, Context write rights, Owner transfer or automatic retry.
|
|
92
|
+
A missing or interrupted Writer must be checked against the authoritative
|
|
93
|
+
business receipt, not inferred from a Trace event.
|
|
94
|
+
|
|
95
|
+
The npm package includes only the SDK root, generated event catalog,
|
|
96
|
+
event definitions, private implementation and this README. It contains no
|
|
97
|
+
independent API documentation or unnecessary executable.
|
|
98
|
+
|
|
99
|
+
## Shared API observation factory
|
|
100
|
+
|
|
101
|
+
`createApiAspect(packageName, {sink})` is the **only public Node AOP implementation**, exported from `@tomflow/chatloop-trace`. Context, Tools, Extension Native/CLI and Darwin Tunnel packages import it through their pinned npm dependency rather than embedding duplicated source. Each consumer supplies only its typed, authorized transport/metadata adapter. Its `observe`, `methods`, `described`, `describedMethods`, `subscribe`, `health`, and `drain` facets preserve business results while reporting non-authoritative audit outcomes.
|
|
102
|
+
|
|
103
|
+
AOP `health().delivered` measures delivery attempts, **not Writer persistence**. A `drain()` success only confirms that tracked sinks have not reported failure; authoritative persistence requires an accepted Trace Writer receipt with matching request ID and event ID. Audit loss or uncertain delivery must not change a business result.
|
|
104
|
+
|
|
105
|
+
The Chrome MV3 Worker cannot import the Node npm SDK, so `scripts/build-api-aspects.mjs` emits a version-checked static browser script from the same canonical Trace source. The browser script is the sole generated runtime copy; no separate Writer is created.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// Only v2 Context API observations use the typed api field. Other event
|
|
2
|
+
// families cannot impersonate these records, including from disk.
|
|
3
|
+
const API_NAME=/^[a-z][A-Za-z0-9._-]{1,89}$/;
|
|
4
|
+
const SURFACES=new Set(['sdk','gateway','operator','trusted']);
|
|
5
|
+
const MODES=new Set(['read','write','unknown','internal','operator']);
|
|
6
|
+
const object=value=>value!==null&&typeof value==='object'&&!Array.isArray(value);
|
|
7
|
+
export const capability=Object.freeze({
|
|
8
|
+
id:'context.api',
|
|
9
|
+
schemaVersion:2,
|
|
10
|
+
errorCode:'TRACE_INVALID_API',
|
|
11
|
+
description:'Typed Context API BEGIN/CONFIRMED/FAILED function boundary',
|
|
12
|
+
// Query projection travels with the event contract, not a Reader switch.
|
|
13
|
+
usageName:v=>'context.'+v.api.surface+'.'+v.api.name,
|
|
14
|
+
validate(v){
|
|
15
|
+
const api=v?.api;
|
|
16
|
+
return v?.component==='context'&&
|
|
17
|
+
['BEGIN','CONFIRMED','FAILED'].includes(v?.status)&&
|
|
18
|
+
object(api)&&Object.keys(api).length===3&&
|
|
19
|
+
Object.keys(api).every(k=>['name','surface','mode'].includes(k))&&
|
|
20
|
+
typeof api.name==='string'&&API_NAME.test(api.name)&&
|
|
21
|
+
SURFACES.has(api.surface)&&MODES.has(api.mode);
|
|
22
|
+
}
|
|
23
|
+
});
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Sanitized aggregateable MCP call event. No arguments, results or URLs.
|
|
2
|
+
// This system-local telemetry scope is not a Context Project or approval.
|
|
3
|
+
const METHOD=/^[a-z][A-Za-z0-9_.:-]{1,126}$/;
|
|
4
|
+
const CODE=/^[A-Z][A-Z0-9_]{1,95}$/;
|
|
5
|
+
export const capability=Object.freeze({
|
|
6
|
+
id:'typed.api.call',schemaVersion:2,errorCode:'TRACE_INVALID_API_USAGE',
|
|
7
|
+
description:'Generic public API begin/completion/failure with safe method identity',
|
|
8
|
+
usageName:v=>v.apiName,
|
|
9
|
+
validate(v){
|
|
10
|
+
return v?.component==='gateway'&&
|
|
11
|
+
v.projectRef==='api_system'&&
|
|
12
|
+
['BEGIN','CONFIRMED','FAILED'].includes(v.status)&&
|
|
13
|
+
typeof v.apiName==='string'&&METHOD.test(v.apiName)&&
|
|
14
|
+
v.api===undefined&&v.taskRef===undefined&&v.sessionRef===undefined&&
|
|
15
|
+
v.actionId===undefined&&v.evidenceRef===undefined&&
|
|
16
|
+
(v.status==='FAILED'
|
|
17
|
+
?typeof v.errorCode==='string'&&CODE.test(v.errorCode)
|
|
18
|
+
:v.errorCode===undefined)&&
|
|
19
|
+
(v.status==='BEGIN'?v.durationMs===undefined
|
|
20
|
+
:Number.isSafeInteger(v.durationMs)&&v.durationMs>=0);
|
|
21
|
+
}
|
|
22
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import {createApiAspect as createSharedApiAspect} from './lib/api-aspect.mjs';
|
|
2
|
+
const apiAspect=createSharedApiAspect('@tomflow/chatloop-trace',
|
|
3
|
+
{bufferUntilSubscribe:true});
|
|
4
|
+
// Shared AOP factory is a versioned public SDK capability. Consumers reuse
|
|
5
|
+
// it directly; only MV3 browsers require a generated static script.
|
|
6
|
+
export const createApiAspect=apiAspect.observe('createApiAspect',
|
|
7
|
+
(packageName,options)=>{
|
|
8
|
+
const facet=createSharedApiAspect(packageName,options);
|
|
9
|
+
// The public current() method must inspect its caller's async context,
|
|
10
|
+
// before the logging span changes that context.
|
|
11
|
+
const current=apiAspect.observe('aspect.current',facet.current,'sdk',
|
|
12
|
+
{preserveCallerContext:true});
|
|
13
|
+
return apiAspect.methods(Object.freeze({...facet,current}),'aspect');
|
|
14
|
+
});
|
|
15
|
+
// Tools composes this opt-in soft observation port into its one Supervisor.
|
|
16
|
+
// Never store telemetry in Trace SDK by creating a second writer.
|
|
17
|
+
export const subscribeTraceApiLog=apiAspect.subscribe;
|
|
18
|
+
// Two data capabilities, shared AOP factory and one observation port. Correlation-id
|
|
19
|
+
// generation and schema constants remain private implementation details.
|
|
20
|
+
import {eventCapabilities} from './events.generated.mjs';
|
|
21
|
+
import {configureTraceEvents,createTraceReader as openReader,createTraceWriter as openWriter} from './lib/trace.mjs';
|
|
22
|
+
configureTraceEvents(eventCapabilities);
|
|
23
|
+
export const createTraceWriter=apiAspect.observe('createTraceWriter',
|
|
24
|
+
options=>{
|
|
25
|
+
const writer=openWriter(options);
|
|
26
|
+
// The writer is the single logging owner. Send only its public method
|
|
27
|
+
// observations through its raw private append path: calling the public
|
|
28
|
+
// record() here would recursively observe its own audit events.
|
|
29
|
+
const writerAspect=createSharedApiAspect('@tomflow/chatloop-trace',{
|
|
30
|
+
sink:event=>{
|
|
31
|
+
try{
|
|
32
|
+
writer.record({event:'typed.api.call',component:'gateway',
|
|
33
|
+
projectRef:'api_system',traceId:event.traceId,spanId:event.spanId,
|
|
34
|
+
...(event.parentSpanId?{parentSpanId:event.parentSpanId}:{}),
|
|
35
|
+
apiName:'trace.'+event.api,
|
|
36
|
+
status:event.phase==='BEGIN'?'BEGIN':event.phase==='OK'
|
|
37
|
+
?'CONFIRMED':'FAILED',
|
|
38
|
+
...(event.phase!=='BEGIN'?{durationMs:event.durationMs}:{}),
|
|
39
|
+
...(event.phase==='FAILED'?{errorCode:event.errorCode}:{})});
|
|
40
|
+
return true;
|
|
41
|
+
}catch{return false} // Soft audit must never modify an API result.
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
// The self-observation queue is bounded. Expose loss in the existing
|
|
45
|
+
// Writer health receipt so a missing audit can never look like PASS.
|
|
46
|
+
return writerAspect.methods(Object.freeze({...writer,
|
|
47
|
+
health:()=>({...writer.health(),apiObservation:writerAspect.health()})
|
|
48
|
+
}),'writer');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// Only the scoped diagnostic contract is used outside Trace. Keep raw query
|
|
52
|
+
// available internally for the private reader's own diagnostic algorithm.
|
|
53
|
+
export const createTraceReader=apiAspect.observe('createTraceReader',
|
|
54
|
+
options=>{
|
|
55
|
+
const reader=openReader(options);
|
|
56
|
+
return apiAspect.methods(Object.freeze({diagnose:reader.diagnose,
|
|
57
|
+
apiUsage:reader.apiUsage,health:reader.health}),
|
|
58
|
+
'reader');
|
|
59
|
+
});
|