@tomflow/chatloop-tools 0.9.19 → 0.9.20
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/package.json +1 -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
package/README.md
CHANGED
|
@@ -63,8 +63,8 @@ The six built-in Providers are:
|
|
|
63
63
|
- `extension`: official pinned Extension CLI and nine scoped actions
|
|
64
64
|
- `runtime`: exact-request receipt lookup without replay
|
|
65
65
|
- `context`: independent Context SDK read/write schemas and fixed CLI
|
|
66
|
-
- `trace`: Project-scoped diagnosis and SOFT stage observations
|
|
67
|
-
- `form`:
|
|
66
|
+
- `trace`: Project-scoped diagnosis and SOFT stage observations, plus a bearer-token-scoped Form Trace lookup using the Prepare `traceRef`
|
|
67
|
+
- `form`: a stateless ChatGPT A/B MCP App adapter; `prepare` renders a caller-supplied card, preserves or generates `formId`, and returns a random `traceRef`; `submit` validates the choice/comment and asks the shared Supervisor to durably claim that `traceRef` once before the App may request `ui/message`. The claim is an at-most-once UI side-effect guard, not business state, user identity, message delivery or approval. Form owns no Context, approval, caller, workflow, expiry, cache or form lifecycle; Prepare/Submit observations and the claim are correlated in the existing Trace by `sessionRef=traceRef` and `evidenceRef=formId`.
|
|
68
68
|
|
|
69
69
|
`npm run build:providers` generates `providers.generated.mjs`, the static
|
|
70
70
|
assembly and release fingerprint manifest. Both `tools/list` and `tools/call`
|
|
@@ -107,7 +107,12 @@ to any existing Provider, the Gateway, or either npm entrypoint.
|
|
|
107
107
|
trigger retries of unknown effects. In particular, verified Extension MCP
|
|
108
108
|
results are returned **before** optional Trace transport finishes; a
|
|
109
109
|
slow, rejecting or unavailable observer cannot replace the action receipt.
|
|
110
|
-
|
|
110
|
+
Form submission claims are different: the Supervisor must durably append
|
|
111
|
+
the at-most-once claim before Submit returns success; if that receipt is
|
|
112
|
+
unknown or the Trace writer is unhealthy, the App must not request a user
|
|
113
|
+
message or retry. Form observations remain best-effort evidence and
|
|
114
|
+
dropped observations are surfaced by Trace health; they are not an
|
|
115
|
+
all-API AOP coverage claim.
|
|
111
116
|
|
|
112
117
|
No legacy Task Registry MCP or JSON fallback is shipped. Historical
|
|
113
118
|
SourceUnit files remain migration evidence, not alternate current facts.
|
package/index.mjs
CHANGED
|
@@ -12,6 +12,9 @@ import {createCliCommandRouter} from './lib/cli-command-router.mjs';
|
|
|
12
12
|
let auditPort=null;
|
|
13
13
|
const auditBacklog=[];
|
|
14
14
|
let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0,auditLost=0;
|
|
15
|
+
let formObservationLost=0;
|
|
16
|
+
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;
|
|
17
|
+
const localError=code=>Object.assign(Error(code),{code});
|
|
15
18
|
const MAX_AUDIT_BACKLOG=1024,MAX_NO_OWNER_RETRIES=20;
|
|
16
19
|
// The CLI can emit BEGIN before a cold Supervisor has opened its IPC socket.
|
|
17
20
|
// Keep ordered, bounded soft observations until that exact socket exists;
|
|
@@ -153,8 +156,15 @@ async function runtime(){
|
|
|
153
156
|
release.configureRelease({PACKAGE_VERSION:control.PACKAGE_VERSION,
|
|
154
157
|
activeDesktopCommands:releasePreflight.activeDesktopCommands,
|
|
155
158
|
awaitStopped:releasePreflight.awaitStopped});
|
|
159
|
+
const traceTalk=async request=>{
|
|
160
|
+
const result=await control.talk(request);
|
|
161
|
+
if(request?.action!=='__trace_health'||!result?.traceHealth)return result;
|
|
162
|
+
const health={...result.traceHealth,formObservationLost};
|
|
163
|
+
if(formObservationLost>0&&health.status==='OK')health.status='TRACE_DEGRADED';
|
|
164
|
+
return {...result,traceHealth:health};
|
|
165
|
+
};
|
|
156
166
|
traceGateway.configureTraceGateway({paths:control.paths,
|
|
157
|
-
talk:
|
|
167
|
+
talk:traceTalk,CONTRACT:control.CONTRACT});
|
|
158
168
|
contextGateway.configureContextApiLog({
|
|
159
169
|
current:apiAspect.current,
|
|
160
170
|
record:entry=>control.talk({
|
|
@@ -168,14 +178,44 @@ async function runtime(){
|
|
|
168
178
|
// tools/call. Adding an independent provider never edits this Gateway.
|
|
169
179
|
const coreToolRouter=createMcpToolRouter(providerDefinitions,{
|
|
170
180
|
control,release,terminal:terminalPolicy,context:contextGateway,
|
|
171
|
-
form:{
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
181
|
+
form:{
|
|
182
|
+
current:apiAspect.current,
|
|
183
|
+
claimSubmission:async ({formId,traceRef})=>{
|
|
184
|
+
const parent=apiAspect.current();
|
|
185
|
+
if(!parent||!OBSERVER_UUID.test(parent.traceId||'')
|
|
186
|
+
||!OBSERVER_UUID.test(parent.spanId||''))
|
|
187
|
+
throw localError('FORM_SUBMISSION_CLAIM_PARENT_MISSING');
|
|
188
|
+
let result;
|
|
189
|
+
try{
|
|
190
|
+
result=await control.talk({
|
|
191
|
+
contract:control.CONTRACT,action:'__form_submission_claim',
|
|
192
|
+
requestId:randomUUID(),formId,traceRef,
|
|
193
|
+
traceId:parent.traceId,spanId:parent.spanId
|
|
194
|
+
},1800);
|
|
195
|
+
}catch{
|
|
196
|
+
throw localError('FORM_SUBMISSION_CLAIM_UNKNOWN');
|
|
197
|
+
}
|
|
198
|
+
if(result?.status!=='FORM_SUBMISSION_CLAIMED'
|
|
199
|
+
||!OBSERVER_UUID.test(result.eventId||''))
|
|
200
|
+
throw localError(result?.error?.code||'FORM_SUBMISSION_CLAIM_UNKNOWN');
|
|
201
|
+
return result;
|
|
202
|
+
},
|
|
203
|
+
observe:async payload=>{
|
|
204
|
+
const result=await control.talk({
|
|
205
|
+
contract:control.CONTRACT,action:'__trace_observation',
|
|
206
|
+
requestId:randomUUID(),event:payload.event,
|
|
207
|
+
status:payload.status||'CONFIRMED',
|
|
208
|
+
traceId:payload.traceId,spanId:payload.spanId,
|
|
209
|
+
projectRef:'api_system',sessionRef:payload.traceRef,
|
|
210
|
+
evidenceRef:payload.formId,
|
|
211
|
+
...(payload.errorCode?{errorCode:payload.errorCode}:{})
|
|
212
|
+
},1800);
|
|
213
|
+
if(result?.status!=='OK'||!OBSERVER_UUID.test(result.eventId||''))
|
|
214
|
+
throw localError(result?.error?.code||'FORM_TRACE_OBSERVATION_UNCONFIRMED');
|
|
215
|
+
return result;
|
|
216
|
+
},
|
|
217
|
+
lost:()=>{formObservationLost++}
|
|
218
|
+
},trace:traceGateway,
|
|
179
219
|
extension:{
|
|
180
220
|
forwardExtensionAction:extensionProxy.forwardExtensionAction,
|
|
181
221
|
observeExtensionResult:traceGateway.observeExtensionResult
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import {createTraceWriter,createTraceReader} from '@tomflow/chatloop-trace';
|
|
2
|
+
|
|
3
|
+
const OBSERVER_ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
4
|
+
const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
5
|
+
const OBSERVER_NAME=/^(?:mcp|extension|tools|context|trace|tunnel)\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
|
|
6
|
+
const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
|
|
7
|
+
'traceId','spanId','parentSpanId','apiName','phase','durationMs','errorCode',
|
|
8
|
+
'ownerNonce','managerPid']);
|
|
9
|
+
|
|
10
|
+
export function createSupervisorObservability({
|
|
11
|
+
filePath,rotationEnabled,contextUsageGrant,contract,nonce,processId,
|
|
12
|
+
createSupervisorTraceBridge,error
|
|
13
|
+
}){
|
|
14
|
+
const traceWriter=createTraceWriter({
|
|
15
|
+
filePath,enableRotation:rotationEnabled
|
|
16
|
+
});
|
|
17
|
+
const usageScopes=['api_system',...(
|
|
18
|
+
typeof contextUsageGrant==='string'&&
|
|
19
|
+
/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextUsageGrant)
|
|
20
|
+
?[contextUsageGrant]:[])];
|
|
21
|
+
const usageReader=createTraceReader({filePath,allowedProjects:usageScopes});
|
|
22
|
+
const formClaimInFlight=new Set();
|
|
23
|
+
|
|
24
|
+
// Control telemetry is bounded and asynchronous; it never changes a
|
|
25
|
+
// confirmed or unknown business result.
|
|
26
|
+
const MAX_CONTROL_AUDIT=1024,CONTROL_AUDIT_BATCH=64,controlAudit=[];
|
|
27
|
+
let controlAuditScheduled=false,controlAuditDropped=0;
|
|
28
|
+
const flushControlAudit=()=>{
|
|
29
|
+
controlAuditScheduled=false;
|
|
30
|
+
for(let i=0;i<CONTROL_AUDIT_BATCH&&controlAudit.length;i++){
|
|
31
|
+
const {event,detail}=controlAudit.shift();
|
|
32
|
+
try{traceWriter.recordControl(event,detail)}catch{}
|
|
33
|
+
}
|
|
34
|
+
if(controlAudit.length){
|
|
35
|
+
controlAuditScheduled=true;
|
|
36
|
+
setImmediate(flushControlAudit);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const flushPending=()=>{while(controlAudit.length)flushControlAudit()};
|
|
40
|
+
const log=(event,detail={})=>{
|
|
41
|
+
if(controlAudit.length>=MAX_CONTROL_AUDIT){controlAuditDropped++;return}
|
|
42
|
+
controlAudit.push({event,detail:{
|
|
43
|
+
status:detail?.status,requestId:detail?.requestId,
|
|
44
|
+
errorCode:detail?.errorCode
|
|
45
|
+
}});
|
|
46
|
+
if(!controlAuditScheduled){
|
|
47
|
+
controlAuditScheduled=true;
|
|
48
|
+
setImmediate(flushControlAudit);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
const traceHealth=()=>{
|
|
52
|
+
const health=traceWriter.health();
|
|
53
|
+
const writerAuditLost=(health.apiObservation?.dropped||0)>0||
|
|
54
|
+
(health.apiObservation?.sinkFailures||0)>0;
|
|
55
|
+
return {...health,controlAuditDropped,controlAuditPending:controlAudit.length,
|
|
56
|
+
...(writerAuditLost&&health.status==='OK'
|
|
57
|
+
?{status:'TRACE_DEGRADED',errorCode:'TRACE_WRITER_API_LOG_GAP'}:{}),
|
|
58
|
+
...(controlAuditDropped>0&&health.status==='OK'
|
|
59
|
+
?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
|
|
60
|
+
};
|
|
61
|
+
const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
|
|
62
|
+
traceWriter,contract,error
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
function recordApiObservation(req){
|
|
66
|
+
if(req?.ownerNonce!==undefined||req?.managerPid!==undefined){
|
|
67
|
+
if(req.ownerNonce!==nonce||req.managerPid!==processId)
|
|
68
|
+
throw Object.assign(Error('TRACE_API_OWNER_MISMATCH'),
|
|
69
|
+
{code:'TRACE_API_OWNER_MISMATCH'});
|
|
70
|
+
}
|
|
71
|
+
if(req?.contract!==contract||!OBSERVER_ID.test(req.requestId||'')||
|
|
72
|
+
!OBSERVER_ID.test(req.callId||'')||!OBSERVER_ID.test(req.traceId||'')||
|
|
73
|
+
req.spanId!==req.callId||
|
|
74
|
+
(req.parentSpanId!==undefined&&
|
|
75
|
+
(!OBSERVER_ID.test(req.parentSpanId)||req.parentSpanId===req.spanId))||
|
|
76
|
+
!OBSERVER_NAME.test(req.apiName||'')||
|
|
77
|
+
!['BEGIN','OK','FAILED'].includes(req.phase)||
|
|
78
|
+
Object.keys(req).some(k=>!OBSERVER_KEYS.has(k))||
|
|
79
|
+
(req.phase==='BEGIN'
|
|
80
|
+
?req.durationMs!==undefined||req.errorCode!==undefined
|
|
81
|
+
:!Number.isSafeInteger(req.durationMs)||req.durationMs<0||
|
|
82
|
+
(req.phase==='FAILED'
|
|
83
|
+
?req.errorCode!=='MCP_TOOL_ERROR'&&
|
|
84
|
+
!/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode||'')
|
|
85
|
+
:req.errorCode!==undefined)))
|
|
86
|
+
throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
|
|
87
|
+
const written=traceWriter.record({
|
|
88
|
+
event:'typed.api.call',component:'gateway',projectRef:'api_system',
|
|
89
|
+
traceId:req.traceId,spanId:req.spanId,
|
|
90
|
+
...(req.parentSpanId?{parentSpanId:req.parentSpanId}:{}),
|
|
91
|
+
apiName:req.apiName,
|
|
92
|
+
status:req.phase==='BEGIN'?'BEGIN':req.phase==='OK'?'CONFIRMED':'FAILED',
|
|
93
|
+
...(req.phase!=='BEGIN'?{durationMs:req.durationMs}:{}),
|
|
94
|
+
...(req.phase==='FAILED'?{errorCode:req.errorCode}:{})
|
|
95
|
+
});
|
|
96
|
+
return {contract,requestId:req.requestId,status:'OK',eventId:written.eventId};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function apiUsage(req){
|
|
100
|
+
if(req?.contract!==contract||
|
|
101
|
+
Object.keys(req).some(k=>!['contract','action','requestId',
|
|
102
|
+
'windowMinutes','limit'].includes(k))||
|
|
103
|
+
!OBSERVER_ID.test(req.requestId||''))
|
|
104
|
+
throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
|
|
105
|
+
const summary=await usageReader.apiUsage({
|
|
106
|
+
windowMinutes:req.windowMinutes??60,limit:req.limit??100});
|
|
107
|
+
return {contract,requestId:req.requestId,status:'OK',summary};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function claimFormSubmission(req){
|
|
111
|
+
const allowed=new Set(['contract','action','requestId','formId','traceRef',
|
|
112
|
+
'traceId','spanId']);
|
|
113
|
+
if(req?.contract!==contract||Object.keys(req).some(key=>!allowed.has(key))||
|
|
114
|
+
!OBSERVER_ID.test(req.requestId||'')||
|
|
115
|
+
typeof req.formId!=='string'||!FORM_ID.test(req.formId)||
|
|
116
|
+
!OBSERVER_ID.test(req.traceRef||'')||!OBSERVER_ID.test(req.traceId||'')||
|
|
117
|
+
!OBSERVER_ID.test(req.spanId||''))
|
|
118
|
+
throw error('FORM_SUBMISSION_CLAIM_INVALID');
|
|
119
|
+
if(formClaimInFlight.has(req.traceRef))
|
|
120
|
+
throw error('FORM_ALREADY_SUBMITTED');
|
|
121
|
+
formClaimInFlight.add(req.traceRef);
|
|
122
|
+
try{
|
|
123
|
+
if(traceWriter.health().status!=='OK')
|
|
124
|
+
throw error('FORM_SUBMISSION_CLAIM_UNVERIFIED');
|
|
125
|
+
const prior=await usageReader.diagnose({projectRef:'api_system',
|
|
126
|
+
sessionRef:req.traceRef,maxEvents:200});
|
|
127
|
+
const preparations=prior.timeline.filter(event=>
|
|
128
|
+
event.event==='form.prepared.soft_observed');
|
|
129
|
+
if(prior.gaps.some(gap=>gap!=='NO_MATCHING_EVENTS')||!preparations.length)
|
|
130
|
+
throw error('FORM_SUBMISSION_CLAIM_UNVERIFIED');
|
|
131
|
+
if(preparations.some(event=>event.evidenceRef!==req.formId))
|
|
132
|
+
throw error('FORM_TRACE_REF_REUSED');
|
|
133
|
+
const claims=prior.timeline.filter(event=>
|
|
134
|
+
event.event==='form.submission.claimed');
|
|
135
|
+
if(claims.length){
|
|
136
|
+
if(claims.some(event=>event.evidenceRef!==req.formId))
|
|
137
|
+
throw error('FORM_TRACE_REF_REUSED');
|
|
138
|
+
throw error('FORM_ALREADY_SUBMITTED');
|
|
139
|
+
}
|
|
140
|
+
const written=traceWriter.record({
|
|
141
|
+
traceId:req.traceId,parentSpanId:req.spanId,
|
|
142
|
+
projectRef:'api_system',sessionRef:req.traceRef,
|
|
143
|
+
requestId:req.requestId,component:'gateway',
|
|
144
|
+
event:'form.submission.claimed',status:'CONFIRMED',
|
|
145
|
+
evidenceRef:req.formId
|
|
146
|
+
});
|
|
147
|
+
if(!written?.eventId)throw error('FORM_SUBMISSION_CLAIM_UNRECORDED');
|
|
148
|
+
return {contract,requestId:req.requestId,
|
|
149
|
+
status:'FORM_SUBMISSION_CLAIMED',eventId:written.eventId};
|
|
150
|
+
}finally{
|
|
151
|
+
formClaimInFlight.delete(req.traceRef);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return {log,traceHealth,handleTraceObservation,traceNativeReceipt,
|
|
156
|
+
recordApiObservation,apiUsage,claimFormSubmission,flushPending};
|
|
157
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {randomUUID} from 'node:crypto';
|
|
2
|
-
import {createTraceWriter,createTraceReader} from '@tomflow/chatloop-trace';
|
|
3
2
|
import {closeSync, existsSync, openSync, readFileSync, unlinkSync, writeFileSync, chmodSync} from 'node:fs';
|
|
4
3
|
import {createServer} from 'node:net';
|
|
4
|
+
import {createSupervisorObservability} from './supervisor-observability.mjs';
|
|
5
5
|
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
6
6
|
// Private modules never import or resolve another private implementation.
|
|
7
7
|
let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, loadContextControlSecret, handleContextControl;
|
|
@@ -36,118 +36,18 @@ function rememberRequest(id,payload,promise){
|
|
|
36
36
|
if(seen.size>MAX_REPLAY_RESULTS)seen.delete(seen.keys().next().value);
|
|
37
37
|
}
|
|
38
38
|
const p=paths(), nonce=randomUUID();
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
typeof contextUsageGrant==='string'&&
|
|
47
|
-
/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextUsageGrant)
|
|
48
|
-
?[contextUsageGrant]:[])];
|
|
49
|
-
const usageReader=createTraceReader({
|
|
50
|
-
filePath:p.log,allowedProjects:usageScopes
|
|
39
|
+
const error=(code,message=code)=>({code,message});
|
|
40
|
+
const observability=createSupervisorObservability({
|
|
41
|
+
filePath:p.log,
|
|
42
|
+
rotationEnabled:process.env.CHAT_LOOP_TRACE_ROTATE_ENABLE==='1',
|
|
43
|
+
contextUsageGrant:process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS,
|
|
44
|
+
contract:CONTRACT,nonce,processId:process.pid,
|
|
45
|
+
createSupervisorTraceBridge,error
|
|
51
46
|
});
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
// Never accept raw UI text, arguments, URLs or other caller payloads.
|
|
55
|
-
const OBSERVER_NAME=/^(?:mcp|extension|tools|context|trace|tunnel)\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
|
|
56
|
-
const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
|
|
57
|
-
'traceId','spanId','parentSpanId','apiName','phase','durationMs','errorCode',
|
|
58
|
-
'ownerNonce','managerPid']);
|
|
59
|
-
function recordApiObservation(req){
|
|
60
|
-
// Native audit carries its exact Manager lock identity on the same IPC
|
|
61
|
-
// request. The internal Tools producer uses the existing trusted channel.
|
|
62
|
-
if(req?.ownerNonce!==undefined||req?.managerPid!==undefined){
|
|
63
|
-
if(req.ownerNonce!==nonce||req.managerPid!==process.pid)
|
|
64
|
-
throw Object.assign(Error('TRACE_API_OWNER_MISMATCH'),
|
|
65
|
-
{code:'TRACE_API_OWNER_MISMATCH'});
|
|
66
|
-
}
|
|
67
|
-
if(req?.contract!==CONTRACT||!OBSERVER_ID.test(req.requestId||'')||
|
|
68
|
-
!OBSERVER_ID.test(req.callId||'')||
|
|
69
|
-
!OBSERVER_ID.test(req.traceId||'')||
|
|
70
|
-
req.spanId!==req.callId||
|
|
71
|
-
(req.parentSpanId!==undefined&&
|
|
72
|
-
(!OBSERVER_ID.test(req.parentSpanId)||req.parentSpanId===req.spanId))||
|
|
73
|
-
!OBSERVER_NAME.test(req.apiName||'')||
|
|
74
|
-
!['BEGIN','OK','FAILED'].includes(req.phase)||
|
|
75
|
-
Object.keys(req).some(k=>!OBSERVER_KEYS.has(k))||
|
|
76
|
-
(req.phase==='BEGIN'
|
|
77
|
-
?req.durationMs!==undefined||req.errorCode!==undefined
|
|
78
|
-
:!Number.isSafeInteger(req.durationMs)||req.durationMs<0||
|
|
79
|
-
(req.phase==='FAILED'
|
|
80
|
-
?req.errorCode!=='MCP_TOOL_ERROR'&&
|
|
81
|
-
!/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode||'')
|
|
82
|
-
:req.errorCode!==undefined)))
|
|
83
|
-
throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
|
|
84
|
-
const written=traceWriter.record({
|
|
85
|
-
event:'typed.api.call',component:'gateway',projectRef:'api_system',
|
|
86
|
-
traceId:req.traceId,spanId:req.spanId,
|
|
87
|
-
...(req.parentSpanId?{parentSpanId:req.parentSpanId}:{}),
|
|
88
|
-
apiName:req.apiName,
|
|
89
|
-
status:req.phase==='BEGIN'?'BEGIN':req.phase==='OK'?'CONFIRMED':'FAILED',
|
|
90
|
-
...(req.phase!=='BEGIN'?{durationMs:req.durationMs}:{}),
|
|
91
|
-
...(req.phase==='FAILED'?{errorCode:req.errorCode}:{})
|
|
92
|
-
});
|
|
93
|
-
return {contract:CONTRACT,requestId:req.requestId,status:'OK',
|
|
94
|
-
eventId:written.eventId};
|
|
95
|
-
}
|
|
96
|
-
async function apiUsage(req){
|
|
97
|
-
if(req?.contract!==CONTRACT||
|
|
98
|
-
Object.keys(req).some(k=>!['contract','action','requestId',
|
|
99
|
-
'windowMinutes','limit'].includes(k))||
|
|
100
|
-
!OBSERVER_ID.test(req.requestId||''))
|
|
101
|
-
throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
|
|
102
|
-
const summary=await usageReader.apiUsage({
|
|
103
|
-
windowMinutes:req.windowMinutes??60,limit:req.limit??100});
|
|
104
|
-
return {contract:CONTRACT,requestId:req.requestId,status:'OK',summary};
|
|
105
|
-
}
|
|
47
|
+
const {log,traceHealth,handleTraceObservation,traceNativeReceipt,
|
|
48
|
+
recordApiObservation,apiUsage,claimFormSubmission,flushPending}=observability;
|
|
106
49
|
const desiredTunnel=new Set(), recoveryAttempts=new Map();
|
|
107
50
|
let lockFd, server, idleTimer;
|
|
108
|
-
// Internal process/control events never perform disk I/O on a business
|
|
109
|
-
// response path. This queue is bounded, asynchronous, and drops telemetry
|
|
110
|
-
// rather than delaying or replaying a confirmed/unknown operation.
|
|
111
|
-
const MAX_CONTROL_AUDIT=1024,CONTROL_AUDIT_BATCH=64,controlAudit=[];
|
|
112
|
-
let controlAuditScheduled=false,controlAuditDropped=0;
|
|
113
|
-
const flushControlAudit=()=>{
|
|
114
|
-
controlAuditScheduled=false;
|
|
115
|
-
for(let i=0;i<CONTROL_AUDIT_BATCH&&controlAudit.length;i++){
|
|
116
|
-
const {event,detail}=controlAudit.shift();
|
|
117
|
-
try{traceWriter.recordControl(event,detail);}
|
|
118
|
-
catch{/* Writer health carries the last error, never a business error. */}
|
|
119
|
-
}
|
|
120
|
-
if(controlAudit.length){
|
|
121
|
-
controlAuditScheduled=true;setImmediate(flushControlAudit);
|
|
122
|
-
}
|
|
123
|
-
};
|
|
124
|
-
const log=(event,detail={})=>{
|
|
125
|
-
if(controlAudit.length>=MAX_CONTROL_AUDIT){controlAuditDropped++;return}
|
|
126
|
-
// Project only the fields the existing Trace recordControl consumes.
|
|
127
|
-
controlAudit.push({event,detail:{
|
|
128
|
-
status:detail?.status,requestId:detail?.requestId,
|
|
129
|
-
errorCode:detail?.errorCode
|
|
130
|
-
}});
|
|
131
|
-
if(!controlAuditScheduled){
|
|
132
|
-
controlAuditScheduled=true;setImmediate(flushControlAudit);
|
|
133
|
-
}
|
|
134
|
-
};
|
|
135
|
-
const traceHealth=()=>{
|
|
136
|
-
const health=traceWriter.health();
|
|
137
|
-
const writerAuditLost=(health.apiObservation?.dropped||0)>0||
|
|
138
|
-
(health.apiObservation?.sinkFailures||0)>0;
|
|
139
|
-
return {...health,controlAuditDropped,controlAuditPending:controlAudit.length,
|
|
140
|
-
...(writerAuditLost&&health.status==='OK'
|
|
141
|
-
?{status:'TRACE_DEGRADED',errorCode:'TRACE_WRITER_API_LOG_GAP'}:{}),
|
|
142
|
-
...(controlAuditDropped>0&&health.status==='OK'
|
|
143
|
-
?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
|
|
144
|
-
};
|
|
145
|
-
const error=(code,message=code)=>({code,message});
|
|
146
|
-
// One Trace owner; this module only handles native/soft event admission.
|
|
147
|
-
const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
|
|
148
|
-
traceWriter,contract:CONTRACT,error
|
|
149
|
-
});
|
|
150
|
-
|
|
151
51
|
const after=rec=>rec ? rec.state : 'STOPPED';
|
|
152
52
|
function saveReceipt(id,state,result=null,errorCode=null){
|
|
153
53
|
receipts.delete(id);
|
|
@@ -298,7 +198,7 @@ async function execute(req){
|
|
|
298
198
|
async function shutdown(){
|
|
299
199
|
if([...records.values()].some(r=>!r.exited))return;
|
|
300
200
|
// Closeout may flush final soft evidence, but never re-authorizes an action.
|
|
301
|
-
|
|
201
|
+
flushPending();
|
|
302
202
|
server?.close();
|
|
303
203
|
try{if(existsSync(p.socket))unlinkSync(p.socket);}catch{}
|
|
304
204
|
try{if(existsSync(p.lock) && JSON.parse(readFileSync(p.lock,'utf8')).nonce===nonce)unlinkSync(p.lock);}catch{}
|
|
@@ -344,6 +244,9 @@ async function main(){
|
|
|
344
244
|
:req?.action==='__api_usage'
|
|
345
245
|
?Promise.resolve().then(()=>apiUsage(req))
|
|
346
246
|
.catch(e=>bad(req,e.code||'TRACE_USAGE_FAILED'))
|
|
247
|
+
:req?.action==='__form_submission_claim'
|
|
248
|
+
?Promise.resolve().then(()=>claimFormSubmission(req))
|
|
249
|
+
.catch(e=>bad(req,e.code||'FORM_SUBMISSION_CLAIM_FAILED'))
|
|
347
250
|
:req?.action==='context-control'
|
|
348
251
|
?handleContextControl(req).then(result=>{
|
|
349
252
|
traceNativeReceipt(req);
|
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
|
|
27
|
+
description:'Read-only Trace timeline for an explicitly authorized Project. A separate api_system lookup is allowed only with the unguessable form traceRef returned by Form Prepare, and exposes only that form plus its parent MCP API spans.',
|
|
28
28
|
inputSchema:{
|
|
29
29
|
type:'object',additionalProperties:false,
|
|
30
30
|
required:['projectRef'],
|
|
@@ -43,6 +43,10 @@ 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 FORM_TRACE_REF=new RegExp(UUID);
|
|
47
|
+
const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
48
|
+
const FORM_EVENT=/^form\.(?:prepared|submitted)\.(?:soft_observed|failed)$|^form\.submission\.claimed$/;
|
|
49
|
+
const FORM_APIS=new Set(['mcp.chat_loop_form__prepare','mcp.chat_loop_form__submit']);
|
|
46
50
|
export const traceStageTool={
|
|
47
51
|
name:'chat_loop_trace_stage',
|
|
48
52
|
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.',
|
|
@@ -94,29 +98,104 @@ const getAllowedProjects=()=>{
|
|
|
94
98
|
// syntax; filtering entries could silently broaden a malformed config.
|
|
95
99
|
return entries.length===1&&PROJECT.test(entries[0])?entries:[];
|
|
96
100
|
};
|
|
101
|
+
async function diagnoseFormTrace(args){
|
|
102
|
+
const reader=createTraceReader({filePath:paths().log,allowedProjects:['api_system']});
|
|
103
|
+
const base=await reader.diagnose({projectRef:'api_system',
|
|
104
|
+
sessionRef:args.sessionRef,maxEvents:args.maxEvents});
|
|
105
|
+
const formEvents=base.timeline.filter(event=>
|
|
106
|
+
event.sessionRef===args.sessionRef&&FORM_EVENT.test(event.event||'')
|
|
107
|
+
&&typeof event.evidenceRef==='string'&&FORM_ID.test(event.evidenceRef));
|
|
108
|
+
const gaps=base.gaps.filter(gap=>gap!=='NO_MATCHING_EVENTS');
|
|
109
|
+
const parentKeys=new Map();
|
|
110
|
+
for(const event of formEvents){
|
|
111
|
+
const apiName=event.event==='form.prepared.soft_observed'
|
|
112
|
+
||event.event==='form.prepared.failed'
|
|
113
|
+
?'mcp.chat_loop_form__prepare':'mcp.chat_loop_form__submit';
|
|
114
|
+
if(!event.parentSpanId){gaps.push('FORM_API_PARENT_MISSING');continue}
|
|
115
|
+
parentKeys.set(event.traceId+':'+event.parentSpanId,apiName);
|
|
116
|
+
}
|
|
117
|
+
const apiEvents=[];
|
|
118
|
+
for(const traceId of new Set(formEvents.map(event=>event.traceId))){
|
|
119
|
+
const query=await reader.diagnose({projectRef:'api_system',traceId,maxEvents:200});
|
|
120
|
+
for(const gap of query.gaps)
|
|
121
|
+
if(['TRACE_MALFORMED_LINES','TRACE_WINDOW_TRUNCATED',
|
|
122
|
+
'TRACE_WRITER_RESTART_UNVERIFIED','LEGACY_EVENTS_UNCORRELATED']
|
|
123
|
+
.includes(gap))gaps.push(gap);
|
|
124
|
+
for(const event of query.timeline){
|
|
125
|
+
const key=event.traceId+':'+event.spanId;
|
|
126
|
+
if(event.event==='typed.api.call'&&parentKeys.get(key)===event.apiName
|
|
127
|
+
&&FORM_APIS.has(event.apiName))apiEvents.push(event);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
for(const [key,apiName] of parentKeys){
|
|
131
|
+
const [traceId,spanId]=key.split(':');
|
|
132
|
+
const linked=apiEvents.filter(event=>event.traceId===traceId
|
|
133
|
+
&&event.spanId===spanId&&event.apiName===apiName);
|
|
134
|
+
const begins=linked.filter(event=>event.status==='BEGIN');
|
|
135
|
+
const terminals=linked.filter(event=>
|
|
136
|
+
['CONFIRMED','FAILED'].includes(event.status));
|
|
137
|
+
if(begins.length!==1||terminals.length!==1)
|
|
138
|
+
gaps.push('FORM_API_PARENT_GAP');
|
|
139
|
+
const terminal=terminals[0];
|
|
140
|
+
if(terminal&&formEvents.some(event=>event.traceId===traceId
|
|
141
|
+
&&event.parentSpanId===spanId&&event.status!==terminal.status))
|
|
142
|
+
gaps.push('FORM_API_STATUS_MISMATCH');
|
|
143
|
+
}
|
|
144
|
+
const formIds=[...new Set(formEvents.map(event=>event.evidenceRef))];
|
|
145
|
+
if(formIds.length>1)gaps.push('FORM_TRACE_REF_REUSED');
|
|
146
|
+
if(!formEvents.length)gaps.push('NO_MATCHING_EVENTS');
|
|
147
|
+
const timeline=[...formEvents,...apiEvents]
|
|
148
|
+
.sort((a,b)=>Date.parse(a.time)-Date.parse(b.time));
|
|
149
|
+
const last=timeline.at(-1)||null;
|
|
150
|
+
const unknown=formEvents.some(event=>['UNKNOWN','BLOCKED'].includes(event.status));
|
|
151
|
+
return {traceId:null,projectRef:'api_system',formTraceRef:args.sessionRef,
|
|
152
|
+
formId:formIds.length===1?formIds[0]:null,
|
|
153
|
+
inspected:timeline.length,totalMatched:timeline.length,
|
|
154
|
+
lastConfirmed:[...timeline].reverse().find(event=>event.status==='CONFIRMED')
|
|
155
|
+
?{eventId:[...timeline].reverse().find(event=>event.status==='CONFIRMED').eventId,
|
|
156
|
+
event:[...timeline].reverse().find(event=>event.status==='CONFIRMED').event,
|
|
157
|
+
time:[...timeline].reverse().find(event=>event.status==='CONFIRMED').time,
|
|
158
|
+
component:[...timeline].reverse().find(event=>event.status==='CONFIRMED').component}
|
|
159
|
+
:null,
|
|
160
|
+
incompleteApiSpans:[],unmatchedApiTerminals:[],lastEvent:last,unknown,
|
|
161
|
+
gaps:[...new Set(gaps)],confidence:gaps.length?'INCOMPLETE':'TRACE_ONLY',
|
|
162
|
+
retryDisposition:unknown||gaps.length
|
|
163
|
+
?'VERIFY_AUTHORITATIVE_RECEIPT_FIRST':'NO_AUTOMATIC_RETRY',timeline};
|
|
164
|
+
}
|
|
97
165
|
export async function runTraceDiagnose(args){
|
|
98
|
-
if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
|
|
99
166
|
if(!args||typeof args!=='object'||Array.isArray(args)||
|
|
100
167
|
Object.keys(args).some(k=>!Object.hasOwn(traceDiagnoseTool.inputSchema.properties,k)))
|
|
101
168
|
throw fail('TRACE_INVALID_ARGUMENT');
|
|
102
|
-
if(
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
}
|
|
169
|
+
if(args.projectRef==='api_system'){
|
|
170
|
+
if(args.traceId!==undefined||typeof args.sessionRef!=='string'
|
|
171
|
+
||!FORM_TRACE_REF.test(args.sessionRef))
|
|
172
|
+
throw fail('TRACE_FORM_LOOKUP_INVALID');
|
|
173
|
+
}else{
|
|
174
|
+
if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
|
|
175
|
+
if(typeof args.projectRef!=='string'||!getAllowedProjects().includes(args.projectRef))
|
|
176
|
+
throw fail('TRACE_PROJECT_ACCESS_DENIED');
|
|
177
|
+
}
|
|
178
|
+
const result=args.projectRef==='api_system'
|
|
179
|
+
?await diagnoseFormTrace(args)
|
|
180
|
+
:await createTraceReader({filePath:paths().log,
|
|
181
|
+
allowedProjects:getAllowedProjects()}).diagnose(args);
|
|
107
182
|
try{
|
|
108
183
|
const response=await talk({contract:CONTRACT,action:'__trace_health',
|
|
109
184
|
requestId:randomUUID()},1400);
|
|
110
185
|
result.writerHealth=response.status==='OK'?response.traceHealth?.status||'UNKNOWN':'UNAVAILABLE';
|
|
186
|
+
if(args.projectRef==='api_system'&&response.traceHealth?.formObservationLost>0)
|
|
187
|
+
result.gaps.push('FORM_TRACE_OBSERVATION_LOSS');
|
|
111
188
|
}catch{result.writerHealth='UNAVAILABLE'}
|
|
112
189
|
if(result.writerHealth!=='OK'){
|
|
113
|
-
|
|
190
|
+
if(['UNKNOWN','UNAVAILABLE'].includes(result.writerHealth))
|
|
191
|
+
result.gaps.push('TRACE_WRITER_UNAVAILABLE');
|
|
192
|
+
if(result.writerHealth==='TRACE_DEGRADED')
|
|
193
|
+
result.gaps.push('FORM_TRACE_OBSERVATION_LOSS');
|
|
114
194
|
result.confidence='INCOMPLETE';
|
|
115
|
-
// An offline / unhealthy writer invalidates any claim that the visible
|
|
116
|
-
// timeline is complete, even when every retained event is CONFIRMED.
|
|
117
|
-
// Only the original authoritative receipt can settle an unknown effect.
|
|
118
195
|
result.retryDisposition='VERIFY_AUTHORITATIVE_RECEIPT_FIRST';
|
|
119
196
|
}
|
|
197
|
+
result.gaps=[...new Set(result.gaps)];
|
|
198
|
+
if(result.gaps.length)result.confidence='INCOMPLETE';
|
|
120
199
|
return result;
|
|
121
200
|
}
|
|
122
201
|
|
|
@@ -16,12 +16,17 @@ export function createSupervisorTraceBridge({traceWriter,contract,error}){
|
|
|
16
16
|
// grant. Public Trace MCP observation/diagnosis remains opt-in and does
|
|
17
17
|
// not become reachable merely because Context collection is active.
|
|
18
18
|
const isContextApi=req?.event==='context.api';
|
|
19
|
+
const form=/^form\.(prepared|submitted)\.(soft_observed|failed)$/.test(req?.event||'');
|
|
19
20
|
const contextGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
|
|
20
21
|
const contextAuthorized=process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
|
|
21
22
|
&&typeof contextGrant==='string'
|
|
22
23
|
&&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextGrant)
|
|
23
24
|
&&req?.projectRef===contextGrant;
|
|
25
|
+
// Form IDs are system-local correlation metadata, not user Project data.
|
|
26
|
+
// Keep them in the existing api_system Writer without requiring a
|
|
27
|
+
// per-Project Trace grant or exposing Project/Chat/task identifiers.
|
|
24
28
|
if(isContextApi?!contextAuthorized:
|
|
29
|
+
form?req?.projectRef!=='api_system':
|
|
25
30
|
!traceEnabled()||!allowedTraceProjects().has(req?.projectRef))
|
|
26
31
|
throw error('TRACE_PROJECT_ACCESS_DENIED');
|
|
27
32
|
// Context call observation has a stable event ID and typed API fields.
|
|
@@ -67,21 +72,25 @@ export function createSupervisorTraceBridge({traceWriter,contract,error}){
|
|
|
67
72
|
return {contract:CONTRACT,requestId:req.requestId,status:'OK',
|
|
68
73
|
eventId:recorded.eventId};
|
|
69
74
|
}
|
|
70
|
-
const form=/^form\.(prepared|submitted)\.soft_observed$/.test(req?.event||'');
|
|
71
75
|
if(form){
|
|
76
|
+
const success=req.event.endsWith('.soft_observed');
|
|
72
77
|
const allowed=new Set(['contract','action','requestId','traceId','spanId',
|
|
73
|
-
'projectRef','
|
|
74
|
-
|
|
78
|
+
'projectRef','sessionRef','evidenceRef','event','status','errorCode']);
|
|
79
|
+
const validError=typeof req.errorCode==='string'
|
|
80
|
+
&&/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode);
|
|
81
|
+
if(req.contract!==CONTRACT||req.projectRef!=='api_system'
|
|
82
|
+
||req.status!==(success?'CONFIRMED':'FAILED')
|
|
75
83
|
||!UUID_RE.test(req.requestId||'')||!UUID_RE.test(req.traceId||'')
|
|
76
84
|
||!UUID_RE.test(req.spanId||'')
|
|
77
|
-
||!
|
|
78
|
-
|
|
85
|
+
||!UUID_RE.test(req.sessionRef||'')
|
|
86
|
+
||!(/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/).test(req.evidenceRef||'')
|
|
87
|
+
||(success?req.errorCode!==undefined:!validError)
|
|
79
88
|
||Object.keys(req).some(k=>!allowed.has(k)))
|
|
80
89
|
throw error('TRACE_INVALID_ARGUMENT');
|
|
81
90
|
const written=traceWriter.record({traceId:req.traceId,
|
|
82
|
-
parentSpanId:req.spanId,
|
|
83
|
-
|
|
84
|
-
|
|
91
|
+
parentSpanId:req.spanId,sessionRef:req.sessionRef,projectRef:'api_system',
|
|
92
|
+
requestId:req.requestId,component:'gateway',event:req.event,
|
|
93
|
+
status:req.status,...(req.errorCode?{errorCode:req.errorCode}:{}),
|
|
85
94
|
evidenceRef:req.evidenceRef});
|
|
86
95
|
return {contract:CONTRACT,requestId:req.requestId,status:'OK',
|
|
87
96
|
eventId:written.eventId};
|
package/package.json
CHANGED
package/providers/form.mjs
CHANGED
|
@@ -1,19 +1,13 @@
|
|
|
1
|
-
//
|
|
2
|
-
// Form IDs identify interactions; Context Issue IDs own R/P decisions.
|
|
1
|
+
// Generic ChatGPT A/B form interaction service; business meaning belongs to callers.
|
|
3
2
|
import {randomUUID} from 'node:crypto';
|
|
4
3
|
import {readFileSync} from 'node:fs';
|
|
5
4
|
const RESOURCE_URI='ui://chat-loop/form/review-v2';
|
|
6
|
-
//
|
|
7
|
-
// Preserve their resource locator; both URIs serve the same audited UI.
|
|
5
|
+
// Preserve the legacy resource locator; both URIs serve the same audited UI.
|
|
8
6
|
const LEGACY_RESOURCE_URI='ui://chat-loop/form/review-v1';
|
|
9
7
|
const RESOURCE_MIME='text/html;profile=mcp-app';
|
|
10
|
-
const
|
|
11
|
-
const FORM_ID=/^[A-Za-z0-9_-]{8,80}$/;
|
|
8
|
+
const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
12
9
|
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;
|
|
13
|
-
const ISSUE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
14
|
-
const HASH=/^[a-f0-9]{64}$/;
|
|
15
10
|
const fail=code=>Object.assign(Error(code),{code});
|
|
16
|
-
const err=code=>({isError:true,content:[{type:'text',text:code}]});
|
|
17
11
|
const ok=value=>({content:[{type:'text',text:JSON.stringify(value)}],
|
|
18
12
|
structuredContent:value});
|
|
19
13
|
const filled=(s,max)=>typeof s==='string'&&s.trim().length>0&&s.length<=max;
|
|
@@ -21,70 +15,34 @@ const shape=(v,fields)=>v&&typeof v==='object'&&!Array.isArray(v)
|
|
|
21
15
|
&&Object.keys(v).every(k=>fields.includes(k));
|
|
22
16
|
const CARD=['title','description','confirmLabel','modifyLabel',
|
|
23
17
|
'modifyPlaceholder','submitLabel','footer'];
|
|
24
|
-
const PREP=['
|
|
25
|
-
|
|
26
|
-
'writeRequestId','card'];
|
|
27
|
-
const SUBMIT=['mode','formId','issueId','projectId','taskId','chatRef','kind',
|
|
28
|
-
'documentId','version','choice','comment','userTurn','presentedAssistantRef',
|
|
29
|
-
'expectedTaskRevision','expectedStoreEpoch','writeRequestId'];
|
|
30
|
-
const common={
|
|
31
|
-
mode:{type:'string',enum:['GENERAL','TEST_ONLY','MANAGED']},
|
|
32
|
-
formId:{type:'string',pattern:FORM_ID.source},projectId:{type:'string',pattern:ID.source},
|
|
33
|
-
taskId:{type:'string',pattern:ID.source},
|
|
34
|
-
chatRef:{type:'string',minLength:8,maxLength:256},
|
|
35
|
-
kind:{type:'string',enum:['R','P','CUSTOM']},
|
|
36
|
-
documentId:{type:'string',pattern:ID.source},
|
|
37
|
-
version:{type:'integer',minimum:1},
|
|
38
|
-
expectedTaskRevision:{type:'integer',minimum:1},
|
|
39
|
-
expectedStoreEpoch:{type:'string',minLength:10,maxLength:64},
|
|
40
|
-
writeRequestId:{type:'string',minLength:8,maxLength:128}
|
|
41
|
-
};
|
|
18
|
+
const PREP=['formId','card'];
|
|
19
|
+
const SUBMIT=['formId','traceRef','choice','comment'];
|
|
42
20
|
const cardSchema={type:'object',additionalProperties:false,required:CARD,
|
|
43
21
|
properties:Object.fromEntries(CARD.map(key=>[key,{type:'string',minLength:1,
|
|
44
22
|
maxLength:['description','footer'].includes(key)?1200:180}]))};
|
|
45
23
|
const tools=[
|
|
46
24
|
{name:'chat_loop_form__prepare',description:
|
|
47
|
-
'
|
|
48
|
-
inputSchema:{type:'object',additionalProperties:false,
|
|
49
|
-
|
|
50
|
-
properties:{...common,contentHash:{type:'string',pattern:HASH.source},
|
|
51
|
-
card:cardSchema}},
|
|
25
|
+
'Render a reusable A/B form. Preserve the optional caller-supplied formId or generate a UUID; also return an opaque traceRef for correlation and one-time submission protection. No business workflow or approval state is owned here.',
|
|
26
|
+
inputSchema:{type:'object',additionalProperties:false,required:['card'],
|
|
27
|
+
properties:{formId:{type:'string',pattern:FORM_ID.source},card:cardSchema}},
|
|
52
28
|
annotations:{readOnlyHint:false},
|
|
53
29
|
_meta:{ui:{resourceUri:RESOURCE_URI,visibility:['model','app']},
|
|
54
30
|
'openai/outputTemplate':RESOURCE_URI,'openai/widgetAccessible':true}},
|
|
55
31
|
{name:'chat_loop_form__submit',description:
|
|
56
|
-
'
|
|
32
|
+
'Receive the selected A/B option and optional comment for a prepared form. Requires its formId and opaque traceRef; the shared Supervisor claims the traceRef once before the app may request a user message. The caller owns all business interpretation and follow-up.',
|
|
57
33
|
inputSchema:{type:'object',additionalProperties:false,
|
|
58
|
-
required:['
|
|
59
|
-
properties:{
|
|
34
|
+
required:['formId','traceRef','choice'],
|
|
35
|
+
properties:{formId:{type:'string',pattern:FORM_ID.source},
|
|
36
|
+
traceRef:{type:'string',pattern:UUID.source},
|
|
60
37
|
choice:{type:'string',enum:['A','B']},
|
|
61
|
-
comment:{type:'string',maxLength:4000},
|
|
62
|
-
userTurn:{type:'string',minLength:8,maxLength:256},
|
|
63
|
-
presentedAssistantRef:{type:'string',minLength:8,maxLength:256}}},
|
|
38
|
+
comment:{type:'string',maxLength:4000}}},
|
|
64
39
|
annotations:{readOnlyHint:false},
|
|
65
|
-
_meta:{ui:{visibility:['model','app']},
|
|
66
|
-
'openai/widgetAccessible':true}}
|
|
40
|
+
_meta:{ui:{visibility:['model','app']},'openai/widgetAccessible':true}}
|
|
67
41
|
];
|
|
68
42
|
function check(a,fields){
|
|
69
|
-
if(!shape(a,fields)
|
|
70
|
-
||a.formId!==undefined
|
|
71
|
-
||a.projectId!==undefined&&!ID.test(a.projectId)
|
|
72
|
-
||a.documentId!==undefined&&!ID.test(a.documentId)
|
|
73
|
-
||a.version!==undefined&&(!Number.isSafeInteger(a.version)||a.version<1)
|
|
74
|
-
||a.kind!==undefined&&!['R','P','CUSTOM'].includes(a.kind))
|
|
43
|
+
if(!shape(a,fields)
|
|
44
|
+
||a.formId!==undefined&&(typeof a.formId!=='string'||!FORM_ID.test(a.formId)))
|
|
75
45
|
throw fail('FORM_INVALID_ARGUMENT');
|
|
76
|
-
if(['R','P'].includes(a.kind)&&(!ID.test(a.documentId||'')
|
|
77
|
-
||!Number.isSafeInteger(a.version)))throw fail('FORM_REVIEW_SCOPE_REQUIRED');
|
|
78
|
-
if(a.mode!=='GENERAL'&&(!ID.test(a.projectId||'')
|
|
79
|
-
||!ID.test(a.documentId||'')||!Number.isSafeInteger(a.version)
|
|
80
|
-
||!['R','P'].includes(a.kind)))throw fail('FORM_REVIEW_SCOPE_REQUIRED');
|
|
81
|
-
if(a.mode==='TEST_ONLY'&&(!filled(a.chatRef,256)||a.chatRef.length<8))
|
|
82
|
-
throw fail('FORM_TEST_CHAT_REQUIRED');
|
|
83
|
-
if(a.mode==='MANAGED'&&(!ID.test(a.taskId||'')
|
|
84
|
-
||!Number.isSafeInteger(a.expectedTaskRevision)
|
|
85
|
-
||a.expectedTaskRevision<1||!filled(a.expectedStoreEpoch,64)
|
|
86
|
-
||!filled(a.writeRequestId,128)))
|
|
87
|
-
throw fail('FORM_MANAGED_SCOPE_REQUIRED');
|
|
88
46
|
}
|
|
89
47
|
function checkCard(a){
|
|
90
48
|
if(!shape(a.card,CARD)||CARD.some(x=>!Object.hasOwn(a.card,x)))
|
|
@@ -94,21 +52,14 @@ function checkCard(a){
|
|
|
94
52
|
throw fail('FORM_CARD_INVALID');
|
|
95
53
|
}
|
|
96
54
|
if(!/^A\s*[—-]/.test(a.card.confirmLabel)
|
|
97
|
-
||!/^B\s*[—-]/.test(a.card.modifyLabel)
|
|
98
|
-
||a.kind==='R'&&a.card.submitLabel!=='提交需求评审'
|
|
99
|
-
||a.kind==='P'&&a.card.submitLabel!=='提交方案评审')
|
|
55
|
+
||!/^B\s*[—-]/.test(a.card.modifyLabel))
|
|
100
56
|
throw fail('FORM_CARD_LAYOUT_INVALID');
|
|
101
57
|
}
|
|
102
|
-
function view(a,formId
|
|
103
|
-
|
|
104
|
-
return {template:'chat-loop-review-card-v1',formId,mode:a.mode,
|
|
58
|
+
function view(a,formId){
|
|
59
|
+
return {template:'chat-loop-review-card-v1',formId,
|
|
105
60
|
layout:{card:'rounded-border',radiusPx:12,paddingPx:12,gapPx:12,
|
|
106
61
|
direction:'column',optionDirection:'column',buttonWidth:'full',
|
|
107
62
|
buttonShape:'pill'},
|
|
108
|
-
badges:review
|
|
109
|
-
?[...(prior?[{text:prior+' SUPERSEDED'}]:[]),
|
|
110
|
-
{text:a.documentId+' CURRENT'},{text:'WAITING_APPROVAL'}]
|
|
111
|
-
:[{text:'WAITING_INPUT'}],
|
|
112
63
|
title:a.card.title,description:a.card.description,
|
|
113
64
|
options:[{value:'A',label:a.card.confirmLabel},
|
|
114
65
|
{value:'B',label:a.card.modifyLabel}],
|
|
@@ -116,121 +67,78 @@ function view(a,formId,issueId,prior){
|
|
|
116
67
|
placeholder:a.card.modifyPlaceholder},
|
|
117
68
|
submit:{label:a.card.submitLabel,disabledInitially:true,
|
|
118
69
|
singleClickLock:true,issueNewUserTurn:true},
|
|
119
|
-
footer:a.card.footer
|
|
120
|
-
...(review?{documentId:a.documentId,version:a.version}:{}),
|
|
121
|
-
authority:issueId?'CONTEXT_ISSUE':'NONE'};
|
|
70
|
+
footer:a.card.footer};
|
|
122
71
|
}
|
|
123
72
|
function trace(form){
|
|
124
73
|
const parent=form?.current?.();
|
|
125
74
|
return parent&&UUID.test(parent.traceId||'')&&UUID.test(parent.spanId||'')
|
|
126
75
|
?{traceId:parent.traceId,spanId:parent.spanId}:null;
|
|
127
76
|
}
|
|
128
|
-
function
|
|
129
|
-
if(
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
77
|
+
async function observeForm(form,event,formId,traceRef,parent,status='CONFIRMED',errorCode){
|
|
78
|
+
if(typeof form?.observe!=='function'||!FORM_ID.test(formId||'')
|
|
79
|
+
||!UUID.test(traceRef||''))return false;
|
|
80
|
+
if(!parent){
|
|
81
|
+
form?.lost?.();
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
try{
|
|
85
|
+
const result=await form.observe({
|
|
86
|
+
event,formId,traceRef,status,...(errorCode?{errorCode}:{}),...parent
|
|
87
|
+
});
|
|
88
|
+
if(result?.status!=='OK'||!UUID.test(result.eventId||'')){
|
|
89
|
+
form?.lost?.();
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
return true;
|
|
93
|
+
}catch{
|
|
94
|
+
form?.lost?.();
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
135
97
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
view:view(a,formId,null,a.kind!=='CUSTOM'&&a.version>1
|
|
146
|
-
?a.documentId[0]+(a.version-1):null),
|
|
147
|
-
trace:trace(form),approvalAuthority:'NONE',businessSideEffects:false,
|
|
148
|
-
provenance:'FORM_ID_ONLY_NO_DURABLE_ISSUE'};
|
|
98
|
+
function prepare(a){
|
|
99
|
+
const formId=a?.formId===undefined?randomUUID():a.formId;
|
|
100
|
+
const traceRef=randomUUID();
|
|
101
|
+
try{check(a,PREP);checkCard(a)}
|
|
102
|
+
catch(error){
|
|
103
|
+
error.formId=typeof formId==='string'&&FORM_ID.test(formId)
|
|
104
|
+
?formId:randomUUID();
|
|
105
|
+
error.traceRef=traceRef;
|
|
106
|
+
throw error;
|
|
149
107
|
}
|
|
150
|
-
|
|
151
|
-
contextAccess(context);
|
|
152
|
-
const doc=await request(context,'get',{operation:'document.get',projectId:a.projectId,
|
|
153
|
-
taskId:a.taskId,documentId:a.documentId,version:a.version});
|
|
154
|
-
if(doc?.kind!==a.kind||doc?.contentHash!==a.contentHash)
|
|
155
|
-
throw fail('FORM_DOCUMENT_MISMATCH');
|
|
156
|
-
const list=await request(context,'get',{operation:'document.list',
|
|
157
|
-
projectId:a.projectId,taskId:a.taskId});
|
|
158
|
-
const prior=Array.isArray(list)&&list.some(x=>x.kind===a.kind&&
|
|
159
|
-
x.version===a.version-1&&x.documentId===a.documentId[0]+(a.version-1))
|
|
160
|
-
?a.documentId[0]+(a.version-1):null;
|
|
161
|
-
const issue=await request(context,'mutate',{operation:'document.prepareIssue',
|
|
162
|
-
projectId:a.projectId,taskId:a.taskId,documentId:a.documentId,
|
|
163
|
-
version:a.version,contentHash:a.contentHash,
|
|
164
|
-
expectedTaskRevision:a.expectedTaskRevision,
|
|
165
|
-
expectedStoreEpoch:a.expectedStoreEpoch,writeRequestId:a.writeRequestId});
|
|
166
|
-
if(issue?.status!=='ISSUE_PENDING'||!ISSUE.test(issue.issueId||''))
|
|
167
|
-
throw fail('FORM_ISSUE_RECEIPT_INVALID');
|
|
168
|
-
// Reuse the durable Issue identity by default to keep MANAGED retries stable;
|
|
169
|
-
// a caller-supplied formId is a separate non-authoritative UI correlation ID.
|
|
170
|
-
const managedFormId=a.formId||issue.issueId;
|
|
171
|
-
return {status:'WAITING_APPROVAL',formId:managedFormId,issueId:issue.issueId,
|
|
172
|
-
mode:a.mode,projectId:a.projectId,taskId:a.taskId,
|
|
173
|
-
documentId:a.documentId,version:a.version,kind:a.kind,
|
|
174
|
-
taskRevision:issue.taskRevision,approvalRevision:issue.approvalRevision,
|
|
175
|
-
writeRequestId:a.writeRequestId,trace:trace(form),
|
|
176
|
-
view:view(a,managedFormId,issue.issueId,prior),approvalAuthority:'CONTEXT',
|
|
177
|
-
businessSideEffects:true};
|
|
108
|
+
return {status:'FORM_PREPARED',formId,traceRef,view:view(a,formId)};
|
|
178
109
|
}
|
|
179
110
|
function validateSubmit(a){
|
|
180
111
|
check(a,SUBMIT);
|
|
181
|
-
if(
|
|
182
|
-
|
|
183
|
-
||!
|
|
112
|
+
if(typeof a.formId!=='string'||!FORM_ID.test(a.formId)
|
|
113
|
+
||typeof a.traceRef!=='string'||!UUID.test(a.traceRef)
|
|
114
|
+
||!['A','B'].includes(a.choice))
|
|
184
115
|
throw fail('FORM_SUBMISSION_INVALID');
|
|
185
116
|
if(a.choice==='B'&&!filled(a.comment,4000)
|
|
186
117
|
||a.choice==='A'&&a.comment!==undefined&&a.comment!=='')
|
|
187
118
|
throw fail('FORM_COMMENT_INVALID');
|
|
188
|
-
if(a.mode==='MANAGED'&&!ISSUE.test(a.issueId||''))
|
|
189
|
-
throw fail('FORM_ISSUE_REF_REQUIRED');
|
|
190
119
|
}
|
|
191
|
-
async function submit(a,
|
|
120
|
+
async function submit(a,form){
|
|
192
121
|
validateSubmit(a);
|
|
193
|
-
if(
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
projectId:a.projectId,taskId:a.taskId,issueId:a.issueId,
|
|
203
|
-
decision:a.choice==='A'?'APPROVE':'REQUEST_CHANGE',
|
|
204
|
-
sourceRole:'user',userTurn:a.userTurn,
|
|
205
|
-
presentedAssistantRef:a.presentedAssistantRef,
|
|
206
|
-
expectedTaskRevision:a.expectedTaskRevision,
|
|
207
|
-
expectedStoreEpoch:a.expectedStoreEpoch,writeRequestId:a.writeRequestId});
|
|
208
|
-
if(!['APPROVED_SOFT','CHANGE_REQUESTED'].includes(result?.status))
|
|
209
|
-
throw fail('FORM_APPROVAL_RECEIPT_INVALID');
|
|
210
|
-
return {status:result.status,formId:a.formId,issueId:a.issueId,
|
|
211
|
-
kind:result.kind,choice:a.choice,taskRevision:result.taskRevision,
|
|
212
|
-
...(result.approvalRevision?{approvalRevision:result.approvalRevision}:{}),
|
|
213
|
-
writeRequestId:a.writeRequestId,trace:trace(form),
|
|
214
|
-
approvalAuthority:'CONTEXT',proofLevel:'SOFT_USER_TURN',
|
|
215
|
-
formIssueBinding:'CALLER_ASSERTED_UNVERIFIED',
|
|
216
|
-
platformProvenance:'AGENT_ASSERTED_UNVERIFIED'};
|
|
122
|
+
if(typeof form?.claimSubmission!=='function')
|
|
123
|
+
throw fail('FORM_SUBMISSION_CLAIM_UNAVAILABLE');
|
|
124
|
+
let claim;
|
|
125
|
+
try{claim=await form.claimSubmission({formId:a.formId,traceRef:a.traceRef})}
|
|
126
|
+
catch(error){throw fail(error?.code||'FORM_SUBMISSION_CLAIM_UNKNOWN')}
|
|
127
|
+
if(claim?.status!=='FORM_SUBMISSION_CLAIMED')
|
|
128
|
+
throw fail(claim?.error?.code||'FORM_SUBMISSION_CLAIM_UNKNOWN');
|
|
129
|
+
return {status:'FORM_SUBMITTED',formId:a.formId,traceRef:a.traceRef,
|
|
130
|
+
choice:a.choice,...(a.comment?{comment:a.comment}:{})};
|
|
217
131
|
}
|
|
218
132
|
export const provider=Object.freeze({
|
|
219
133
|
id:'form',order:5,names:tools.map(x=>x.name),
|
|
220
|
-
create({
|
|
221
|
-
//
|
|
222
|
-
//
|
|
223
|
-
const forms=new Map(),TTL=30*60*1000;
|
|
224
|
-
const lookup=id=>{
|
|
225
|
-
const record=forms.get(id);
|
|
226
|
-
if(!record||Date.now()-record.at>TTL){forms.delete(id);return null}
|
|
227
|
-
return record;
|
|
228
|
-
};
|
|
134
|
+
create({form}={}){
|
|
135
|
+
// Pure interaction adapter: no caller identity, business Context, form
|
|
136
|
+
// registry, expiry, capacity limit, or process-local lifecycle state.
|
|
229
137
|
return Object.freeze({
|
|
230
138
|
tools:()=>tools,
|
|
231
139
|
resources:()=>[RESOURCE_URI,LEGACY_RESOURCE_URI].map(uri=>({
|
|
232
|
-
uri,name:'Chat Loop
|
|
233
|
-
description:'A/B
|
|
140
|
+
uri,name:'Chat Loop Form',mimeType:RESOURCE_MIME,
|
|
141
|
+
description:'Reusable A/B form UI'
|
|
234
142
|
})),
|
|
235
143
|
async readResource(uri){
|
|
236
144
|
if(uri!==RESOURCE_URI&&uri!==LEGACY_RESOURCE_URI)
|
|
@@ -241,53 +149,24 @@ export const provider=Object.freeze({
|
|
|
241
149
|
preferredDisplayMode:'inline'}}}]};
|
|
242
150
|
},
|
|
243
151
|
async call(name,args){
|
|
152
|
+
const isPrepare=name===tools[0].name;
|
|
153
|
+
const isSubmit=name===tools[1].name;
|
|
154
|
+
if(!isPrepare&&!isSubmit)throw fail('UNKNOWN_TOOL');
|
|
155
|
+
const parent=trace(form);
|
|
156
|
+
const formId=typeof args?.formId==='string'?args.formId:null;
|
|
157
|
+
const traceRef=typeof args?.traceRef==='string'?args.traceRef:null;
|
|
244
158
|
try{
|
|
245
|
-
const isPrepare
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
if(prior.args[key]!==args?.[key]&&(
|
|
257
|
-
prior.args[key]!==undefined||args?.[key]!==undefined))
|
|
258
|
-
throw fail('FORM_SCOPE_MISMATCH');
|
|
259
|
-
}
|
|
260
|
-
// Mark before async Context call. UNKNOWN is never retried with
|
|
261
|
-
// a different request ID; the real Context receipt remains owner.
|
|
262
|
-
prior.submitted=true;
|
|
263
|
-
}
|
|
264
|
-
const result=isPrepare?await prepare(args,context,form)
|
|
265
|
-
:isSubmit?await submit(args,context,form):null;
|
|
266
|
-
if(isSubmit&&result&&args.mode!=='MANAGED')
|
|
267
|
-
result.preparedFormIdVerified=true;
|
|
268
|
-
if(isPrepare&&result){
|
|
269
|
-
for(const [id,record] of forms){
|
|
270
|
-
if(Date.now()-record.at>TTL)forms.delete(id);
|
|
271
|
-
}
|
|
272
|
-
if(forms.size>=256)forms.delete(forms.keys().next().value);
|
|
273
|
-
forms.set(result.formId,{at:Date.now(),submitted:false,
|
|
274
|
-
args:{...args,kind:result.kind,formId:result.formId,
|
|
275
|
-
issueId:result.issueId}});
|
|
276
|
-
}
|
|
277
|
-
if(result&&args?.projectId&&typeof form?.observe==='function'){
|
|
278
|
-
const parent=trace(form);
|
|
279
|
-
if(parent)setImmediate(()=>{
|
|
280
|
-
// Soft evidence, never an approval receipt or a retry trigger.
|
|
281
|
-
try{void Promise.resolve(form.observe({
|
|
282
|
-
event:name===tools[0].name?'form.prepared.soft_observed'
|
|
283
|
-
:'form.submitted.soft_observed',
|
|
284
|
-
projectRef:args.projectId,taskRef:args.taskId,
|
|
285
|
-
formId:result.formId,...parent
|
|
286
|
-
})).catch(()=>{})}catch{/* telemetry isolation */}
|
|
287
|
-
});
|
|
288
|
-
}
|
|
289
|
-
return result?ok(result):err('UNKNOWN_TOOL');
|
|
290
|
-
}catch(e){return err(e.code||'FORM_FAILED')}
|
|
159
|
+
const result=isPrepare?prepare(args):await submit(args,form);
|
|
160
|
+
await observeForm(form,
|
|
161
|
+
isPrepare?'form.prepared.soft_observed':'form.submitted.soft_observed',
|
|
162
|
+
result.formId,result.traceRef,parent);
|
|
163
|
+
return ok(result);
|
|
164
|
+
}catch(e){
|
|
165
|
+
await observeForm(form,
|
|
166
|
+
isPrepare?'form.prepared.failed':'form.submitted.failed',
|
|
167
|
+
e.formId||formId,e.traceRef||traceRef,parent,'FAILED',e.code||'FORM_FAILED');
|
|
168
|
+
throw e;
|
|
169
|
+
}
|
|
291
170
|
}
|
|
292
171
|
});
|
|
293
172
|
}
|
package/providers/trace.mjs
CHANGED
|
@@ -6,9 +6,12 @@ export const provider=Object.freeze({
|
|
|
6
6
|
id:'trace',order:4,names,
|
|
7
7
|
create({trace}){
|
|
8
8
|
return Object.freeze({
|
|
9
|
-
tools:()=>trace.traceGatewayEnabled()
|
|
9
|
+
tools:()=>trace.traceGatewayEnabled()
|
|
10
|
+
?[traceDiagnoseTool,traceStageTool]:[traceDiagnoseTool],
|
|
10
11
|
async call(name,args){
|
|
11
|
-
|
|
12
|
+
const formLookup=name===traceDiagnoseTool.name
|
|
13
|
+
&&args?.projectRef==='api_system';
|
|
14
|
+
if(!trace.traceGatewayEnabled()&&!formLookup)return fail('UNKNOWN_TOOL');
|
|
12
15
|
try{
|
|
13
16
|
const result=name===traceStageTool.name
|
|
14
17
|
?await trace.runTraceStage(args)
|
package/ui/form/review-app.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// Minimal MCP Apps View bridge: JSON-RPC over postMessage, no bundled runtime.
|
|
2
2
|
// Protocol: https://modelcontextprotocol.io/extensions/apps
|
|
3
|
-
//
|
|
3
|
+
// The Form service only renders, collects and returns user selections.
|
|
4
4
|
const $=id=>document.getElementById(id);
|
|
5
5
|
const options=[...document.querySelectorAll('input[name="choice"]')];
|
|
6
|
-
const idPattern=/^[A-Za-z0-9_-]{
|
|
6
|
+
const idPattern=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
7
|
+
const tracePattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
7
8
|
const requests=new Map();
|
|
8
|
-
let seq=0,connected=false,prepared=null,locked=false,toolResult=null;
|
|
9
|
+
let seq=0,connected=false,prepared=null,locked=false,toolResult=null,hostFailure=null;
|
|
9
10
|
function status(message,state='info'){
|
|
10
11
|
$('status').textContent=message;
|
|
11
12
|
$('status').dataset.state=state;
|
|
@@ -16,6 +17,7 @@ function call(method,params){
|
|
|
16
17
|
if(!connected)throw Error('FORM_APP_NOT_INITIALIZED');
|
|
17
18
|
return new Promise((resolve,reject)=>{
|
|
18
19
|
const id=++seq;
|
|
20
|
+
// Transport reply timeout only; it never expires or deletes a prepared form.
|
|
19
21
|
// A timeout never authorizes a retry of a write.
|
|
20
22
|
const timer=setTimeout(()=>{
|
|
21
23
|
requests.delete(id);reject(Error('FORM_APP_REPLY_UNKNOWN'));
|
|
@@ -25,7 +27,11 @@ function call(method,params){
|
|
|
25
27
|
});
|
|
26
28
|
}
|
|
27
29
|
function decode(result){
|
|
28
|
-
if(result?.isError)
|
|
30
|
+
if(result?.isError){
|
|
31
|
+
const code=result.content?.find(x=>x.type==='text')?.text;
|
|
32
|
+
throw Error(typeof code==='string'
|
|
33
|
+
&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)?code:'FORM_TOOL_REJECTED');
|
|
34
|
+
}
|
|
29
35
|
if(result?.structuredContent?.status)return result.structuredContent;
|
|
30
36
|
const text=result?.content?.find(x=>x.type==='text')?.text;
|
|
31
37
|
if(typeof text!=='string'||text.length>20000)throw Error('FORM_RECEIPT_MISSING');
|
|
@@ -34,22 +40,24 @@ function decode(result){
|
|
|
34
40
|
const selected=()=>options.find(x=>x.checked)?.value||null;
|
|
35
41
|
function update(){
|
|
36
42
|
const choice=selected();
|
|
43
|
+
$('options').disabled=!connected;
|
|
37
44
|
$('modify').hidden=choice!=='B';
|
|
38
|
-
$('submit').disabled=!prepared||locked||!choice
|
|
45
|
+
$('submit').disabled=!connected||!prepared||locked||!choice
|
|
39
46
|
||(choice==='B'&&!$('comment').value.trim());
|
|
40
47
|
resize();
|
|
41
48
|
}
|
|
42
49
|
function render(value){
|
|
43
50
|
const view=value?.view;
|
|
44
51
|
if(!view||view.template!=='chat-loop-review-card-v1'
|
|
45
|
-
||!idPattern.test(value.formId
|
|
52
|
+
||typeof value.formId!=='string'||!idPattern.test(value.formId)
|
|
53
|
+
||typeof value.traceRef!=='string'||!tracePattern.test(value.traceRef)
|
|
46
54
|
||view.formId!==value.formId
|
|
47
|
-
||!['GENERAL','TEST_ONLY','MANAGED'].includes(view.mode)
|
|
48
55
|
||view.options?.length!==2
|
|
49
56
|
||view.options[0]?.value!=='A'||view.options[1]?.value!=='B')
|
|
50
57
|
throw Error('FORM_VIEW_INVALID');
|
|
51
|
-
const
|
|
52
|
-
|
|
58
|
+
const preserveLock=prepared?.formId===value.formId
|
|
59
|
+
&&prepared?.traceRef===value.traceRef&&locked;
|
|
60
|
+
prepared=value;
|
|
53
61
|
$('title').textContent=view.title;
|
|
54
62
|
$('description').textContent=view.description;
|
|
55
63
|
$('a-label').textContent=view.options[0].label;
|
|
@@ -57,12 +65,13 @@ function render(value){
|
|
|
57
65
|
$('comment').placeholder=view.modifyField?.placeholder||'填写修改意见';
|
|
58
66
|
$('submit').textContent=view.submit?.label||'提交';
|
|
59
67
|
$('footer').textContent=view.footer||'';
|
|
60
|
-
$('options').disabled=!
|
|
68
|
+
$('options').disabled=!connected;
|
|
61
69
|
$('comment').value='';
|
|
62
70
|
options.forEach(x=>x.checked=false);
|
|
63
|
-
locked
|
|
64
|
-
status(
|
|
65
|
-
'
|
|
71
|
+
locked=preserveLock;
|
|
72
|
+
status(hostFailure|| (connected?'表单已准备,请选择 A 或 B。':
|
|
73
|
+
'表单已准备,正在等待宿主能力确认。'),
|
|
74
|
+
hostFailure?'error':connected?'ok':'info');
|
|
66
75
|
update();
|
|
67
76
|
}
|
|
68
77
|
function receive(event){
|
|
@@ -113,64 +122,70 @@ async function initialize(){
|
|
|
113
122
|
});
|
|
114
123
|
try{
|
|
115
124
|
const response=await init;
|
|
116
|
-
if(!response?.protocolVersion||!response.hostInfo
|
|
125
|
+
if(!response?.protocolVersion||!response.hostInfo
|
|
126
|
+
||!response.hostCapabilities)
|
|
117
127
|
throw Error('FORM_APP_INIT_INVALID');
|
|
128
|
+
if(!response.hostCapabilities.serverTools
|
|
129
|
+
||!response.hostCapabilities.message?.text){
|
|
130
|
+
hostFailure='当前宿主缺少 serverTools 或 message.text 能力,表单不可提交。';
|
|
131
|
+
status(hostFailure,'error');
|
|
132
|
+
update();
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
118
135
|
connected=true;
|
|
136
|
+
hostFailure=null;
|
|
119
137
|
notify('ui/notifications/initialized',{});
|
|
120
138
|
resize();
|
|
121
139
|
if(toolResult)render(decode(toolResult));
|
|
122
140
|
if(typeof ResizeObserver==='function')
|
|
123
141
|
new ResizeObserver(resize).observe(document.documentElement);
|
|
124
142
|
}catch{
|
|
125
|
-
|
|
143
|
+
hostFailure='MCP App 初始化失败,请核查宿主连接与协议能力。';
|
|
144
|
+
status(hostFailure,'error');
|
|
145
|
+
connected=false;
|
|
146
|
+
update();
|
|
126
147
|
}
|
|
127
148
|
}
|
|
128
149
|
async function submit(){
|
|
129
|
-
if(!connected||locked||!prepared
|
|
130
|
-
||!['GENERAL','TEST_ONLY'].includes(prepared.mode))return;
|
|
150
|
+
if(!connected||locked||!prepared)return;
|
|
131
151
|
const choice=selected(),comment=$('comment').value.trim();
|
|
132
152
|
if(!['A','B'].includes(choice)||choice==='B'&&!comment)return;
|
|
133
153
|
locked=true;update();
|
|
134
|
-
const {formId,
|
|
135
|
-
const args={
|
|
136
|
-
|
|
137
|
-
userTurn:'unverified-app-'+writeRequestId,
|
|
138
|
-
presentedAssistantRef:'app-form-'+formId,
|
|
139
|
-
writeRequestId,
|
|
140
|
-
...(mode==='TEST_ONLY'?{
|
|
141
|
-
projectId:prepared.projectId,chatRef:prepared.chatRef,
|
|
142
|
-
documentId:prepared.documentId,version:prepared.version
|
|
143
|
-
}:{})};
|
|
144
|
-
status('正在向 Form submit 提交唯一请求…');
|
|
154
|
+
const {formId,traceRef}=prepared;
|
|
155
|
+
const args={formId,traceRef,choice,...(choice==='B'?{comment}:{})};
|
|
156
|
+
status('正在提交表单…');
|
|
145
157
|
let receipt;
|
|
146
158
|
try{receipt=decode(await call('tools/call',{
|
|
147
159
|
name:'chat_loop_form__submit',arguments:args
|
|
148
160
|
}))}
|
|
149
|
-
catch{
|
|
150
|
-
|
|
161
|
+
catch(error){
|
|
162
|
+
const code=typeof error?.message==='string'
|
|
163
|
+
&&/^[A-Z][A-Z0-9_]{1,95}$/.test(error.message)
|
|
164
|
+
?error.message:'FORM_APP_REPLY_UNKNOWN';
|
|
165
|
+
status(code==='FORM_APP_REPLY_UNKNOWN'||code==='FORM_SUBMISSION_CLAIM_UNKNOWN'
|
|
166
|
+
?'Submit 结果未知,已锁定,禁止重复提交;请查原请求回执。'
|
|
167
|
+
:code==='FORM_ALREADY_SUBMITTED'
|
|
168
|
+
?'该表单已提交过,禁止重复发送;请核查原消息。'
|
|
169
|
+
:'Submit 明确失败('+code+'),用户消息未发送。','error');
|
|
151
170
|
return;
|
|
152
171
|
}
|
|
153
|
-
if(receipt.status!=='
|
|
154
|
-
||receipt.formId!==formId||receipt.
|
|
155
|
-
||receipt.
|
|
156
|
-
status('Submit
|
|
172
|
+
if(receipt.status!=='FORM_SUBMITTED'
|
|
173
|
+
||receipt.formId!==formId||receipt.traceRef!==traceRef
|
|
174
|
+
||receipt.choice!==choice){
|
|
175
|
+
status('Submit 返回的信息与当前表单不匹配,用户消息未发送。','error');
|
|
157
176
|
return;
|
|
158
177
|
}
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
+(choice==='A'?'A 确认':'B 修改:'+comment)
|
|
163
|
-
+'。组件请求发送,用户消息身份须独立核对。'
|
|
164
|
-
+(mode==='TEST_ONLY'?'不构成正式审批,不 Start/Continue/Handoff。':'');
|
|
165
|
-
status('Submit 软回执成功,正在申请单次用户消息…');
|
|
178
|
+
const text='【Chat Loop Form】formId='+formId+'|'
|
|
179
|
+
+(choice==='A'?'A 选择':'B 选择:'+comment)+'。';
|
|
180
|
+
status('单次提交已锁定,正在申请当前 Chat 用户消息…');
|
|
166
181
|
try{
|
|
167
182
|
const result=await call('ui/message',{
|
|
168
183
|
role:'user',content:[{type:'text',text}]
|
|
169
184
|
});
|
|
170
|
-
status(result?.isError?'
|
|
171
|
-
'
|
|
185
|
+
status(result?.isError?'宿主未接受表单结果消息。':
|
|
186
|
+
'宿主已接受用户消息请求;平台消息身份仍需独立核验。',
|
|
172
187
|
result?.isError?'error':'ok');
|
|
173
|
-
}catch{status('
|
|
188
|
+
}catch{status('用户消息发送状态未知,已锁定,禁止重试;请核查原消息。','error')}
|
|
174
189
|
}
|
|
175
190
|
window.addEventListener('message',receive);
|
|
176
191
|
options.forEach(x=>x.addEventListener('change',update));
|
package/ui/form/review.html
CHANGED
|
@@ -40,7 +40,7 @@ button:disabled{opacity:.44;cursor:not-allowed}
|
|
|
40
40
|
<div id="status" role="status">等待真实 MCP Form prepare 回执</div>
|
|
41
41
|
<small id="footer"></small>
|
|
42
42
|
</main>
|
|
43
|
-
<script>(()=>{var r=t=>document.getElementById(t),
|
|
43
|
+
<script>(()=>{var r=t=>document.getElementById(t),w=[...document.querySelectorAll('input[name="choice"]')],N=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/,T=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,u=new Map,P=0,s=!1,l=null,p=!1,_=null,d=null;function i(t,e="info"){r("status").textContent=t,r("status").dataset.state=e}function E(t){window.parent.postMessage({jsonrpc:"2.0",...t},"*")}function g(t,e={}){E({method:t,params:e})}function O(t,e){if(!s)throw Error("FORM_APP_NOT_INITIALIZED");return new Promise((o,n)=>{let c=++P,a=setTimeout(()=>{u.delete(c),n(Error("FORM_APP_REPLY_UNKNOWN"))},3e4);u.set(c,{resolve:o,reject:n,timer:a}),E({id:c,method:t,params:e})})}function b(t){if(t?.isError){let o=t.content?.find(n=>n.type==="text")?.text;throw Error(typeof o=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(o)?o:"FORM_TOOL_REJECTED")}if(t?.structuredContent?.status)return t.structuredContent;let e=t?.content?.find(o=>o.type==="text")?.text;if(typeof e!="string"||e.length>2e4)throw Error("FORM_RECEIPT_MISSING");return JSON.parse(e)}var M=()=>w.find(t=>t.checked)?.value||null;function m(){let t=M();r("options").disabled=!s,r("modify").hidden=t!=="B",r("submit").disabled=!s||!l||p||!t||t==="B"&&!r("comment").value.trim(),I()}function C(t){let e=t?.view;if(!e||e.template!=="chat-loop-review-card-v1"||typeof t.formId!="string"||!N.test(t.formId)||typeof t.traceRef!="string"||!T.test(t.traceRef)||e.formId!==t.formId||e.options?.length!==2||e.options[0]?.value!=="A"||e.options[1]?.value!=="B")throw Error("FORM_VIEW_INVALID");let o=l?.formId===t.formId&&l?.traceRef===t.traceRef&&p;l=t,r("title").textContent=e.title,r("description").textContent=e.description,r("a-label").textContent=e.options[0].label,r("b-label").textContent=e.options[1].label,r("comment").placeholder=e.modifyField?.placeholder||"\u586B\u5199\u4FEE\u6539\u610F\u89C1",r("submit").textContent=e.submit?.label||"\u63D0\u4EA4",r("footer").textContent=e.footer||"",r("options").disabled=!s,r("comment").value="",w.forEach(n=>n.checked=!1),p=o,i(d||(s?"\u8868\u5355\u5DF2\u51C6\u5907\uFF0C\u8BF7\u9009\u62E9 A \u6216 B\u3002":"\u8868\u5355\u5DF2\u51C6\u5907\uFF0C\u6B63\u5728\u7B49\u5F85\u5BBF\u4E3B\u80FD\u529B\u786E\u8BA4\u3002"),d?"error":s?"ok":"info"),m()}function v(t){if(t.source!==window.parent)return;let e=t.data;if(!(!e||e.jsonrpc!=="2.0"||typeof e!="object")){if(Object.hasOwn(e,"id")&&!Object.hasOwn(e,"method")){let o=u.get(e.id);if(!o)return;u.delete(e.id),clearTimeout(o.timer),e.error?o.reject(Error("MCP_APP_HOST_REJECTED")):o.resolve(e.result);return}if(e.method==="ui/notifications/tool-result"){_=e.params;try{C(b(_))}catch{i("Form prepare \u56DE\u6267\u65E0\u6548\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error")}}e.method==="ui/resource-teardown"&&e.id!==void 0&&E({id:e.id,result:{}})}}var R=0,A=0;function I(){if(!s)return;let t=Math.ceil(document.documentElement.scrollHeight),e=Math.ceil(document.documentElement.clientWidth);t===R&&e===A||(R=t,A=e,g("ui/notifications/size-changed",{width:e,height:t}))}async function x(){if(window.parent===window){i("\u672A\u5728 ChatGPT MCP App iframe \u4E2D\u8FD0\u884C\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error");return}let t=++P,e=new Promise((o,n)=>{let c=setTimeout(()=>{u.delete(t),n(Error("FORM_APP_INIT_TIMEOUT"))},12e3);u.set(t,{resolve:o,reject:n,timer:c}),E({id:t,method:"ui/initialize",params:{appInfo:{name:"Chat Loop Review",version:"1.0.1"},appCapabilities:{},protocolVersion:"2026-01-26"}})});try{let o=await e;if(!o?.protocolVersion||!o.hostInfo||!o.hostCapabilities)throw Error("FORM_APP_INIT_INVALID");if(!o.hostCapabilities.serverTools||!o.hostCapabilities.message?.text){d="\u5F53\u524D\u5BBF\u4E3B\u7F3A\u5C11 serverTools \u6216 message.text \u80FD\u529B\uFF0C\u8868\u5355\u4E0D\u53EF\u63D0\u4EA4\u3002",i(d,"error"),m();return}s=!0,d=null,g("ui/notifications/initialized",{}),I(),_&&C(b(_)),typeof ResizeObserver=="function"&&new ResizeObserver(I).observe(document.documentElement)}catch{d="MCP App \u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u6838\u67E5\u5BBF\u4E3B\u8FDE\u63A5\u4E0E\u534F\u8BAE\u80FD\u529B\u3002",i(d,"error"),s=!1,m()}}async function F(){if(!s||p||!l)return;let t=M(),e=r("comment").value.trim();if(!["A","B"].includes(t)||t==="B"&&!e)return;p=!0,m();let{formId:o,traceRef:n}=l,c={formId:o,traceRef:n,choice:t,...t==="B"?{comment:e}:{}};i("\u6B63\u5728\u63D0\u4EA4\u8868\u5355\u2026");let a;try{a=b(await O("tools/call",{name:"chat_loop_form__submit",arguments:c}))}catch(f){let h=typeof f?.message=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(f.message)?f.message:"FORM_APP_REPLY_UNKNOWN";i(h==="FORM_APP_REPLY_UNKNOWN"||h==="FORM_SUBMISSION_CLAIM_UNKNOWN"?"Submit \u7ED3\u679C\u672A\u77E5\uFF0C\u5DF2\u9501\u5B9A\uFF0C\u7981\u6B62\u91CD\u590D\u63D0\u4EA4\uFF1B\u8BF7\u67E5\u539F\u8BF7\u6C42\u56DE\u6267\u3002":h==="FORM_ALREADY_SUBMITTED"?"\u8BE5\u8868\u5355\u5DF2\u63D0\u4EA4\u8FC7\uFF0C\u7981\u6B62\u91CD\u590D\u53D1\u9001\uFF1B\u8BF7\u6838\u67E5\u539F\u6D88\u606F\u3002":"Submit \u660E\u786E\u5931\u8D25\uFF08"+h+"\uFF09\uFF0C\u7528\u6237\u6D88\u606F\u672A\u53D1\u9001\u3002","error");return}if(a.status!=="FORM_SUBMITTED"||a.formId!==o||a.traceRef!==n||a.choice!==t){i("Submit \u8FD4\u56DE\u7684\u4FE1\u606F\u4E0E\u5F53\u524D\u8868\u5355\u4E0D\u5339\u914D\uFF0C\u7528\u6237\u6D88\u606F\u672A\u53D1\u9001\u3002","error");return}let y="\u3010Chat Loop Form\u3011formId="+o+"\uFF5C"+(t==="A"?"A \u9009\u62E9":"B \u9009\u62E9\uFF1A"+e)+"\u3002";i("\u5355\u6B21\u63D0\u4EA4\u5DF2\u9501\u5B9A\uFF0C\u6B63\u5728\u7533\u8BF7\u5F53\u524D Chat \u7528\u6237\u6D88\u606F\u2026");try{let f=await O("ui/message",{role:"user",content:[{type:"text",text:y}]});i(f?.isError?"\u5BBF\u4E3B\u672A\u63A5\u53D7\u8868\u5355\u7ED3\u679C\u6D88\u606F\u3002":"\u5BBF\u4E3B\u5DF2\u63A5\u53D7\u7528\u6237\u6D88\u606F\u8BF7\u6C42\uFF1B\u5E73\u53F0\u6D88\u606F\u8EAB\u4EFD\u4ECD\u9700\u72EC\u7ACB\u6838\u9A8C\u3002",f?.isError?"error":"ok")}catch{i("\u7528\u6237\u6D88\u606F\u53D1\u9001\u72B6\u6001\u672A\u77E5\uFF0C\u5DF2\u9501\u5B9A\uFF0C\u7981\u6B62\u91CD\u8BD5\uFF1B\u8BF7\u6838\u67E5\u539F\u6D88\u606F\u3002","error")}}window.addEventListener("message",v);w.forEach(t=>t.addEventListener("change",m));r("comment").addEventListener("input",m);r("submit").addEventListener("click",F);x();})();
|
|
44
44
|
</script>
|
|
45
45
|
</body>
|
|
46
46
|
</html>
|