@tomflow/chatloop-tools 0.9.22 → 0.9.24
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 +12 -8
- package/index.mjs +3 -20
- package/lib/supervisor-observability.mjs +7 -54
- package/lib/supervisor-runtime.mjs +1 -4
- package/lib/trace-gateway.mjs +1 -1
- package/node_modules/@tomflow/chatloop-context/package.json +3 -3
- package/node_modules/@tomflow/chatloop-extension/extension/manifest.json +1 -1
- package/node_modules/@tomflow/chatloop-extension/package.json +2 -2
- package/node_modules/@tomflow/chatloop-trace/README.md +10 -3
- package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +4 -2
- package/node_modules/@tomflow/chatloop-trace/lib/trace-retention.mjs +109 -0
- package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +12 -5
- package/node_modules/@tomflow/chatloop-trace/package.json +1 -1
- package/package.json +6 -6
- package/providers/form.mjs +135 -103
- package/ui/form/review-app.js +93 -78
- package/ui/form/review.html +10 -6
- package/ui/form/review.template.html +9 -5
package/README.md
CHANGED
|
@@ -39,7 +39,9 @@ declared methods and MCP Provider
|
|
|
39
39
|
catalog have separate capability tests. Internal Trace Writer health/record
|
|
40
40
|
operations are excluded from re-submitting themselves to prevent recursive logs.
|
|
41
41
|
Non-authoritative process/control logs use a bounded async queue, with drops
|
|
42
|
-
and pending counts visible in Supervisor Trace health.
|
|
42
|
+
and pending counts visible in Supervisor Trace health. The Trace Writer retains
|
|
43
|
+
30 days by default, prunes expired records at startup and daily, and reports
|
|
44
|
+
retention results/errors through its existing health receipt.
|
|
43
45
|
|
|
44
46
|
```text
|
|
45
47
|
Usage: chatloop-tools <command> [target]
|
|
@@ -64,7 +66,7 @@ The six built-in Providers are:
|
|
|
64
66
|
- `runtime`: exact-request receipt lookup without replay
|
|
65
67
|
- `context`: independent Context SDK read/write schemas and fixed CLI
|
|
66
68
|
- `trace`: Project-scoped diagnosis and SOFT stage observations, plus a bearer-token-scoped Form Trace lookup using the Prepare `traceRef`
|
|
67
|
-
- `form`: a stateless
|
|
69
|
+
- `form`: a stateless generic single-select MCP App. `prepare` renders caller-defined options and optional text input, preserves or generates `formId`, and returns a random `traceRef`; `submit` returns the selected value/label and optional text to the caller. It does not send Chat messages, interpret business meaning, call Context, retain prepared-form state, or impose expiry. Prepare/Submit API spans and soft observations are correlated in the existing Trace writer by `sessionRef=traceRef` and `evidenceRef=formId`; Trace loss never blocks or changes the returned Form data.
|
|
68
70
|
|
|
69
71
|
`npm run build:providers` generates `providers.generated.mjs`, the static
|
|
70
72
|
assembly and release fingerprint manifest. Both `tools/list` and `tools/call`
|
|
@@ -107,12 +109,14 @@ to any existing Provider, the Gateway, or either npm entrypoint.
|
|
|
107
109
|
trigger retries of unknown effects. In particular, verified Extension MCP
|
|
108
110
|
results are returned **before** optional Trace transport finishes; a
|
|
109
111
|
slow, rejecting or unavailable observer cannot replace the action receipt.
|
|
110
|
-
Form submission claims are
|
|
111
|
-
the
|
|
112
|
-
|
|
113
|
-
message
|
|
114
|
-
|
|
115
|
-
|
|
112
|
+
Form submission claims are a generic Supervisor idempotency concern:
|
|
113
|
+
the dedicated private ledger durably records the opaque `traceRef` claim
|
|
114
|
+
independently of the 30-day Trace retention window. A failed or unknown
|
|
115
|
+
ledger write blocks the user message and forbids retry. Once the claim is
|
|
116
|
+
durably committed, Trace observation failure never reverses or blocks the
|
|
117
|
+
Form result; the missing evidence is surfaced by Trace health/diagnose.
|
|
118
|
+
Form observations remain best-effort evidence and are not an all-API AOP
|
|
119
|
+
coverage claim.
|
|
116
120
|
|
|
117
121
|
No legacy Task Registry MCP or JSON fallback is shipped. Historical
|
|
118
122
|
SourceUnit files remain migration evidence, not alternate current facts.
|
package/index.mjs
CHANGED
|
@@ -179,33 +179,16 @@ async function runtime(){
|
|
|
179
179
|
const coreToolRouter=createMcpToolRouter(providerDefinitions,{
|
|
180
180
|
control,release,terminal:terminalPolicy,context:contextGateway,
|
|
181
181
|
form:{
|
|
182
|
-
|
|
183
|
-
claimSubmission:async ({formId,traceRef})=>{
|
|
182
|
+
observe:async payload=>{
|
|
184
183
|
const parent=apiAspect.current();
|
|
185
184
|
if(!parent||!OBSERVER_UUID.test(parent.traceId||'')
|
|
186
185
|
||!OBSERVER_UUID.test(parent.spanId||''))
|
|
187
|
-
throw localError('
|
|
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=>{
|
|
186
|
+
throw localError('FORM_TRACE_PARENT_MISSING');
|
|
204
187
|
const result=await control.talk({
|
|
205
188
|
contract:control.CONTRACT,action:'__trace_observation',
|
|
206
189
|
requestId:randomUUID(),event:payload.event,
|
|
207
190
|
status:payload.status||'CONFIRMED',
|
|
208
|
-
traceId:
|
|
191
|
+
traceId:parent.traceId,spanId:parent.spanId,
|
|
209
192
|
projectRef:'api_system',sessionRef:payload.traceRef,
|
|
210
193
|
evidenceRef:payload.formId,
|
|
211
194
|
...(payload.errorCode?{errorCode:payload.errorCode}:{})
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import {createTraceWriter,createTraceReader} from '@tomflow/chatloop-trace';
|
|
2
2
|
|
|
3
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
4
|
const OBSERVER_NAME=/^(?:mcp|extension|tools|context|trace|tunnel)\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
|
|
6
5
|
const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
|
|
7
6
|
'traceId','spanId','parentSpanId','apiName','phase','durationMs','errorCode',
|
|
@@ -9,9 +8,9 @@ const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
|
|
|
9
8
|
|
|
10
9
|
export function createSupervisorObservability({
|
|
11
10
|
filePath,rotationEnabled,contextUsageGrant,contract,nonce,processId,
|
|
12
|
-
createSupervisorTraceBridge,
|
|
11
|
+
createSupervisorTraceBridge,createTraceWriterImpl=createTraceWriter
|
|
13
12
|
}){
|
|
14
|
-
const traceWriter=
|
|
13
|
+
const traceWriter=createTraceWriterImpl({
|
|
15
14
|
filePath,enableRotation:rotationEnabled
|
|
16
15
|
});
|
|
17
16
|
const usageScopes=['api_system',...(
|
|
@@ -19,7 +18,6 @@ export function createSupervisorObservability({
|
|
|
19
18
|
/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextUsageGrant)
|
|
20
19
|
?[contextUsageGrant]:[])];
|
|
21
20
|
const usageReader=createTraceReader({filePath,allowedProjects:usageScopes});
|
|
22
|
-
const formClaimInFlight=new Set();
|
|
23
21
|
|
|
24
22
|
// Control telemetry is bounded and asynchronous; it never changes a
|
|
25
23
|
// confirmed or unknown business result.
|
|
@@ -59,7 +57,7 @@ export function createSupervisorObservability({
|
|
|
59
57
|
?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
|
|
60
58
|
};
|
|
61
59
|
const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
|
|
62
|
-
traceWriter,contract
|
|
60
|
+
traceWriter,contract
|
|
63
61
|
});
|
|
64
62
|
|
|
65
63
|
function recordApiObservation(req){
|
|
@@ -75,7 +73,7 @@ export function createSupervisorObservability({
|
|
|
75
73
|
(!OBSERVER_ID.test(req.parentSpanId)||req.parentSpanId===req.spanId))||
|
|
76
74
|
!OBSERVER_NAME.test(req.apiName||'')||
|
|
77
75
|
!['BEGIN','OK','FAILED'].includes(req.phase)||
|
|
78
|
-
Object.keys(req).some(
|
|
76
|
+
Object.keys(req).some(key=>!OBSERVER_KEYS.has(key))||
|
|
79
77
|
(req.phase==='BEGIN'
|
|
80
78
|
?req.durationMs!==undefined||req.errorCode!==undefined
|
|
81
79
|
:!Number.isSafeInteger(req.durationMs)||req.durationMs<0||
|
|
@@ -98,8 +96,8 @@ export function createSupervisorObservability({
|
|
|
98
96
|
|
|
99
97
|
async function apiUsage(req){
|
|
100
98
|
if(req?.contract!==contract||
|
|
101
|
-
Object.keys(req).some(
|
|
102
|
-
'windowMinutes','limit'].includes(
|
|
99
|
+
Object.keys(req).some(key=>!['contract','action','requestId',
|
|
100
|
+
'windowMinutes','limit'].includes(key))||
|
|
103
101
|
!OBSERVER_ID.test(req.requestId||''))
|
|
104
102
|
throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
|
|
105
103
|
const summary=await usageReader.apiUsage({
|
|
@@ -107,51 +105,6 @@ export function createSupervisorObservability({
|
|
|
107
105
|
return {contract,requestId:req.requestId,status:'OK',summary};
|
|
108
106
|
}
|
|
109
107
|
|
|
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
108
|
return {log,traceHealth,handleTraceObservation,traceNativeReceipt,
|
|
156
|
-
recordApiObservation,apiUsage,
|
|
109
|
+
recordApiObservation,apiUsage,flushPending};
|
|
157
110
|
}
|
|
@@ -45,7 +45,7 @@ const observability=createSupervisorObservability({
|
|
|
45
45
|
createSupervisorTraceBridge,error
|
|
46
46
|
});
|
|
47
47
|
const {log,traceHealth,handleTraceObservation,traceNativeReceipt,
|
|
48
|
-
recordApiObservation,apiUsage,
|
|
48
|
+
recordApiObservation,apiUsage,flushPending}=observability;
|
|
49
49
|
const desiredTunnel=new Set(), recoveryAttempts=new Map();
|
|
50
50
|
let lockFd, server, idleTimer;
|
|
51
51
|
const after=rec=>rec ? rec.state : 'STOPPED';
|
|
@@ -244,9 +244,6 @@ async function main(){
|
|
|
244
244
|
:req?.action==='__api_usage'
|
|
245
245
|
?Promise.resolve().then(()=>apiUsage(req))
|
|
246
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'))
|
|
250
247
|
:req?.action==='context-control'
|
|
251
248
|
?handleContextControl(req).then(result=>{
|
|
252
249
|
traceNativeReceipt(req);
|
package/lib/trace-gateway.mjs
CHANGED
|
@@ -45,7 +45,7 @@ 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
46
|
const FORM_TRACE_REF=new RegExp(UUID);
|
|
47
47
|
const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
48
|
-
const FORM_EVENT=/^form\.(?:prepared|submitted)\.(?:soft_observed|failed)
|
|
48
|
+
const FORM_EVENT=/^form\.(?:prepared|submitted)\.(?:soft_observed|failed)$/;
|
|
49
49
|
const FORM_APIS=new Set(['mcp.chat_loop_form__prepare','mcp.chat_loop_form__submit']);
|
|
50
50
|
export const traceStageTool={
|
|
51
51
|
name:'chat_loop_trace_stage',
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tomflow/chatloop-context",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.12",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Independent local Context SDK and short-lived CLI for Chat Loop projects",
|
|
6
6
|
"publishConfig": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"ps-list": "9.0.0",
|
|
37
|
-
"@tomflow/chatloop-extension": "0.4.
|
|
38
|
-
"@tomflow/chatloop-trace": "0.4.
|
|
37
|
+
"@tomflow/chatloop-extension": "0.4.12",
|
|
38
|
+
"@tomflow/chatloop-trace": "0.4.5"
|
|
39
39
|
}
|
|
40
40
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tomflow/chatloop-extension",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.12",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Chat Loop Extension package: nine formal Action pages and its own native CLI bridge",
|
|
6
6
|
"bin": {
|
|
@@ -33,6 +33,6 @@
|
|
|
33
33
|
".": "./index.mjs"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@tomflow/chatloop-trace": "0.4.
|
|
36
|
+
"@tomflow/chatloop-trace": "0.4.5"
|
|
37
37
|
}
|
|
38
38
|
}
|
|
@@ -13,8 +13,13 @@ The root exposes two data APIs, a shared AOP factory and one opt-in, non-authori
|
|
|
13
13
|
to the existing Supervisor. The writer's own `record/recordControl`
|
|
14
14
|
telemetry is filtered at that boundary to prevent feedback loops. A
|
|
15
15
|
standalone SDK stays installable and never creates another logging service.
|
|
16
|
-
- `createTraceWriter({filePath})`: the Supervisor invokes
|
|
17
|
-
`record(event)`, `recordControl(event,detail)` and `health()`.
|
|
16
|
+
- `createTraceWriter({filePath,retentionDays=30})`: the Supervisor invokes
|
|
17
|
+
`record(event)`, `recordControl(event,detail)` and `health()`. The single
|
|
18
|
+
Writer prunes only parseable records older than the configured retention
|
|
19
|
+
window at startup and daily across its active file and bounded rotation
|
|
20
|
+
segments. Unknown/malformed-age lines are preserved; source identity and
|
|
21
|
+
permissions are rechecked before atomic replacement. Retention results are
|
|
22
|
+
visible in `health().retention`.
|
|
18
23
|
- `createTraceReader({filePath,allowedProjects})`: the Gateway invokes
|
|
19
24
|
`diagnose({projectRef,traceId|sessionRef,maxEvents})`, `apiUsage({windowMinutes,limit})`
|
|
20
25
|
or `health()`. `apiUsage` requires a Reader explicitly scoped to
|
|
@@ -86,7 +91,9 @@ nested result objects can enter v2 records. Existing legacy evidence is
|
|
|
86
91
|
read-only, never migrated into a new current receipt or permission.
|
|
87
92
|
|
|
88
93
|
The SDK verifies file owner, permissions, symlink safety and bounds event
|
|
89
|
-
and query sizes.
|
|
94
|
+
and query sizes. Scoped readers stream logs up to 2 GiB without loading the
|
|
95
|
+
full JSONL file into memory; the default 30-day Writer retention keeps normal
|
|
96
|
+
operational history within that read bound. Diagnostics expose truncation, corrupted lines, writer
|
|
90
97
|
restarts, legacy records and pending receipts as **uncertainty**. They never
|
|
91
98
|
grant approval, Context write rights, Owner transfer or automatic retry.
|
|
92
99
|
A missing or interrupted Writer must be checked against the authoritative
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
import {constants as FS,createReadStream,closeSync,fstatSync,openSync} from 'node:fs';
|
|
3
3
|
import {createInterface} from 'node:readline';
|
|
4
4
|
|
|
5
|
+
const MAX_TRACE_READ_BYTES=2*1024*1024*1024;
|
|
6
|
+
|
|
5
7
|
export function makeTraceReader(options,deps){
|
|
6
8
|
const {TRACE_SCHEMA_VERSION,fail,validStoredFamily,object,isId,safeScope,
|
|
7
9
|
safeRef,natural,keys,secureFile,eventRule,EVENT,CODE,COMPONENTS,STATUSES}=deps;
|
|
@@ -60,7 +62,7 @@ export function makeTraceReader(options,deps){
|
|
|
60
62
|
filePath].map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
|
|
61
63
|
if(!files.length)return {events:[],matched:0,legacyUncorrelated:true,gapped:true,
|
|
62
64
|
errors:['TRACE_LOG_MISSING'],truncated:false};
|
|
63
|
-
if(files.reduce((sum,x)=>sum+x.stat.size,0)>
|
|
65
|
+
if(files.reduce((sum,x)=>sum+x.stat.size,0)>MAX_TRACE_READ_BYTES)
|
|
64
66
|
throw fail('TRACE_FILE_TOO_LARGE');
|
|
65
67
|
const seen=new Set(),events=[],errors=[],writerEpochs=new Set();
|
|
66
68
|
let matched=0,corrupt=0,legacy=0;
|
|
@@ -157,7 +159,7 @@ export function makeTraceReader(options,deps){
|
|
|
157
159
|
const files=[...Array.from({length:maxSegments},(_,i)=>
|
|
158
160
|
filePath+'.'+(maxSegments-i)),filePath]
|
|
159
161
|
.map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
|
|
160
|
-
if(files.reduce((n,x)=>n+x.stat.size,0)>
|
|
162
|
+
if(files.reduce((n,x)=>n+x.stat.size,0)>MAX_TRACE_READ_BYTES)
|
|
161
163
|
throw fail('TRACE_FILE_TOO_LARGE');
|
|
162
164
|
let malformed=0;
|
|
163
165
|
for(const item of files){
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import {randomUUID} from 'node:crypto';
|
|
2
|
+
import {constants as FS,closeSync,fstatSync,fsyncSync,lstatSync,openSync,readSync,writeSync,renameSync,unlinkSync} from 'node:fs';
|
|
3
|
+
|
|
4
|
+
const sameFile=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size
|
|
5
|
+
&&a.mtimeMs===b.mtimeMs;
|
|
6
|
+
const writeAll=(fd,buffer)=>{
|
|
7
|
+
let offset=0;
|
|
8
|
+
while(offset<buffer.length)offset+=writeSync(fd,buffer,offset,buffer.length-offset);
|
|
9
|
+
};
|
|
10
|
+
function pruneFile(filePath,cutoff,secureFile){
|
|
11
|
+
const before=secureFile(filePath);
|
|
12
|
+
if(!before)return {droppedRecords:0,droppedBytes:0,pruned:false};
|
|
13
|
+
const input=openSync(filePath,FS.O_RDONLY|FS.O_NOFOLLOW);
|
|
14
|
+
let output,temp;
|
|
15
|
+
try{
|
|
16
|
+
const opened=fstatSync(input);
|
|
17
|
+
if(!opened.isFile()||(opened.mode&0o077)||
|
|
18
|
+
process.getuid&&opened.uid!==process.getuid()||!sameFile(before,opened))
|
|
19
|
+
throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
|
|
20
|
+
{code:'TRACE_RETENTION_SOURCE_CHANGED'});
|
|
21
|
+
temp=filePath+'.retention-'+randomUUID();
|
|
22
|
+
output=openSync(temp,FS.O_WRONLY|FS.O_CREAT|FS.O_EXCL|FS.O_NOFOLLOW,0o600);
|
|
23
|
+
const chunk=Buffer.allocUnsafe(64*1024),newline=Buffer.from([10]);
|
|
24
|
+
let position=0,pending=Buffer.alloc(0),longLine=false;
|
|
25
|
+
let droppedRecords=0,droppedBytes=0,keptRecords=0;
|
|
26
|
+
const keepLine=(line,terminated=true)=>{
|
|
27
|
+
let expired=false;
|
|
28
|
+
if(line.length<=8192){
|
|
29
|
+
try{
|
|
30
|
+
const value=JSON.parse(line.toString('utf8'));
|
|
31
|
+
const timestamp=Date.parse(value?.time);
|
|
32
|
+
expired=Number.isFinite(timestamp)&×tamp<cutoff;
|
|
33
|
+
}catch{}
|
|
34
|
+
}
|
|
35
|
+
if(expired){droppedRecords++;droppedBytes+=line.length+(terminated?1:0);}
|
|
36
|
+
else{writeAll(output,line);writeAll(output,newline);keptRecords++;}
|
|
37
|
+
};
|
|
38
|
+
while(position<before.size){
|
|
39
|
+
const count=readSync(input,chunk,0,Math.min(chunk.length,before.size-position),position);
|
|
40
|
+
if(!count)throw Object.assign(Error('TRACE_RETENTION_READ_INCOMPLETE'),
|
|
41
|
+
{code:'TRACE_RETENTION_READ_INCOMPLETE'});
|
|
42
|
+
position+=count;
|
|
43
|
+
let start=0;
|
|
44
|
+
while(start<count){
|
|
45
|
+
const end=chunk.indexOf(10,start);
|
|
46
|
+
if(longLine){
|
|
47
|
+
const next=end<0?count:end+1;
|
|
48
|
+
writeAll(output,chunk.subarray(start,next));
|
|
49
|
+
if(end<0){start=count;continue;}
|
|
50
|
+
longLine=false;start=next;continue;
|
|
51
|
+
}
|
|
52
|
+
if(end<0){
|
|
53
|
+
const part=chunk.subarray(start,count);
|
|
54
|
+
if(pending.length+part.length>8192){
|
|
55
|
+
writeAll(output,pending);writeAll(output,part);
|
|
56
|
+
pending=Buffer.alloc(0);longLine=true;keptRecords++;
|
|
57
|
+
}else pending=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
|
|
58
|
+
start=count;continue;
|
|
59
|
+
}
|
|
60
|
+
const part=chunk.subarray(start,end);
|
|
61
|
+
const line=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
|
|
62
|
+
if(line.length>8192){writeAll(output,line);writeAll(output,newline);keptRecords++;}
|
|
63
|
+
else keepLine(line);
|
|
64
|
+
pending=Buffer.alloc(0);start=end+1;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
if(longLine)writeAll(output,newline);
|
|
68
|
+
else if(pending.length)keepLine(pending,false);
|
|
69
|
+
const after=fstatSync(input),current=lstatSync(filePath);
|
|
70
|
+
if(!sameFile(before,after)||!sameFile(before,current))
|
|
71
|
+
throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
|
|
72
|
+
{code:'TRACE_RETENTION_SOURCE_CHANGED'});
|
|
73
|
+
if(!droppedRecords){
|
|
74
|
+
closeSync(output);output=undefined;unlinkSync(temp);temp=null;
|
|
75
|
+
return {droppedRecords,droppedBytes,pruned:false};
|
|
76
|
+
}
|
|
77
|
+
fsyncSync(output);closeSync(output);output=undefined;
|
|
78
|
+
closeSync(input);
|
|
79
|
+
if(!keptRecords){unlinkSync(filePath);unlinkSync(temp);temp=null;}
|
|
80
|
+
else{renameSync(temp,filePath);temp=null;}
|
|
81
|
+
return {droppedRecords,droppedBytes,pruned:true};
|
|
82
|
+
}finally{
|
|
83
|
+
try{closeSync(input)}catch{}
|
|
84
|
+
if(output!==undefined)try{closeSync(output)}catch{}
|
|
85
|
+
if(temp)try{unlinkSync(temp)}catch{}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export function createTraceRetention({filePath,maxSegments,retentionDays,secureFile}){
|
|
89
|
+
const state={days:retentionDays,droppedRecords:0,droppedBytes:0,
|
|
90
|
+
prunedFiles:0,lastRunAt:null,error:null};
|
|
91
|
+
const prune=()=>{
|
|
92
|
+
const cutoff=Date.now()-retentionDays*24*60*60*1000;
|
|
93
|
+
const paths=[...Array.from({length:maxSegments},(_,i)=>filePath+'.'+(i+1)),filePath];
|
|
94
|
+
state.error=null;
|
|
95
|
+
for(const path of paths){
|
|
96
|
+
try{
|
|
97
|
+
const result=pruneFile(path,cutoff,secureFile);
|
|
98
|
+
state.droppedRecords+=result.droppedRecords;
|
|
99
|
+
state.droppedBytes+=result.droppedBytes;
|
|
100
|
+
if(result.pruned)state.prunedFiles++;
|
|
101
|
+
}catch(error){state.error=error.code||'TRACE_RETENTION_FAILED';}
|
|
102
|
+
}
|
|
103
|
+
state.lastRunAt=new Date().toISOString();
|
|
104
|
+
};
|
|
105
|
+
prune();
|
|
106
|
+
const timer=setInterval(prune,24*60*60*1000);
|
|
107
|
+
timer.unref?.();
|
|
108
|
+
return {health:()=>({...state})};
|
|
109
|
+
}
|
|
@@ -2,6 +2,7 @@ import {makeTraceReader} from './trace-reader.mjs';
|
|
|
2
2
|
import {randomUUID} from 'node:crypto';
|
|
3
3
|
import {constants as FS,closeSync,fstatSync,lstatSync,openSync,writeSync,renameSync,unlinkSync} from 'node:fs';
|
|
4
4
|
import {dirname,isAbsolute} from 'node:path';
|
|
5
|
+
import {createTraceRetention} from './trace-retention.mjs';
|
|
5
6
|
|
|
6
7
|
export const TRACE_SCHEMA_VERSION=2;
|
|
7
8
|
const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
@@ -138,13 +139,16 @@ function secureFile(filePath){
|
|
|
138
139
|
return st;
|
|
139
140
|
}
|
|
140
141
|
export function createTraceWriter({
|
|
141
|
-
filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5
|
|
142
|
+
filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5,
|
|
143
|
+
retentionDays=30
|
|
142
144
|
}){
|
|
143
145
|
if(typeof enableRotation!=='boolean'||!Number.isSafeInteger(rotateBytes)||
|
|
144
146
|
rotateBytes<512||rotateBytes>10*1024*1024||
|
|
145
|
-
!Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5
|
|
147
|
+
!Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5||
|
|
148
|
+
!Number.isSafeInteger(retentionDays)||retentionDays<1||retentionDays>3650)
|
|
146
149
|
throw fail('TRACE_ROTATION_INVALID');
|
|
147
150
|
const epoch=randomUUID();let seq=0,failures=0,lastError=null,rotations=0;
|
|
151
|
+
const retention=createTraceRetention({filePath,maxSegments,retentionDays,secureFile});
|
|
148
152
|
const rotateIfNeeded=lineBytes=>{
|
|
149
153
|
// Legacy data is never moved until an operator explicitly enables
|
|
150
154
|
// rotation after preserving its historical evidence.
|
|
@@ -190,9 +194,12 @@ export function createTraceWriter({
|
|
|
190
194
|
{errorCode:detail.errorCode}:{})
|
|
191
195
|
});
|
|
192
196
|
};
|
|
193
|
-
const health=()=>
|
|
194
|
-
|
|
195
|
-
|
|
197
|
+
const health=()=>{
|
|
198
|
+
const retained=retention.health();
|
|
199
|
+
return {status:lastError||retained.error?'TRACE_DEGRADED':'OK',
|
|
200
|
+
errorCode:lastError||retained.error,failures,writerEpoch:epoch,writerSeq:seq,
|
|
201
|
+
rotationEnabled:enableRotation,rotations,retention:retained};
|
|
202
|
+
};
|
|
196
203
|
return {record,recordControl,health};
|
|
197
204
|
}
|
|
198
205
|
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.9.
|
|
6
|
+
"version": "0.9.24",
|
|
7
7
|
"type": "module",
|
|
8
8
|
"description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
|
|
9
9
|
"bin": {
|
|
@@ -31,11 +31,11 @@
|
|
|
31
31
|
"prepack": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check"
|
|
32
32
|
},
|
|
33
33
|
"dependencies": {
|
|
34
|
-
"@tomflow/chatloop-context": "0.6.
|
|
35
|
-
"@tomflow/chatloop-trace": "0.4.
|
|
34
|
+
"@tomflow/chatloop-context": "0.6.12",
|
|
35
|
+
"@tomflow/chatloop-trace": "0.4.5",
|
|
36
36
|
"@wonderwhy-er/desktop-commander": "0.2.44",
|
|
37
37
|
"ps-list": "9.0.0",
|
|
38
|
-
"@tomflow/chatloop-extension": "0.4.
|
|
38
|
+
"@tomflow/chatloop-extension": "0.4.12"
|
|
39
39
|
},
|
|
40
40
|
"bundleDependencies": [
|
|
41
41
|
"@tomflow/chatloop-context",
|
|
@@ -47,8 +47,8 @@
|
|
|
47
47
|
"node": ">=24"
|
|
48
48
|
},
|
|
49
49
|
"optionalDependencies": {
|
|
50
|
-
"@tomflow/chatloop-tunnel-darwin-arm64": "0.0.
|
|
51
|
-
"@tomflow/chatloop-tunnel-darwin-x64": "0.0.
|
|
50
|
+
"@tomflow/chatloop-tunnel-darwin-arm64": "0.0.25",
|
|
51
|
+
"@tomflow/chatloop-tunnel-darwin-x64": "0.0.25"
|
|
52
52
|
},
|
|
53
53
|
"exports": {
|
|
54
54
|
".": "./index.mjs"
|
package/providers/form.mjs
CHANGED
|
@@ -1,147 +1,180 @@
|
|
|
1
|
-
//
|
|
1
|
+
// Stateless generic single-select form service; business meaning belongs to callers.
|
|
2
2
|
import {randomUUID} from 'node:crypto';
|
|
3
3
|
import {readFileSync} from 'node:fs';
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const
|
|
4
|
+
|
|
5
|
+
const RESOURCE_URI='ui://chat-loop/form/v3';
|
|
6
|
+
const LEGACY_RESOURCE_URIS=['ui://chat-loop/form/review-v2','ui://chat-loop/form/review-v1'];
|
|
7
7
|
const RESOURCE_MIME='text/html;profile=mcp-app';
|
|
8
8
|
const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
9
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;
|
|
10
10
|
const fail=code=>Object.assign(Error(code),{code});
|
|
11
11
|
const ok=value=>({content:[{type:'text',text:JSON.stringify(value)}],
|
|
12
12
|
structuredContent:value});
|
|
13
|
-
const filled=(
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
13
|
+
const filled=(value,max)=>typeof value==='string'
|
|
14
|
+
&&value.trim().length>0&&value.length<=max;
|
|
15
|
+
const shape=(value,fields)=>value&&typeof value==='object'
|
|
16
|
+
&&!Array.isArray(value)&&Object.keys(value).every(key=>fields.includes(key));
|
|
17
|
+
const CARD=['title','description','options','submitLabel','footer','textInput'];
|
|
18
|
+
const REQUIRED_CARD=['title','description','options','submitLabel'];
|
|
19
|
+
const OPTION=['value','label'];
|
|
20
|
+
const TEXT_INPUT=['label','placeholder','showWhen','requiredWhen','maxLength','rows'];
|
|
18
21
|
const PREP=['formId','card'];
|
|
19
|
-
const SUBMIT=['formId','traceRef','
|
|
20
|
-
const
|
|
21
|
-
properties:
|
|
22
|
-
|
|
22
|
+
const SUBMIT=['formId','traceRef','selection','input'];
|
|
23
|
+
const optionSchema={type:'object',additionalProperties:false,required:OPTION,
|
|
24
|
+
properties:{
|
|
25
|
+
value:{type:'string',minLength:1,maxLength:80},
|
|
26
|
+
label:{type:'string',minLength:1,maxLength:180}
|
|
27
|
+
}};
|
|
28
|
+
const textInputSchema={type:'object',additionalProperties:false,
|
|
29
|
+
required:['label','placeholder'],properties:{
|
|
30
|
+
label:{type:'string',minLength:1,maxLength:180},
|
|
31
|
+
placeholder:{type:'string',minLength:1,maxLength:180},
|
|
32
|
+
showWhen:{type:'array',minItems:1,maxItems:32,
|
|
33
|
+
items:{type:'string',minLength:1,maxLength:80}},
|
|
34
|
+
requiredWhen:{type:'array',minItems:1,maxItems:32,
|
|
35
|
+
items:{type:'string',minLength:1,maxLength:80}},
|
|
36
|
+
maxLength:{type:'integer',minimum:1,maximum:4000},
|
|
37
|
+
rows:{type:'integer',minimum:1,maximum:12}
|
|
38
|
+
}};
|
|
39
|
+
const cardSchema={type:'object',additionalProperties:false,required:REQUIRED_CARD,
|
|
40
|
+
properties:{
|
|
41
|
+
title:{type:'string',minLength:1,maxLength:180},
|
|
42
|
+
description:{type:'string',minLength:1,maxLength:1200},
|
|
43
|
+
options:{type:'array',minItems:1,maxItems:32,items:optionSchema},
|
|
44
|
+
submitLabel:{type:'string',minLength:1,maxLength:180},
|
|
45
|
+
footer:{type:'string',maxLength:1200},
|
|
46
|
+
textInput:textInputSchema
|
|
47
|
+
}};
|
|
23
48
|
const tools=[
|
|
24
49
|
{name:'chat_loop_form__prepare',description:
|
|
25
|
-
'Render a
|
|
50
|
+
'Render a generic single-select form with caller-defined options and optional text input. Preserve an optional caller-supplied formId or generate a UUID; return an opaque traceRef for log correlation. No business workflow or approval state is owned here.',
|
|
26
51
|
inputSchema:{type:'object',additionalProperties:false,required:['card'],
|
|
27
52
|
properties:{formId:{type:'string',pattern:FORM_ID.source},card:cardSchema}},
|
|
28
53
|
annotations:{readOnlyHint:false},
|
|
29
54
|
_meta:{ui:{resourceUri:RESOURCE_URI,visibility:['model','app']},
|
|
30
55
|
'openai/outputTemplate':RESOURCE_URI,'openai/widgetAccessible':true}},
|
|
31
56
|
{name:'chat_loop_form__submit',description:
|
|
32
|
-
'
|
|
57
|
+
'Return the selected caller-defined option and optional text input for a prepared form. Requires its formId and traceRef for correlation. The caller owns all business interpretation and follow-up; this tool does not send Chat messages.',
|
|
33
58
|
inputSchema:{type:'object',additionalProperties:false,
|
|
34
|
-
required:['formId','traceRef','
|
|
35
|
-
properties:{
|
|
59
|
+
required:['formId','traceRef','selection'],
|
|
60
|
+
properties:{
|
|
61
|
+
formId:{type:'string',pattern:FORM_ID.source},
|
|
36
62
|
traceRef:{type:'string',pattern:UUID.source},
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
63
|
+
selection:{type:'object',additionalProperties:false,required:OPTION,
|
|
64
|
+
properties:optionSchema.properties},
|
|
65
|
+
input:{type:'string',maxLength:4000}
|
|
66
|
+
}},
|
|
67
|
+
annotations:{readOnlyHint:false},_meta:{ui:{visibility:['model','app']},
|
|
68
|
+
'openai/widgetAccessible':true}}
|
|
41
69
|
];
|
|
42
|
-
function check(
|
|
43
|
-
if(!shape(
|
|
44
|
-
||
|
|
70
|
+
function check(args,fields){
|
|
71
|
+
if(!shape(args,fields)
|
|
72
|
+
||args.formId!==undefined&&(typeof args.formId!=='string'||!FORM_ID.test(args.formId)))
|
|
45
73
|
throw fail('FORM_INVALID_ARGUMENT');
|
|
46
74
|
}
|
|
47
|
-
function checkCard(
|
|
48
|
-
|
|
75
|
+
function checkCard(args){
|
|
76
|
+
const card=args.card;
|
|
77
|
+
if(!shape(card,CARD)||REQUIRED_CARD.some(key=>!Object.hasOwn(card,key))
|
|
78
|
+
||!filled(card.title,180)||!filled(card.description,1200)
|
|
79
|
+
||!filled(card.submitLabel,180)
|
|
80
|
+
||card.footer!==undefined&&typeof card.footer!=='string'
|
|
81
|
+
||card.footer?.length>1200)
|
|
49
82
|
throw fail('FORM_CARD_INVALID');
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
83
|
+
if(!Array.isArray(card.options)||card.options.length<1||card.options.length>32)
|
|
84
|
+
throw fail('FORM_OPTIONS_INVALID');
|
|
85
|
+
const values=new Set();
|
|
86
|
+
for(const option of card.options){
|
|
87
|
+
if(!shape(option,OPTION)||OPTION.some(key=>!Object.hasOwn(option,key))
|
|
88
|
+
||!filled(option.value,80)||!filled(option.label,180)
|
|
89
|
+
||values.has(option.value))throw fail('FORM_OPTIONS_INVALID');
|
|
90
|
+
values.add(option.value);
|
|
91
|
+
}
|
|
92
|
+
if(card.textInput!==undefined){
|
|
93
|
+
const field=card.textInput;
|
|
94
|
+
if(!shape(field,TEXT_INPUT)||!filled(field.label,180)
|
|
95
|
+
||!filled(field.placeholder,180)
|
|
96
|
+
||field.maxLength!==undefined&&(!Number.isInteger(field.maxLength)
|
|
97
|
+
||field.maxLength<1||field.maxLength>4000)
|
|
98
|
+
||field.rows!==undefined&&(!Number.isInteger(field.rows)
|
|
99
|
+
||field.rows<1||field.rows>12))throw fail('FORM_TEXT_INPUT_INVALID');
|
|
100
|
+
for(const key of ['showWhen','requiredWhen']){
|
|
101
|
+
const list=field[key];
|
|
102
|
+
if(list!==undefined&&(!Array.isArray(list)||!list.length
|
|
103
|
+
||new Set(list).size!==list.length
|
|
104
|
+
||list.some(value=>typeof value!=='string'||!values.has(value))))
|
|
105
|
+
throw fail('FORM_TEXT_INPUT_INVALID');
|
|
106
|
+
}
|
|
107
|
+
const shown=new Set(field.showWhen??[...values]);
|
|
108
|
+
if((field.requiredWhen??[]).some(value=>!shown.has(value)))
|
|
109
|
+
throw fail('FORM_TEXT_INPUT_INVALID');
|
|
53
110
|
}
|
|
54
|
-
if(!/^A\s*[—-]/.test(a.card.confirmLabel)
|
|
55
|
-
||!/^B\s*[—-]/.test(a.card.modifyLabel))
|
|
56
|
-
throw fail('FORM_CARD_LAYOUT_INVALID');
|
|
57
|
-
}
|
|
58
|
-
function view(a,formId){
|
|
59
|
-
return {template:'chat-loop-review-card-v1',formId,
|
|
60
|
-
layout:{card:'rounded-border',radiusPx:12,paddingPx:12,gapPx:12,
|
|
61
|
-
direction:'column',optionDirection:'column',buttonWidth:'full',
|
|
62
|
-
buttonShape:'pill'},
|
|
63
|
-
title:a.card.title,description:a.card.description,
|
|
64
|
-
options:[{value:'A',label:a.card.confirmLabel},
|
|
65
|
-
{value:'B',label:a.card.modifyLabel}],
|
|
66
|
-
modifyField:{when:'B',required:true,rows:3,
|
|
67
|
-
placeholder:a.card.modifyPlaceholder},
|
|
68
|
-
submit:{label:a.card.submitLabel,disabledInitially:true,
|
|
69
|
-
singleClickLock:true,issueNewUserTurn:true},
|
|
70
|
-
footer:a.card.footer};
|
|
71
111
|
}
|
|
72
|
-
function
|
|
73
|
-
const
|
|
74
|
-
return
|
|
75
|
-
|
|
112
|
+
function view(args,formId){
|
|
113
|
+
const card=args.card,field=card.textInput;
|
|
114
|
+
return {template:'chat-loop-form-v1',formId,
|
|
115
|
+
title:card.title,description:card.description,
|
|
116
|
+
options:card.options.map(option=>({value:option.value,label:option.label})),
|
|
117
|
+
textInput:field?{
|
|
118
|
+
label:field.label,placeholder:field.placeholder,
|
|
119
|
+
showWhen:field.showWhen??card.options.map(option=>option.value),
|
|
120
|
+
requiredWhen:field.requiredWhen??[],
|
|
121
|
+
maxLength:field.maxLength??4000,rows:field.rows??4
|
|
122
|
+
}:null,
|
|
123
|
+
submitLabel:card.submitLabel,footer:card.footer??''};
|
|
76
124
|
}
|
|
77
|
-
async function observeForm(form,event,formId,traceRef,
|
|
125
|
+
async function observeForm(form,event,formId,traceRef,errorCode){
|
|
78
126
|
if(typeof form?.observe!=='function'||!FORM_ID.test(formId||'')
|
|
79
127
|
||!UUID.test(traceRef||''))return false;
|
|
80
|
-
if(!parent){
|
|
81
|
-
form?.lost?.();
|
|
82
|
-
return false;
|
|
83
|
-
}
|
|
84
128
|
try{
|
|
85
129
|
const result=await form.observe({
|
|
86
|
-
event,formId,traceRef,status
|
|
130
|
+
event,formId,traceRef,status:errorCode?'FAILED':'CONFIRMED',
|
|
131
|
+
...(errorCode?{errorCode}:{})
|
|
87
132
|
});
|
|
88
133
|
if(result?.status!=='OK'||!UUID.test(result.eventId||'')){
|
|
89
|
-
form?.lost?.();
|
|
90
|
-
return false;
|
|
134
|
+
form?.lost?.();return false;
|
|
91
135
|
}
|
|
92
136
|
return true;
|
|
93
|
-
}catch{
|
|
94
|
-
form?.lost?.();
|
|
95
|
-
return false;
|
|
96
|
-
}
|
|
137
|
+
}catch{form?.lost?.();return false}
|
|
97
138
|
}
|
|
98
|
-
function prepare(
|
|
99
|
-
const formId=
|
|
139
|
+
function prepare(args){
|
|
140
|
+
const formId=args?.formId===undefined?randomUUID():args.formId;
|
|
100
141
|
const traceRef=randomUUID();
|
|
101
|
-
try{check(
|
|
142
|
+
try{check(args,PREP);checkCard(args)}
|
|
102
143
|
catch(error){
|
|
103
|
-
error.formId=typeof formId==='string'&&FORM_ID.test(formId)
|
|
104
|
-
?formId:randomUUID();
|
|
144
|
+
error.formId=typeof formId==='string'&&FORM_ID.test(formId)?formId:randomUUID();
|
|
105
145
|
error.traceRef=traceRef;
|
|
106
146
|
throw error;
|
|
107
147
|
}
|
|
108
|
-
return {status:'FORM_PREPARED',formId,traceRef,view:view(
|
|
148
|
+
return {status:'FORM_PREPARED',formId,traceRef,view:view(args,formId)};
|
|
109
149
|
}
|
|
110
|
-
function validateSubmit(
|
|
111
|
-
check(
|
|
112
|
-
if(typeof
|
|
113
|
-
||typeof
|
|
114
|
-
||!
|
|
150
|
+
function validateSubmit(args){
|
|
151
|
+
check(args,SUBMIT);
|
|
152
|
+
if(typeof args.formId!=='string'||!FORM_ID.test(args.formId)
|
|
153
|
+
||typeof args.traceRef!=='string'||!UUID.test(args.traceRef)
|
|
154
|
+
||!shape(args.selection,OPTION)
|
|
155
|
+
||OPTION.some(key=>!filled(args.selection[key],key==='value'?80:180))
|
|
156
|
+
||args.input!==undefined&&(typeof args.input!=='string'||args.input.length>4000))
|
|
115
157
|
throw fail('FORM_SUBMISSION_INVALID');
|
|
116
|
-
if(a.choice==='B'&&!filled(a.comment,4000)
|
|
117
|
-
||a.choice==='A'&&a.comment!==undefined&&a.comment!=='')
|
|
118
|
-
throw fail('FORM_COMMENT_INVALID');
|
|
119
158
|
}
|
|
120
|
-
|
|
121
|
-
validateSubmit(
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
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}:{})};
|
|
159
|
+
function submit(args){
|
|
160
|
+
validateSubmit(args);
|
|
161
|
+
return {status:'FORM_SUBMITTED',formId:args.formId,traceRef:args.traceRef,
|
|
162
|
+
selection:{value:args.selection.value,label:args.selection.label},
|
|
163
|
+
...(args.input!==undefined?{input:args.input}:{})};
|
|
131
164
|
}
|
|
132
165
|
export const provider=Object.freeze({
|
|
133
|
-
id:'form',order:5,names:tools.map(
|
|
166
|
+
id:'form',order:5,names:tools.map(tool=>tool.name),
|
|
134
167
|
create({form}={}){
|
|
135
|
-
//
|
|
136
|
-
//
|
|
168
|
+
// No caller identity, prepared-form registry, expiry, business state or
|
|
169
|
+
// process-local lifecycle. Only opaque IDs correlate data with Trace.
|
|
137
170
|
return Object.freeze({
|
|
138
171
|
tools:()=>tools,
|
|
139
|
-
resources:()=>[RESOURCE_URI
|
|
172
|
+
resources:()=>[RESOURCE_URI,...LEGACY_RESOURCE_URIS].map(uri=>({
|
|
140
173
|
uri,name:'Chat Loop Form',mimeType:RESOURCE_MIME,
|
|
141
|
-
description:'
|
|
174
|
+
description:'Generic single-select form UI'
|
|
142
175
|
})),
|
|
143
176
|
async readResource(uri){
|
|
144
|
-
if(uri!==RESOURCE_URI
|
|
177
|
+
if(uri!==RESOURCE_URI&&!LEGACY_RESOURCE_URIS.includes(uri))
|
|
145
178
|
throw fail('MCP_RESOURCE_NOT_FOUND');
|
|
146
179
|
return {contents:[{uri,mimeType:RESOURCE_MIME,
|
|
147
180
|
text:readFileSync(new URL('../ui/form/review.html',import.meta.url),'utf8'),
|
|
@@ -149,23 +182,22 @@ export const provider=Object.freeze({
|
|
|
149
182
|
preferredDisplayMode:'inline'}}}]};
|
|
150
183
|
},
|
|
151
184
|
async call(name,args){
|
|
152
|
-
const isPrepare=name===tools[0].name;
|
|
153
|
-
const isSubmit=name===tools[1].name;
|
|
185
|
+
const isPrepare=name===tools[0].name,isSubmit=name===tools[1].name;
|
|
154
186
|
if(!isPrepare&&!isSubmit)throw fail('UNKNOWN_TOOL');
|
|
155
|
-
const parent=trace(form);
|
|
156
187
|
const formId=typeof args?.formId==='string'?args.formId:null;
|
|
157
188
|
const traceRef=typeof args?.traceRef==='string'?args.traceRef:null;
|
|
158
189
|
try{
|
|
159
|
-
const result=isPrepare?prepare(args):
|
|
160
|
-
|
|
190
|
+
const result=isPrepare?prepare(args):submit(args);
|
|
191
|
+
// Trace is soft and never delays or alters the returned Form data.
|
|
192
|
+
void observeForm(form,
|
|
161
193
|
isPrepare?'form.prepared.soft_observed':'form.submitted.soft_observed',
|
|
162
|
-
result.formId,result.traceRef
|
|
194
|
+
result.formId,result.traceRef);
|
|
163
195
|
return ok(result);
|
|
164
|
-
}catch(
|
|
165
|
-
|
|
196
|
+
}catch(error){
|
|
197
|
+
void observeForm(form,
|
|
166
198
|
isPrepare?'form.prepared.failed':'form.submitted.failed',
|
|
167
|
-
|
|
168
|
-
throw
|
|
199
|
+
error.formId||formId,error.traceRef||traceRef,error.code||'FORM_FAILED');
|
|
200
|
+
throw error;
|
|
169
201
|
}
|
|
170
202
|
}
|
|
171
203
|
});
|
package/ui/form/review-app.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
// Minimal MCP Apps View bridge:
|
|
2
|
-
// Protocol: https://modelcontextprotocol.io/extensions/apps
|
|
3
|
-
// The Form service only renders, collects and returns user selections.
|
|
1
|
+
// Minimal MCP Apps View bridge: render generic options and return the Submit tool result.
|
|
4
2
|
const $=id=>document.getElementById(id);
|
|
5
|
-
const options=[...document.querySelectorAll('input[name="choice"]')];
|
|
6
3
|
const idPattern=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
7
4
|
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;
|
|
8
5
|
const requests=new Map();
|
|
@@ -17,8 +14,7 @@ function call(method,params){
|
|
|
17
14
|
if(!connected)throw Error('FORM_APP_NOT_INITIALIZED');
|
|
18
15
|
return new Promise((resolve,reject)=>{
|
|
19
16
|
const id=++seq;
|
|
20
|
-
// Transport
|
|
21
|
-
// A timeout never authorizes a retry of a write.
|
|
17
|
+
// Transport wait only: this does not expire the prepared form.
|
|
22
18
|
const timer=setTimeout(()=>{
|
|
23
19
|
requests.delete(id);reject(Error('FORM_APP_REPLY_UNKNOWN'));
|
|
24
20
|
},30000);
|
|
@@ -28,48 +24,83 @@ function call(method,params){
|
|
|
28
24
|
}
|
|
29
25
|
function decode(result){
|
|
30
26
|
if(result?.isError){
|
|
31
|
-
const code=result.content?.find(
|
|
32
|
-
throw Error(typeof code==='string'
|
|
33
|
-
|
|
27
|
+
const code=result.content?.find(item=>item.type==='text')?.text;
|
|
28
|
+
throw Error(typeof code==='string'&&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)
|
|
29
|
+
?code:'FORM_TOOL_REJECTED');
|
|
34
30
|
}
|
|
35
31
|
if(result?.structuredContent?.status)return result.structuredContent;
|
|
36
|
-
const text=result?.content?.find(
|
|
32
|
+
const text=result?.content?.find(item=>item.type==='text')?.text;
|
|
37
33
|
if(typeof text!=='string'||text.length>20000)throw Error('FORM_RECEIPT_MISSING');
|
|
38
34
|
return JSON.parse(text);
|
|
39
35
|
}
|
|
40
|
-
const
|
|
36
|
+
const radios=()=>[...document.querySelectorAll('input[name="choice"]')];
|
|
37
|
+
const selected=()=>radios().find(item=>item.checked)?.value||null;
|
|
38
|
+
function selectedOption(){
|
|
39
|
+
const value=selected();
|
|
40
|
+
return prepared?.view.options.find(option=>option.value===value)||null;
|
|
41
|
+
}
|
|
42
|
+
function inputVisible(option){
|
|
43
|
+
const config=prepared?.view.textInput;
|
|
44
|
+
return Boolean(config&&option&&config.showWhen.includes(option.value));
|
|
45
|
+
}
|
|
46
|
+
function inputRequired(option){
|
|
47
|
+
const config=prepared?.view.textInput;
|
|
48
|
+
return Boolean(config&&option&&config.requiredWhen.includes(option.value));
|
|
49
|
+
}
|
|
41
50
|
function update(){
|
|
42
|
-
const
|
|
51
|
+
const option=selectedOption(),visible=inputVisible(option);
|
|
43
52
|
$('options').disabled=!connected;
|
|
44
|
-
$('
|
|
45
|
-
|
|
46
|
-
|
|
53
|
+
$('text-input').hidden=!visible;
|
|
54
|
+
const text=$('input').value.trim();
|
|
55
|
+
$('submit').disabled=!connected||!prepared||locked||!option
|
|
56
|
+
||(visible&&inputRequired(option)&&!text);
|
|
47
57
|
resize();
|
|
48
58
|
}
|
|
49
59
|
function render(value){
|
|
50
|
-
const view=value?.view;
|
|
51
|
-
if(!view||view.template!=='chat-loop-
|
|
60
|
+
const view=value?.view,options=view?.options;
|
|
61
|
+
if(!view||view.template!=='chat-loop-form-v1'
|
|
52
62
|
||typeof value.formId!=='string'||!idPattern.test(value.formId)
|
|
53
63
|
||typeof value.traceRef!=='string'||!tracePattern.test(value.traceRef)
|
|
54
|
-
||view.formId!==value.formId
|
|
55
|
-
||
|
|
56
|
-
||
|
|
64
|
+
||view.formId!==value.formId||!Array.isArray(options)
|
|
65
|
+
||options.length<1||options.length>32
|
|
66
|
+
||options.some(option=>!option||typeof option.value!=='string'
|
|
67
|
+
||!option.value.trim()||typeof option.label!=='string'||!option.label.trim())
|
|
68
|
+
||new Set(options.map(option=>option.value)).size!==options.length)
|
|
69
|
+
throw Error('FORM_VIEW_INVALID');
|
|
70
|
+
const field=view.textInput;
|
|
71
|
+
if(field&&(!Array.isArray(field.showWhen)||!Array.isArray(field.requiredWhen)
|
|
72
|
+
||field.requiredWhen.some(option=>!field.showWhen.includes(option))))
|
|
57
73
|
throw Error('FORM_VIEW_INVALID');
|
|
58
74
|
const preserveLock=prepared?.formId===value.formId
|
|
59
75
|
&&prepared?.traceRef===value.traceRef&&locked;
|
|
60
76
|
prepared=value;
|
|
61
77
|
$('title').textContent=view.title;
|
|
62
78
|
$('description').textContent=view.description;
|
|
63
|
-
$('
|
|
64
|
-
$('b-label').textContent=view.options[1].label;
|
|
65
|
-
$('comment').placeholder=view.modifyField?.placeholder||'填写修改意见';
|
|
66
|
-
$('submit').textContent=view.submit?.label||'提交';
|
|
79
|
+
$('submit').textContent=view.submitLabel||'提交';
|
|
67
80
|
$('footer').textContent=view.footer||'';
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
options
|
|
81
|
+
const list=$('option-list');
|
|
82
|
+
list.replaceChildren();
|
|
83
|
+
for(const option of options){
|
|
84
|
+
const label=document.createElement('label');
|
|
85
|
+
label.className='option';
|
|
86
|
+
const radio=document.createElement('input');
|
|
87
|
+
radio.type='radio';radio.name='choice';radio.value=option.value;
|
|
88
|
+
radio.addEventListener('change',update);
|
|
89
|
+
const text=document.createElement('span');
|
|
90
|
+
text.textContent=option.label;
|
|
91
|
+
label.append(radio,text);
|
|
92
|
+
list.append(label);
|
|
93
|
+
}
|
|
94
|
+
$('text-label').textContent=field?.label||'补充信息';
|
|
95
|
+
$('input').placeholder=field?.placeholder||'';
|
|
96
|
+
$('input').maxLength=field?.maxLength||4000;
|
|
97
|
+
$('input').rows=field?.rows||4;
|
|
98
|
+
$('text-input').hidden=true;
|
|
99
|
+
$('input').value='';
|
|
71
100
|
locked=preserveLock;
|
|
72
|
-
|
|
101
|
+
$('result').hidden=true;
|
|
102
|
+
$('result').textContent='';
|
|
103
|
+
status(hostFailure||(connected?'表单已准备,请选择一项。':
|
|
73
104
|
'表单已准备,正在等待宿主能力确认。'),
|
|
74
105
|
hostFailure?'error':connected?'ok':'info');
|
|
75
106
|
update();
|
|
@@ -82,7 +113,7 @@ function receive(event){
|
|
|
82
113
|
const request=requests.get(message.id);
|
|
83
114
|
if(!request)return;
|
|
84
115
|
requests.delete(message.id);clearTimeout(request.timer);
|
|
85
|
-
if(message.error)request.reject(Error('
|
|
116
|
+
if(message.error)request.reject(Error('FORM_APP_REPLY_UNKNOWN'));
|
|
86
117
|
else request.resolve(message.result);
|
|
87
118
|
return;
|
|
88
119
|
}
|
|
@@ -115,25 +146,19 @@ async function initialize(){
|
|
|
115
146
|
},12000);
|
|
116
147
|
requests.set(id,{resolve,reject,timer});
|
|
117
148
|
send({id,method:'ui/initialize',params:{
|
|
118
|
-
appInfo:{name:'Chat Loop
|
|
119
|
-
appCapabilities:{},
|
|
120
|
-
protocolVersion:'2026-01-26'
|
|
149
|
+
appInfo:{name:'Chat Loop Form',version:'1.1.0'},
|
|
150
|
+
appCapabilities:{},protocolVersion:'2026-01-26'
|
|
121
151
|
}});
|
|
122
152
|
});
|
|
123
153
|
try{
|
|
124
154
|
const response=await init;
|
|
125
155
|
if(!response?.protocolVersion||!response.hostInfo
|
|
126
|
-
||!response.hostCapabilities)
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
hostFailure='当前宿主缺少 serverTools 或 message.text 能力,表单不可提交。';
|
|
131
|
-
status(hostFailure,'error');
|
|
132
|
-
update();
|
|
133
|
-
return;
|
|
156
|
+
||!response.hostCapabilities)throw Error('FORM_APP_INIT_INVALID');
|
|
157
|
+
if(!response.hostCapabilities.serverTools){
|
|
158
|
+
hostFailure='当前宿主缺少 serverTools 能力,表单不可提交。';
|
|
159
|
+
status(hostFailure,'error');update();return;
|
|
134
160
|
}
|
|
135
|
-
connected=true;
|
|
136
|
-
hostFailure=null;
|
|
161
|
+
connected=true;hostFailure=null;
|
|
137
162
|
notify('ui/notifications/initialized',{});
|
|
138
163
|
resize();
|
|
139
164
|
if(toolResult)render(decode(toolResult));
|
|
@@ -141,54 +166,44 @@ async function initialize(){
|
|
|
141
166
|
new ResizeObserver(resize).observe(document.documentElement);
|
|
142
167
|
}catch{
|
|
143
168
|
hostFailure='MCP App 初始化失败,请核查宿主连接与协议能力。';
|
|
144
|
-
status(hostFailure,'error');
|
|
145
|
-
connected=false;
|
|
146
|
-
update();
|
|
169
|
+
status(hostFailure,'error');connected=false;update();
|
|
147
170
|
}
|
|
148
171
|
}
|
|
149
172
|
async function submit(){
|
|
150
173
|
if(!connected||locked||!prepared)return;
|
|
151
|
-
const
|
|
152
|
-
if(!
|
|
174
|
+
const option=selectedOption();
|
|
175
|
+
if(!option)return;
|
|
176
|
+
const visible=inputVisible(option),input=$('input').value.trim();
|
|
177
|
+
if(visible&&inputRequired(option)&&!input)return;
|
|
153
178
|
locked=true;update();
|
|
154
179
|
const {formId,traceRef}=prepared;
|
|
155
|
-
const args={formId,traceRef,
|
|
180
|
+
const args={formId,traceRef,
|
|
181
|
+
selection:{value:option.value,label:option.label},
|
|
182
|
+
...(visible&&input?{input}:{})};
|
|
156
183
|
status('正在提交表单…');
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
184
|
+
try{
|
|
185
|
+
const receipt=decode(await call('tools/call',{
|
|
186
|
+
name:'chat_loop_form__submit',arguments:args
|
|
187
|
+
}));
|
|
188
|
+
if(receipt.status!=='FORM_SUBMITTED'||receipt.formId!==formId
|
|
189
|
+
||receipt.traceRef!==traceRef
|
|
190
|
+
||receipt.selection?.value!==option.value
|
|
191
|
+
||receipt.selection?.label!==option.label){
|
|
192
|
+
status('Submit 返回的数据与当前表单不匹配。','error');return;
|
|
193
|
+
}
|
|
194
|
+
$('result').textContent=JSON.stringify(receipt,null,2);
|
|
195
|
+
$('result').hidden=false;
|
|
196
|
+
status('提交成功,表单数据已返回。','ok');
|
|
197
|
+
}catch(error){
|
|
162
198
|
const code=typeof error?.message==='string'
|
|
163
199
|
&&/^[A-Z][A-Z0-9_]{1,95}$/.test(error.message)
|
|
164
200
|
?error.message:'FORM_APP_REPLY_UNKNOWN';
|
|
165
|
-
status(code==='FORM_APP_REPLY_UNKNOWN'
|
|
166
|
-
?'
|
|
167
|
-
:code
|
|
168
|
-
?'该表单已提交过,禁止重复发送;请核查原消息。'
|
|
169
|
-
:'Submit 明确失败('+code+'),用户消息未发送。','error');
|
|
170
|
-
return;
|
|
201
|
+
status(code==='FORM_APP_REPLY_UNKNOWN'
|
|
202
|
+
?'提交结果未知;已锁定当前表单,请核查原请求回执。'
|
|
203
|
+
:'提交失败('+code+')。','error');
|
|
171
204
|
}
|
|
172
|
-
if(receipt.status!=='FORM_SUBMITTED'
|
|
173
|
-
||receipt.formId!==formId||receipt.traceRef!==traceRef
|
|
174
|
-
||receipt.choice!==choice){
|
|
175
|
-
status('Submit 返回的信息与当前表单不匹配,用户消息未发送。','error');
|
|
176
|
-
return;
|
|
177
|
-
}
|
|
178
|
-
const text='【Chat Loop Form】formId='+formId+'|'
|
|
179
|
-
+(choice==='A'?'A 选择':'B 选择:'+comment)+'。';
|
|
180
|
-
status('单次提交已锁定,正在申请当前 Chat 用户消息…');
|
|
181
|
-
try{
|
|
182
|
-
const result=await call('ui/message',{
|
|
183
|
-
role:'user',content:[{type:'text',text}]
|
|
184
|
-
});
|
|
185
|
-
status(result?.isError?'宿主未接受表单结果消息。':
|
|
186
|
-
'宿主已接受用户消息请求;平台消息身份仍需独立核验。',
|
|
187
|
-
result?.isError?'error':'ok');
|
|
188
|
-
}catch{status('用户消息发送状态未知,已锁定,禁止重试;请核查原消息。','error')}
|
|
189
205
|
}
|
|
190
206
|
window.addEventListener('message',receive);
|
|
191
|
-
|
|
192
|
-
$('comment').addEventListener('input',update);
|
|
207
|
+
$('input').addEventListener('input',update);
|
|
193
208
|
$('submit').addEventListener('click',submit);
|
|
194
209
|
void initialize();
|
package/ui/form/review.html
CHANGED
|
@@ -16,13 +16,14 @@ fieldset{border:0;padding:0;margin:8px 0}
|
|
|
16
16
|
label.option{display:flex;align-items:center;gap:10px;padding:10px 8px;cursor:pointer}
|
|
17
17
|
label.option+label.option{border-top:1px solid #aaa3}
|
|
18
18
|
input[type=radio]{width:18px;height:18px;accent-color:#2675bf}
|
|
19
|
-
textarea{width:100%;min-height:
|
|
19
|
+
textarea{width:100%;min-height:72px;padding:10px;font:inherit;resize:vertical;border:1px solid #aaa8;border-radius:9px;background:transparent;color:inherit}
|
|
20
20
|
button{width:100%;margin:12px 0;padding:10px 12px;border:0;border-radius:24px;background:#186ac1;color:white;font:inherit;cursor:pointer}
|
|
21
21
|
button:disabled{opacity:.44;cursor:not-allowed}
|
|
22
22
|
[hidden]{display:none!important}
|
|
23
23
|
#status{font-size:12px;white-space:pre-wrap;overflow-wrap:anywhere}
|
|
24
24
|
#status[data-state=error]{color:#bf3030}
|
|
25
25
|
#status[data-state=ok]{color:#247d48}
|
|
26
|
+
#result{font:12px/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere}
|
|
26
27
|
@media(prefers-color-scheme:dark){button{background:#4295e8}textarea{border-color:#888}}
|
|
27
28
|
</style>
|
|
28
29
|
</head>
|
|
@@ -32,15 +33,18 @@ button:disabled{opacity:.44;cursor:not-allowed}
|
|
|
32
33
|
<p id="description">正在连接表单工具…</p>
|
|
33
34
|
<fieldset id="options" disabled>
|
|
34
35
|
<legend id="legend">请选择一项</legend>
|
|
35
|
-
<
|
|
36
|
-
<label class="option"><input type="radio" name="choice" value="B"><span id="b-label">修改</span></label>
|
|
36
|
+
<div id="option-list"></div>
|
|
37
37
|
</fieldset>
|
|
38
|
-
<div id="
|
|
39
|
-
<
|
|
38
|
+
<div id="text-input" hidden>
|
|
39
|
+
<label id="text-label" for="input">补充信息</label>
|
|
40
|
+
<textarea id="input" maxlength="4000" rows="4"></textarea>
|
|
41
|
+
</div>
|
|
42
|
+
<button id="submit" disabled>提交</button>
|
|
40
43
|
<div id="status" role="status">等待真实 MCP Form prepare 回执</div>
|
|
44
|
+
<pre id="result" hidden></pre>
|
|
41
45
|
<small id="footer"></small>
|
|
42
46
|
</main>
|
|
43
|
-
<script>(()=>{var r=
|
|
47
|
+
<script>(()=>{var r=e=>document.getElementById(e),C=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/,M=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,p=new Map,R=0,l=!1,c=null,w=!1,_=null,u=null;function a(e,t="info"){r("status").textContent=e,r("status").dataset.state=t}function E(e){window.parent.postMessage({jsonrpc:"2.0",...e},"*")}function y(e,t={}){E({method:e,params:t})}function L(e,t){if(!l)throw Error("FORM_APP_NOT_INITIALIZED");return new Promise((n,i)=>{let s=++R,d=setTimeout(()=>{p.delete(s),i(Error("FORM_APP_REPLY_UNKNOWN"))},3e4);p.set(s,{resolve:n,reject:i,timer:d}),E({id:s,method:e,params:t})})}function b(e){if(e?.isError){let n=e.content?.find(i=>i.type==="text")?.text;throw Error(typeof n=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(n)?n:"FORM_TOOL_REJECTED")}if(e?.structuredContent?.status)return e.structuredContent;let t=e?.content?.find(n=>n.type==="text")?.text;if(typeof t!="string"||t.length>2e4)throw Error("FORM_RECEIPT_MISSING");return JSON.parse(t)}var T=()=>[...document.querySelectorAll('input[name="choice"]')],F=()=>T().find(e=>e.checked)?.value||null;function A(){let e=F();return c?.view.options.find(t=>t.value===e)||null}function P(e){let t=c?.view.textInput;return!!(t&&e&&t.showWhen.includes(e.value))}function x(e){let t=c?.view.textInput;return!!(t&&e&&t.requiredWhen.includes(e.value))}function m(){let e=A(),t=P(e);r("options").disabled=!l,r("text-input").hidden=!t;let n=r("input").value.trim();r("submit").disabled=!l||!c||w||!e||t&&x(e)&&!n,I()}function N(e){let t=e?.view,n=t?.options;if(!t||t.template!=="chat-loop-form-v1"||typeof e.formId!="string"||!C.test(e.formId)||typeof e.traceRef!="string"||!M.test(e.traceRef)||t.formId!==e.formId||!Array.isArray(n)||n.length<1||n.length>32||n.some(o=>!o||typeof o.value!="string"||!o.value.trim()||typeof o.label!="string"||!o.label.trim())||new Set(n.map(o=>o.value)).size!==n.length)throw Error("FORM_VIEW_INVALID");let i=t.textInput;if(i&&(!Array.isArray(i.showWhen)||!Array.isArray(i.requiredWhen)||i.requiredWhen.some(o=>!i.showWhen.includes(o))))throw Error("FORM_VIEW_INVALID");let s=c?.formId===e.formId&&c?.traceRef===e.traceRef&&w;c=e,r("title").textContent=t.title,r("description").textContent=t.description,r("submit").textContent=t.submitLabel||"\u63D0\u4EA4",r("footer").textContent=t.footer||"";let d=r("option-list");d.replaceChildren();for(let o of n){let f=document.createElement("label");f.className="option";let h=document.createElement("input");h.type="radio",h.name="choice",h.value=o.value,h.addEventListener("change",m);let g=document.createElement("span");g.textContent=o.label,f.append(h,g),d.append(f)}r("text-label").textContent=i?.label||"\u8865\u5145\u4FE1\u606F",r("input").placeholder=i?.placeholder||"",r("input").maxLength=i?.maxLength||4e3,r("input").rows=i?.rows||4,r("text-input").hidden=!0,r("input").value="",w=s,r("result").hidden=!0,r("result").textContent="",a(u||(l?"\u8868\u5355\u5DF2\u51C6\u5907\uFF0C\u8BF7\u9009\u62E9\u4E00\u9879\u3002":"\u8868\u5355\u5DF2\u51C6\u5907\uFF0C\u6B63\u5728\u7B49\u5F85\u5BBF\u4E3B\u80FD\u529B\u786E\u8BA4\u3002"),u?"error":l?"ok":"info"),m()}function W(e){if(e.source!==window.parent)return;let t=e.data;if(!(!t||t.jsonrpc!=="2.0"||typeof t!="object")){if(Object.hasOwn(t,"id")&&!Object.hasOwn(t,"method")){let n=p.get(t.id);if(!n)return;p.delete(t.id),clearTimeout(n.timer),t.error?n.reject(Error("FORM_APP_REPLY_UNKNOWN")):n.resolve(t.result);return}if(t.method==="ui/notifications/tool-result"){_=t.params;try{N(b(_))}catch{a("Form prepare \u56DE\u6267\u65E0\u6548\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error")}}t.method==="ui/resource-teardown"&&t.id!==void 0&&E({id:t.id,result:{}})}}var v=0,O=0;function I(){if(!l)return;let e=Math.ceil(document.documentElement.scrollHeight),t=Math.ceil(document.documentElement.clientWidth);e===v&&t===O||(v=e,O=t,y("ui/notifications/size-changed",{width:t,height:e}))}async function z(){if(window.parent===window){a("\u672A\u5728 ChatGPT MCP App iframe \u4E2D\u8FD0\u884C\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error");return}let e=++R,t=new Promise((n,i)=>{let s=setTimeout(()=>{p.delete(e),i(Error("FORM_APP_INIT_TIMEOUT"))},12e3);p.set(e,{resolve:n,reject:i,timer:s}),E({id:e,method:"ui/initialize",params:{appInfo:{name:"Chat Loop Form",version:"1.1.0"},appCapabilities:{},protocolVersion:"2026-01-26"}})});try{let n=await t;if(!n?.protocolVersion||!n.hostInfo||!n.hostCapabilities)throw Error("FORM_APP_INIT_INVALID");if(!n.hostCapabilities.serverTools){u="\u5F53\u524D\u5BBF\u4E3B\u7F3A\u5C11 serverTools \u80FD\u529B\uFF0C\u8868\u5355\u4E0D\u53EF\u63D0\u4EA4\u3002",a(u,"error"),m();return}l=!0,u=null,y("ui/notifications/initialized",{}),I(),_&&N(b(_)),typeof ResizeObserver=="function"&&new ResizeObserver(I).observe(document.documentElement)}catch{u="MCP App \u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u6838\u67E5\u5BBF\u4E3B\u8FDE\u63A5\u4E0E\u534F\u8BAE\u80FD\u529B\u3002",a(u,"error"),l=!1,m()}}async function q(){if(!l||w||!c)return;let e=A();if(!e)return;let t=P(e),n=r("input").value.trim();if(t&&x(e)&&!n)return;w=!0,m();let{formId:i,traceRef:s}=c,d={formId:i,traceRef:s,selection:{value:e.value,label:e.label},...t&&n?{input:n}:{}};a("\u6B63\u5728\u63D0\u4EA4\u8868\u5355\u2026");try{let o=b(await L("tools/call",{name:"chat_loop_form__submit",arguments:d}));if(o.status!=="FORM_SUBMITTED"||o.formId!==i||o.traceRef!==s||o.selection?.value!==e.value||o.selection?.label!==e.label){a("Submit \u8FD4\u56DE\u7684\u6570\u636E\u4E0E\u5F53\u524D\u8868\u5355\u4E0D\u5339\u914D\u3002","error");return}r("result").textContent=JSON.stringify(o,null,2),r("result").hidden=!1,a("\u63D0\u4EA4\u6210\u529F\uFF0C\u8868\u5355\u6570\u636E\u5DF2\u8FD4\u56DE\u3002","ok")}catch(o){let f=typeof o?.message=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(o.message)?o.message:"FORM_APP_REPLY_UNKNOWN";a(f==="FORM_APP_REPLY_UNKNOWN"?"\u63D0\u4EA4\u7ED3\u679C\u672A\u77E5\uFF1B\u5DF2\u9501\u5B9A\u5F53\u524D\u8868\u5355\uFF0C\u8BF7\u6838\u67E5\u539F\u8BF7\u6C42\u56DE\u6267\u3002":"\u63D0\u4EA4\u5931\u8D25\uFF08"+f+"\uFF09\u3002","error")}}window.addEventListener("message",W);r("input").addEventListener("input",m);r("submit").addEventListener("click",q);z();})();
|
|
44
48
|
</script>
|
|
45
49
|
</body>
|
|
46
50
|
</html>
|
|
@@ -16,13 +16,14 @@ fieldset{border:0;padding:0;margin:8px 0}
|
|
|
16
16
|
label.option{display:flex;align-items:center;gap:10px;padding:10px 8px;cursor:pointer}
|
|
17
17
|
label.option+label.option{border-top:1px solid #aaa3}
|
|
18
18
|
input[type=radio]{width:18px;height:18px;accent-color:#2675bf}
|
|
19
|
-
textarea{width:100%;min-height:
|
|
19
|
+
textarea{width:100%;min-height:72px;padding:10px;font:inherit;resize:vertical;border:1px solid #aaa8;border-radius:9px;background:transparent;color:inherit}
|
|
20
20
|
button{width:100%;margin:12px 0;padding:10px 12px;border:0;border-radius:24px;background:#186ac1;color:white;font:inherit;cursor:pointer}
|
|
21
21
|
button:disabled{opacity:.44;cursor:not-allowed}
|
|
22
22
|
[hidden]{display:none!important}
|
|
23
23
|
#status{font-size:12px;white-space:pre-wrap;overflow-wrap:anywhere}
|
|
24
24
|
#status[data-state=error]{color:#bf3030}
|
|
25
25
|
#status[data-state=ok]{color:#247d48}
|
|
26
|
+
#result{font:12px/1.5 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere}
|
|
26
27
|
@media(prefers-color-scheme:dark){button{background:#4295e8}textarea{border-color:#888}}
|
|
27
28
|
</style>
|
|
28
29
|
</head>
|
|
@@ -32,12 +33,15 @@ button:disabled{opacity:.44;cursor:not-allowed}
|
|
|
32
33
|
<p id="description">正在连接表单工具…</p>
|
|
33
34
|
<fieldset id="options" disabled>
|
|
34
35
|
<legend id="legend">请选择一项</legend>
|
|
35
|
-
<
|
|
36
|
-
<label class="option"><input type="radio" name="choice" value="B"><span id="b-label">修改</span></label>
|
|
36
|
+
<div id="option-list"></div>
|
|
37
37
|
</fieldset>
|
|
38
|
-
<div id="
|
|
39
|
-
<
|
|
38
|
+
<div id="text-input" hidden>
|
|
39
|
+
<label id="text-label" for="input">补充信息</label>
|
|
40
|
+
<textarea id="input" maxlength="4000" rows="4"></textarea>
|
|
41
|
+
</div>
|
|
42
|
+
<button id="submit" disabled>提交</button>
|
|
40
43
|
<div id="status" role="status">等待真实 MCP Form prepare 回执</div>
|
|
44
|
+
<pre id="result" hidden></pre>
|
|
41
45
|
<small id="footer"></small>
|
|
42
46
|
</main>
|
|
43
47
|
<!-- CHAT_LOOP_FORM_SCRIPT -->
|