@tomflow/chatloop-tools 0.9.43 → 0.9.44
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/index.mjs +27 -24
- package/lib/trace-gateway.mjs +42 -26
- package/lib/trace-observation.mjs +5 -3
- package/package.json +1 -1
- package/providers/document.mjs +28 -4
package/index.mjs
CHANGED
|
@@ -13,7 +13,7 @@ import {createCliCommandRouter} from './lib/cli-command-router.mjs';
|
|
|
13
13
|
let auditPort=null;
|
|
14
14
|
const auditBacklog=[];
|
|
15
15
|
let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0,auditLost=0;
|
|
16
|
-
let formObservationLost=0;
|
|
16
|
+
let formObservationLost=0,documentObservationLost=0;
|
|
17
17
|
const OBSERVER_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;
|
|
18
18
|
const localError=code=>Object.assign(Error(code),{code});
|
|
19
19
|
const MAX_AUDIT_BACKLOG=1024,MAX_NO_OWNER_RETRIES=20;
|
|
@@ -168,8 +168,9 @@ async function runtime(){
|
|
|
168
168
|
const traceTalk=async request=>{
|
|
169
169
|
const result=await control.talk(request);
|
|
170
170
|
if(request?.action!=='__trace_health'||!result?.traceHealth)return result;
|
|
171
|
-
const health={...result.traceHealth,formObservationLost};
|
|
172
|
-
if(formObservationLost>0
|
|
171
|
+
const health={...result.traceHealth,formObservationLost,documentObservationLost};
|
|
172
|
+
if((formObservationLost>0||documentObservationLost>0)
|
|
173
|
+
&&health.status==='OK')health.status='TRACE_DEGRADED';
|
|
173
174
|
return {...result,traceHealth:health};
|
|
174
175
|
};
|
|
175
176
|
traceGateway.configureTraceGateway({paths:control.paths,
|
|
@@ -185,29 +186,31 @@ async function runtime(){
|
|
|
185
186
|
subscribeContextApiLog(event=>contextGateway.forwardContextApiLog(event));
|
|
186
187
|
// One statically generated provider composition, shared by tools/list and
|
|
187
188
|
// tools/call. Adding an independent provider never edits this Gateway.
|
|
189
|
+
const appObserver=(kind,idKey,lost)=>({
|
|
190
|
+
observe:async payload=>{
|
|
191
|
+
const parent=apiAspect.current();
|
|
192
|
+
if(!parent||!OBSERVER_UUID.test(parent.traceId||'')
|
|
193
|
+
||!OBSERVER_UUID.test(parent.spanId||''))
|
|
194
|
+
throw localError(kind+'_TRACE_PARENT_MISSING');
|
|
195
|
+
const result=await control.talk({
|
|
196
|
+
contract:control.CONTRACT,action:'__trace_observation',
|
|
197
|
+
requestId:randomUUID(),event:payload.event,
|
|
198
|
+
status:payload.status||'CONFIRMED',
|
|
199
|
+
traceId:parent.traceId,spanId:parent.spanId,
|
|
200
|
+
projectRef:'api_system',sessionRef:payload.traceRef,
|
|
201
|
+
evidenceRef:payload[idKey],
|
|
202
|
+
...(payload.errorCode?{errorCode:payload.errorCode}:{})
|
|
203
|
+
},1800);
|
|
204
|
+
if(result?.status!=='OK'||!OBSERVER_UUID.test(result.eventId||''))
|
|
205
|
+
throw localError(result?.error?.code||kind+'_TRACE_OBSERVATION_UNCONFIRMED');
|
|
206
|
+
return result;
|
|
207
|
+
},lost
|
|
208
|
+
});
|
|
188
209
|
const coreToolRouter=createMcpToolRouter(providerDefinitions,{
|
|
189
210
|
control,release:releaseApi,terminal:terminalPolicy,context:contextGateway,
|
|
190
|
-
form:{
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
if(!parent||!OBSERVER_UUID.test(parent.traceId||'')
|
|
194
|
-
||!OBSERVER_UUID.test(parent.spanId||''))
|
|
195
|
-
throw localError('FORM_TRACE_PARENT_MISSING');
|
|
196
|
-
const result=await control.talk({
|
|
197
|
-
contract:control.CONTRACT,action:'__trace_observation',
|
|
198
|
-
requestId:randomUUID(),event:payload.event,
|
|
199
|
-
status:payload.status||'CONFIRMED',
|
|
200
|
-
traceId:parent.traceId,spanId:parent.spanId,
|
|
201
|
-
projectRef:'api_system',sessionRef:payload.traceRef,
|
|
202
|
-
evidenceRef:payload.formId,
|
|
203
|
-
...(payload.errorCode?{errorCode:payload.errorCode}:{})
|
|
204
|
-
},1800);
|
|
205
|
-
if(result?.status!=='OK'||!OBSERVER_UUID.test(result.eventId||''))
|
|
206
|
-
throw localError(result?.error?.code||'FORM_TRACE_OBSERVATION_UNCONFIRMED');
|
|
207
|
-
return result;
|
|
208
|
-
},
|
|
209
|
-
lost:()=>{formObservationLost++}
|
|
210
|
-
},trace:traceGateway,
|
|
211
|
+
form:appObserver('FORM','formId',()=>{formObservationLost++}),
|
|
212
|
+
document:appObserver('DOCUMENT','documentId',()=>{documentObservationLost++}),
|
|
213
|
+
trace:traceGateway,
|
|
211
214
|
extension:{
|
|
212
215
|
forwardExtensionAction:extensionProxy.forwardExtensionAction,
|
|
213
216
|
observeExtensionResult:traceGateway.observeExtensionResult
|
package/lib/trace-gateway.mjs
CHANGED
|
@@ -24,7 +24,7 @@ export const traceGatewayEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1
|
|
|
24
24
|
&&getAllowedProjects().length===1;
|
|
25
25
|
export const traceDiagnoseTool={
|
|
26
26
|
name:'chat_loop_trace_diagnose',
|
|
27
|
-
description:'Read-only Trace timeline for an explicitly authorized Project. A separate api_system lookup is allowed
|
|
27
|
+
description:'Read-only Trace timeline for an explicitly authorized Project. A separate api_system lookup is allowed with the unguessable Form/Document traceRef returned by Prepare/Show; exposes only that App instance and matching parent MCP API spans.',
|
|
28
28
|
inputSchema:{
|
|
29
29
|
type:'object',additionalProperties:false,
|
|
30
30
|
required:['projectRef'],
|
|
@@ -43,10 +43,14 @@ export const traceDiagnoseTool={
|
|
|
43
43
|
const STAGE_NAMES=['intent','project','tooling','requirements','plan','approval'];
|
|
44
44
|
const STAGE_OUTCOMES=['OBSERVED','BLOCKED','UNVERIFIED'];
|
|
45
45
|
const USER_EVIDENCE=/^user:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
46
|
-
const
|
|
46
|
+
const APP_TRACE_REF=new RegExp(UUID);
|
|
47
47
|
const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
48
|
+
const DOC_ID=/^[A-Za-z0-9][A-Za-z0-9_.-]{7,127}$/;
|
|
48
49
|
const FORM_EVENT=/^form\.(?:prepared|rendered|submitted)\.(?:soft_observed|failed)$/;
|
|
49
|
-
const
|
|
50
|
+
const DOC_EVENT=/^document\.(?:shown|rendered)\.(?:soft_observed|failed)$/;
|
|
51
|
+
const APP_APIS=new Set(['mcp.chat_loop_form__prepare','mcp.chat_loop_form__render',
|
|
52
|
+
'mcp.chat_loop_form__submit','mcp.chat_loop_document__show',
|
|
53
|
+
'mcp.chat_loop_document__render']);
|
|
50
54
|
export const traceStageTool={
|
|
51
55
|
name:'chat_loop_trace_stage',
|
|
52
56
|
description:'Record an explicitly SOFT agent-stage observation (including R/P revision) in the existing Trace writer. Optional user:<uuid> evidenceRef is a caller assertion, NOT verified host-click provenance; no approval/Owner/content is stored. Return traceId for later calls; never use this as task approval.',
|
|
@@ -98,25 +102,33 @@ const getAllowedProjects=()=>{
|
|
|
98
102
|
// syntax; filtering entries could silently broaden a malformed config.
|
|
99
103
|
return entries.length===1&&PROJECT.test(entries[0])?entries:[];
|
|
100
104
|
};
|
|
101
|
-
async function
|
|
105
|
+
async function diagnoseAppTrace(args){
|
|
102
106
|
const reader=createTraceReader({filePath:paths().log,allowedProjects:['api_system']});
|
|
103
107
|
const base=await reader.diagnose({projectRef:'api_system',
|
|
104
108
|
sessionRef:args.sessionRef,maxEvents:args.maxEvents});
|
|
105
|
-
const
|
|
106
|
-
event.sessionRef===args.sessionRef&&
|
|
107
|
-
|
|
109
|
+
const appEvents=base.timeline.filter(event=>
|
|
110
|
+
event.sessionRef===args.sessionRef&&
|
|
111
|
+
(FORM_EVENT.test(event.event||'')&&FORM_ID.test(event.evidenceRef||'')
|
|
112
|
+
||DOC_EVENT.test(event.event||'')&&DOC_ID.test(event.evidenceRef||'')));
|
|
113
|
+
const kind=appEvents[0]?.event.startsWith('document.')?'document':'form';
|
|
114
|
+
const matching=appEvents.filter(event=>event.event.startsWith(kind+'.'));
|
|
115
|
+
const prefix=kind.toUpperCase();
|
|
108
116
|
const gaps=base.gaps.filter(gap=>gap!=='NO_MATCHING_EVENTS');
|
|
109
117
|
const parentKeys=new Map();
|
|
110
|
-
for(const event of
|
|
118
|
+
for(const event of matching){
|
|
111
119
|
const apiName=event.event.startsWith('form.prepared.')
|
|
112
120
|
?'mcp.chat_loop_form__prepare'
|
|
113
121
|
:event.event.startsWith('form.rendered.')
|
|
114
|
-
?'mcp.chat_loop_form__render'
|
|
115
|
-
|
|
122
|
+
?'mcp.chat_loop_form__render'
|
|
123
|
+
:event.event.startsWith('form.submitted.')
|
|
124
|
+
?'mcp.chat_loop_form__submit'
|
|
125
|
+
:event.event.startsWith('document.shown.')
|
|
126
|
+
?'mcp.chat_loop_document__show':'mcp.chat_loop_document__render';
|
|
127
|
+
if(!event.parentSpanId){gaps.push(prefix+'_API_PARENT_MISSING');continue}
|
|
116
128
|
parentKeys.set(event.traceId+':'+event.parentSpanId,apiName);
|
|
117
129
|
}
|
|
118
130
|
const apiEvents=[];
|
|
119
|
-
for(const traceId of new Set(
|
|
131
|
+
for(const traceId of new Set(matching.map(event=>event.traceId))){
|
|
120
132
|
const query=await reader.diagnose({projectRef:'api_system',traceId,maxEvents:200});
|
|
121
133
|
for(const gap of query.gaps)
|
|
122
134
|
if(['TRACE_MALFORMED_LINES','TRACE_WINDOW_TRUNCATED',
|
|
@@ -125,7 +137,7 @@ async function diagnoseFormTrace(args){
|
|
|
125
137
|
for(const event of query.timeline){
|
|
126
138
|
const key=event.traceId+':'+event.spanId;
|
|
127
139
|
if(event.event==='typed.api.call'&&parentKeys.get(key)===event.apiName
|
|
128
|
-
&&
|
|
140
|
+
&&APP_APIS.has(event.apiName))apiEvents.push(event);
|
|
129
141
|
}
|
|
130
142
|
}
|
|
131
143
|
for(const [key,apiName] of parentKeys){
|
|
@@ -136,21 +148,23 @@ async function diagnoseFormTrace(args){
|
|
|
136
148
|
const terminals=linked.filter(event=>
|
|
137
149
|
['CONFIRMED','FAILED'].includes(event.status));
|
|
138
150
|
if(begins.length!==1||terminals.length!==1)
|
|
139
|
-
gaps.push('
|
|
151
|
+
gaps.push(prefix+'_API_PARENT_GAP');
|
|
140
152
|
const terminal=terminals[0];
|
|
141
|
-
if(terminal&&
|
|
153
|
+
if(terminal&&matching.some(event=>event.traceId===traceId
|
|
142
154
|
&&event.parentSpanId===spanId&&event.status!==terminal.status))
|
|
143
|
-
gaps.push('
|
|
155
|
+
gaps.push(prefix+'_API_STATUS_MISMATCH');
|
|
144
156
|
}
|
|
145
|
-
const
|
|
146
|
-
if(
|
|
147
|
-
if(
|
|
148
|
-
|
|
157
|
+
const ids=[...new Set(matching.map(event=>event.evidenceRef))];
|
|
158
|
+
if(ids.length>1)gaps.push(prefix+'_TRACE_REF_REUSED');
|
|
159
|
+
if(appEvents.length!==matching.length)gaps.push('APP_TRACE_REF_CROSS_KIND');
|
|
160
|
+
if(!matching.length)gaps.push('NO_MATCHING_EVENTS');
|
|
161
|
+
const timeline=[...matching,...apiEvents]
|
|
149
162
|
.sort((a,b)=>Date.parse(a.time)-Date.parse(b.time));
|
|
150
163
|
const last=timeline.at(-1)||null;
|
|
151
|
-
const unknown=
|
|
152
|
-
return {traceId:null,projectRef:'api_system',
|
|
153
|
-
formId:
|
|
164
|
+
const unknown=matching.some(event=>['UNKNOWN','BLOCKED'].includes(event.status));
|
|
165
|
+
return {traceId:null,projectRef:'api_system',
|
|
166
|
+
...(kind==='form'?{formTraceRef:args.sessionRef,formId:ids.length===1?ids[0]:null}
|
|
167
|
+
:{documentTraceRef:args.sessionRef,documentId:ids.length===1?ids[0]:null}),
|
|
154
168
|
inspected:timeline.length,totalMatched:timeline.length,
|
|
155
169
|
lastConfirmed:[...timeline].reverse().find(event=>event.status==='CONFIRMED')
|
|
156
170
|
?{eventId:[...timeline].reverse().find(event=>event.status==='CONFIRMED').eventId,
|
|
@@ -169,15 +183,15 @@ export async function runTraceDiagnose(args){
|
|
|
169
183
|
throw fail('TRACE_INVALID_ARGUMENT');
|
|
170
184
|
if(args.projectRef==='api_system'){
|
|
171
185
|
if(args.traceId!==undefined||typeof args.sessionRef!=='string'
|
|
172
|
-
||!
|
|
173
|
-
throw fail('
|
|
186
|
+
||!APP_TRACE_REF.test(args.sessionRef))
|
|
187
|
+
throw fail('TRACE_APP_LOOKUP_INVALID');
|
|
174
188
|
}else{
|
|
175
189
|
if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
|
|
176
190
|
if(typeof args.projectRef!=='string'||!getAllowedProjects().includes(args.projectRef))
|
|
177
191
|
throw fail('TRACE_PROJECT_ACCESS_DENIED');
|
|
178
192
|
}
|
|
179
193
|
const result=args.projectRef==='api_system'
|
|
180
|
-
?await
|
|
194
|
+
?await diagnoseAppTrace(args)
|
|
181
195
|
:await createTraceReader({filePath:paths().log,
|
|
182
196
|
allowedProjects:getAllowedProjects()}).diagnose(args);
|
|
183
197
|
try{
|
|
@@ -186,12 +200,14 @@ export async function runTraceDiagnose(args){
|
|
|
186
200
|
result.writerHealth=response.status==='OK'?response.traceHealth?.status||'UNKNOWN':'UNAVAILABLE';
|
|
187
201
|
if(args.projectRef==='api_system'&&response.traceHealth?.formObservationLost>0)
|
|
188
202
|
result.gaps.push('FORM_TRACE_OBSERVATION_LOSS');
|
|
203
|
+
if(args.projectRef==='api_system'&&response.traceHealth?.documentObservationLost>0)
|
|
204
|
+
result.gaps.push('DOCUMENT_TRACE_OBSERVATION_LOSS');
|
|
189
205
|
}catch{result.writerHealth='UNAVAILABLE'}
|
|
190
206
|
if(result.writerHealth!=='OK'){
|
|
191
207
|
if(['UNKNOWN','UNAVAILABLE'].includes(result.writerHealth))
|
|
192
208
|
result.gaps.push('TRACE_WRITER_UNAVAILABLE');
|
|
193
209
|
if(result.writerHealth==='TRACE_DEGRADED')
|
|
194
|
-
result.gaps.push('
|
|
210
|
+
result.gaps.push('TRACE_APP_OBSERVATION_LOSS');
|
|
195
211
|
result.confidence='INCOMPLETE';
|
|
196
212
|
result.retryDisposition='VERIFY_AUTHORITATIVE_RECEIPT_FIRST';
|
|
197
213
|
}
|
|
@@ -18,6 +18,7 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
|
|
|
18
18
|
// not become reachable merely because Context collection is active.
|
|
19
19
|
const isContextApi=req?.event==='context.api';
|
|
20
20
|
const form=/^form\.(prepared|rendered|submitted)\.(soft_observed|failed)$/.test(req?.event||'');
|
|
21
|
+
const document=/^document\.(shown|rendered)\.(soft_observed|failed)$/.test(req?.event||'');
|
|
21
22
|
const contextGrant=observationGrants.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
|
|
22
23
|
const contextAuthorized=observationGrants.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
|
|
23
24
|
&&typeof contextGrant==='string'
|
|
@@ -27,7 +28,7 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
|
|
|
27
28
|
// Keep them in the existing api_system Writer without requiring a
|
|
28
29
|
// per-Project Trace grant or exposing Project/Chat/task identifiers.
|
|
29
30
|
if(isContextApi?!contextAuthorized:
|
|
30
|
-
form?req?.projectRef!=='api_system':
|
|
31
|
+
form||document?req?.projectRef!=='api_system':
|
|
31
32
|
!traceEnabled()||!allowedTraceProjects().has(req?.projectRef))
|
|
32
33
|
throw error('TRACE_PROJECT_ACCESS_DENIED');
|
|
33
34
|
// Context call observation has a stable event ID and typed API fields.
|
|
@@ -73,7 +74,7 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
|
|
|
73
74
|
return {contract:CONTRACT,requestId:req.requestId,status:'OK',
|
|
74
75
|
eventId:recorded.eventId};
|
|
75
76
|
}
|
|
76
|
-
if(form){
|
|
77
|
+
if(form||document){
|
|
77
78
|
const success=req.event.endsWith('.soft_observed');
|
|
78
79
|
const allowed=new Set(['contract','action','requestId','traceId','spanId',
|
|
79
80
|
'projectRef','sessionRef','evidenceRef','event','status','errorCode']);
|
|
@@ -84,7 +85,8 @@ export function createSupervisorTraceBridge({traceWriter,contract,error,
|
|
|
84
85
|
||!UUID_RE.test(req.requestId||'')||!UUID_RE.test(req.traceId||'')
|
|
85
86
|
||!UUID_RE.test(req.spanId||'')
|
|
86
87
|
||!UUID_RE.test(req.sessionRef||'')
|
|
87
|
-
||!(
|
|
88
|
+
||!(document?/^[A-Za-z0-9][A-Za-z0-9_.-]{7,127}$/:
|
|
89
|
+
/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/).test(req.evidenceRef||'')
|
|
88
90
|
||(success?req.errorCode!==undefined:!validError)
|
|
89
91
|
||Object.keys(req).some(k=>!allowed.has(k)))
|
|
90
92
|
throw error('TRACE_INVALID_ARGUMENT');
|
package/package.json
CHANGED
package/providers/document.mjs
CHANGED
|
@@ -12,6 +12,19 @@ const TYPE=/^[a-zA-Z0-9][a-zA-Z0-9.+/-]{0,79}$/;
|
|
|
12
12
|
const err=code=>Object.assign(Error(code),{code});
|
|
13
13
|
const result=data=>({content:[{type:'text',text:JSON.stringify(data)}],
|
|
14
14
|
structuredContent:data});
|
|
15
|
+
async function observeDocument(port,event,documentId,traceRef,errorCode){
|
|
16
|
+
if(typeof port?.observe!=='function'||!IDENT.test(documentId||'')
|
|
17
|
+
||!UUID.test(traceRef||''))return false;
|
|
18
|
+
try{
|
|
19
|
+
const reply=await port.observe({event,documentId,traceRef,
|
|
20
|
+
status:errorCode?'FAILED':'CONFIRMED',
|
|
21
|
+
...(errorCode?{errorCode}:{})});
|
|
22
|
+
if(reply?.status!=='OK'||!UUID.test(reply.eventId||'')){
|
|
23
|
+
port?.lost?.();return false;
|
|
24
|
+
}
|
|
25
|
+
return true;
|
|
26
|
+
}catch{port?.lost?.();return false}
|
|
27
|
+
}
|
|
15
28
|
const pure=(x,keys)=>x&&typeof x==='object'&&!Array.isArray(x)
|
|
16
29
|
&&Object.keys(x).every(k=>keys.includes(k));
|
|
17
30
|
const length=(x,n)=>typeof x==='string'&&x.trim().length>0&&x.length<=n;
|
|
@@ -73,7 +86,7 @@ function rendered(args){
|
|
|
73
86
|
}
|
|
74
87
|
export const provider=Object.freeze({
|
|
75
88
|
id:'document',order:6,names:tools.map(tool=>tool.name),
|
|
76
|
-
create(){
|
|
89
|
+
create({document}={}){
|
|
77
90
|
return Object.freeze({
|
|
78
91
|
tools:()=>tools,
|
|
79
92
|
resources:()=>[URI,...LEGACY_URIS].map(uri=>({uri,name:'Chat Loop Document',
|
|
@@ -88,9 +101,20 @@ export const provider=Object.freeze({
|
|
|
88
101
|
permissions:{clipboardWrite:{}}}}}]};
|
|
89
102
|
},
|
|
90
103
|
async call(name,args){
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
throw err('UNKNOWN_TOOL');
|
|
104
|
+
const isShow=name===tools[0].name;
|
|
105
|
+
const isRender=name===tools[1].name;
|
|
106
|
+
if(!isShow&&!isRender)throw err('UNKNOWN_TOOL');
|
|
107
|
+
try{
|
|
108
|
+
const value=isShow?show(args):rendered(args);
|
|
109
|
+
void observeDocument(document,isShow?'document.shown.soft_observed':
|
|
110
|
+
'document.rendered.soft_observed',value.documentId,value.traceRef);
|
|
111
|
+
return result(value);
|
|
112
|
+
}catch(error){
|
|
113
|
+
void observeDocument(document,isShow?'document.shown.failed':
|
|
114
|
+
'document.rendered.failed',args?.documentId,args?.traceRef,
|
|
115
|
+
error.code||'DOCUMENT_FAILED');
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
94
118
|
}
|
|
95
119
|
});
|
|
96
120
|
}
|