@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 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 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`.
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 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.
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
- current:apiAspect.current,
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('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=>{
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:payload.traceId,spanId:payload.spanId,
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,error
11
+ createSupervisorTraceBridge,createTraceWriterImpl=createTraceWriter
13
12
  }){
14
- const traceWriter=createTraceWriter({
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,error
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(k=>!OBSERVER_KEYS.has(k))||
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(k=>!['contract','action','requestId',
102
- 'windowMinutes','limit'].includes(k))||
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,claimFormSubmission,flushPending};
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,claimFormSubmission,flushPending}=observability;
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);
@@ -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)$|^form\.submission\.claimed$/;
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.11",
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.11",
38
- "@tomflow/chatloop-trace": "0.4.4"
37
+ "@tomflow/chatloop-extension": "0.4.12",
38
+ "@tomflow/chatloop-trace": "0.4.5"
39
39
  }
40
40
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Chat Loop Extension",
4
- "version": "0.4.11",
4
+ "version": "0.4.12",
5
5
  "description": "Chat Loop browser companion: Eye actions, Turn observer, Continue and Handoff Actions",
6
6
  "permissions": [
7
7
  "activeTab",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-extension",
3
- "version": "0.4.11",
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.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. Diagnostics expose truncation, corrupted lines, writer
94
+ and query sizes. Scoped readers stream logs up to 2 GiB without loading the
95
+ full JSONL file into memory; the default 30-day Writer retention keeps normal
96
+ operational history within that read bound. Diagnostics expose truncation, corrupted lines, writer
90
97
  restarts, legacy records and pending receipts as **uncertainty**. They never
91
98
  grant approval, Context write rights, Owner transfer or automatic retry.
92
99
  A missing or interrupted Writer must be checked against the authoritative
@@ -2,6 +2,8 @@
2
2
  import {constants as FS,createReadStream,closeSync,fstatSync,openSync} from 'node:fs';
3
3
  import {createInterface} from 'node:readline';
4
4
 
5
+ const MAX_TRACE_READ_BYTES=2*1024*1024*1024;
6
+
5
7
  export function makeTraceReader(options,deps){
6
8
  const {TRACE_SCHEMA_VERSION,fail,validStoredFamily,object,isId,safeScope,
7
9
  safeRef,natural,keys,secureFile,eventRule,EVENT,CODE,COMPONENTS,STATUSES}=deps;
@@ -60,7 +62,7 @@ export function makeTraceReader(options,deps){
60
62
  filePath].map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
61
63
  if(!files.length)return {events:[],matched:0,legacyUncorrelated:true,gapped:true,
62
64
  errors:['TRACE_LOG_MISSING'],truncated:false};
63
- if(files.reduce((sum,x)=>sum+x.stat.size,0)>64*1024*1024)
65
+ if(files.reduce((sum,x)=>sum+x.stat.size,0)>MAX_TRACE_READ_BYTES)
64
66
  throw fail('TRACE_FILE_TOO_LARGE');
65
67
  const seen=new Set(),events=[],errors=[],writerEpochs=new Set();
66
68
  let matched=0,corrupt=0,legacy=0;
@@ -157,7 +159,7 @@ export function makeTraceReader(options,deps){
157
159
  const files=[...Array.from({length:maxSegments},(_,i)=>
158
160
  filePath+'.'+(maxSegments-i)),filePath]
159
161
  .map(path=>({path,stat:secureFile(path)})).filter(x=>x.stat);
160
- if(files.reduce((n,x)=>n+x.stat.size,0)>64*1024*1024)
162
+ if(files.reduce((n,x)=>n+x.stat.size,0)>MAX_TRACE_READ_BYTES)
161
163
  throw fail('TRACE_FILE_TOO_LARGE');
162
164
  let malformed=0;
163
165
  for(const item of files){
@@ -0,0 +1,109 @@
1
+ import {randomUUID} from 'node:crypto';
2
+ import {constants as FS,closeSync,fstatSync,fsyncSync,lstatSync,openSync,readSync,writeSync,renameSync,unlinkSync} from 'node:fs';
3
+
4
+ const sameFile=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.size===b.size
5
+ &&a.mtimeMs===b.mtimeMs;
6
+ const writeAll=(fd,buffer)=>{
7
+ let offset=0;
8
+ while(offset<buffer.length)offset+=writeSync(fd,buffer,offset,buffer.length-offset);
9
+ };
10
+ function pruneFile(filePath,cutoff,secureFile){
11
+ const before=secureFile(filePath);
12
+ if(!before)return {droppedRecords:0,droppedBytes:0,pruned:false};
13
+ const input=openSync(filePath,FS.O_RDONLY|FS.O_NOFOLLOW);
14
+ let output,temp;
15
+ try{
16
+ const opened=fstatSync(input);
17
+ if(!opened.isFile()||(opened.mode&0o077)||
18
+ process.getuid&&opened.uid!==process.getuid()||!sameFile(before,opened))
19
+ throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
20
+ {code:'TRACE_RETENTION_SOURCE_CHANGED'});
21
+ temp=filePath+'.retention-'+randomUUID();
22
+ output=openSync(temp,FS.O_WRONLY|FS.O_CREAT|FS.O_EXCL|FS.O_NOFOLLOW,0o600);
23
+ const chunk=Buffer.allocUnsafe(64*1024),newline=Buffer.from([10]);
24
+ let position=0,pending=Buffer.alloc(0),longLine=false;
25
+ let droppedRecords=0,droppedBytes=0,keptRecords=0;
26
+ const keepLine=(line,terminated=true)=>{
27
+ let expired=false;
28
+ if(line.length<=8192){
29
+ try{
30
+ const value=JSON.parse(line.toString('utf8'));
31
+ const timestamp=Date.parse(value?.time);
32
+ expired=Number.isFinite(timestamp)&&timestamp<cutoff;
33
+ }catch{}
34
+ }
35
+ if(expired){droppedRecords++;droppedBytes+=line.length+(terminated?1:0);}
36
+ else{writeAll(output,line);writeAll(output,newline);keptRecords++;}
37
+ };
38
+ while(position<before.size){
39
+ const count=readSync(input,chunk,0,Math.min(chunk.length,before.size-position),position);
40
+ if(!count)throw Object.assign(Error('TRACE_RETENTION_READ_INCOMPLETE'),
41
+ {code:'TRACE_RETENTION_READ_INCOMPLETE'});
42
+ position+=count;
43
+ let start=0;
44
+ while(start<count){
45
+ const end=chunk.indexOf(10,start);
46
+ if(longLine){
47
+ const next=end<0?count:end+1;
48
+ writeAll(output,chunk.subarray(start,next));
49
+ if(end<0){start=count;continue;}
50
+ longLine=false;start=next;continue;
51
+ }
52
+ if(end<0){
53
+ const part=chunk.subarray(start,count);
54
+ if(pending.length+part.length>8192){
55
+ writeAll(output,pending);writeAll(output,part);
56
+ pending=Buffer.alloc(0);longLine=true;keptRecords++;
57
+ }else pending=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
58
+ start=count;continue;
59
+ }
60
+ const part=chunk.subarray(start,end);
61
+ const line=pending.length?Buffer.concat([pending,part]):Buffer.from(part);
62
+ if(line.length>8192){writeAll(output,line);writeAll(output,newline);keptRecords++;}
63
+ else keepLine(line);
64
+ pending=Buffer.alloc(0);start=end+1;
65
+ }
66
+ }
67
+ if(longLine)writeAll(output,newline);
68
+ else if(pending.length)keepLine(pending,false);
69
+ const after=fstatSync(input),current=lstatSync(filePath);
70
+ if(!sameFile(before,after)||!sameFile(before,current))
71
+ throw Object.assign(Error('TRACE_RETENTION_SOURCE_CHANGED'),
72
+ {code:'TRACE_RETENTION_SOURCE_CHANGED'});
73
+ if(!droppedRecords){
74
+ closeSync(output);output=undefined;unlinkSync(temp);temp=null;
75
+ return {droppedRecords,droppedBytes,pruned:false};
76
+ }
77
+ fsyncSync(output);closeSync(output);output=undefined;
78
+ closeSync(input);
79
+ if(!keptRecords){unlinkSync(filePath);unlinkSync(temp);temp=null;}
80
+ else{renameSync(temp,filePath);temp=null;}
81
+ return {droppedRecords,droppedBytes,pruned:true};
82
+ }finally{
83
+ try{closeSync(input)}catch{}
84
+ if(output!==undefined)try{closeSync(output)}catch{}
85
+ if(temp)try{unlinkSync(temp)}catch{}
86
+ }
87
+ }
88
+ export function createTraceRetention({filePath,maxSegments,retentionDays,secureFile}){
89
+ const state={days:retentionDays,droppedRecords:0,droppedBytes:0,
90
+ prunedFiles:0,lastRunAt:null,error:null};
91
+ const prune=()=>{
92
+ const cutoff=Date.now()-retentionDays*24*60*60*1000;
93
+ const paths=[...Array.from({length:maxSegments},(_,i)=>filePath+'.'+(i+1)),filePath];
94
+ state.error=null;
95
+ for(const path of paths){
96
+ try{
97
+ const result=pruneFile(path,cutoff,secureFile);
98
+ state.droppedRecords+=result.droppedRecords;
99
+ state.droppedBytes+=result.droppedBytes;
100
+ if(result.pruned)state.prunedFiles++;
101
+ }catch(error){state.error=error.code||'TRACE_RETENTION_FAILED';}
102
+ }
103
+ state.lastRunAt=new Date().toISOString();
104
+ };
105
+ prune();
106
+ const timer=setInterval(prune,24*60*60*1000);
107
+ timer.unref?.();
108
+ return {health:()=>({...state})};
109
+ }
@@ -2,6 +2,7 @@ import {makeTraceReader} from './trace-reader.mjs';
2
2
  import {randomUUID} from 'node:crypto';
3
3
  import {constants as FS,closeSync,fstatSync,lstatSync,openSync,writeSync,renameSync,unlinkSync} from 'node:fs';
4
4
  import {dirname,isAbsolute} from 'node:path';
5
+ import {createTraceRetention} from './trace-retention.mjs';
5
6
 
6
7
  export const TRACE_SCHEMA_VERSION=2;
7
8
  const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -138,13 +139,16 @@ function secureFile(filePath){
138
139
  return st;
139
140
  }
140
141
  export function createTraceWriter({
141
- filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5
142
+ filePath,enableRotation=false,rotateBytes=10*1024*1024,maxSegments=5,
143
+ retentionDays=30
142
144
  }){
143
145
  if(typeof enableRotation!=='boolean'||!Number.isSafeInteger(rotateBytes)||
144
146
  rotateBytes<512||rotateBytes>10*1024*1024||
145
- !Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5)
147
+ !Number.isSafeInteger(maxSegments)||maxSegments<1||maxSegments>5||
148
+ !Number.isSafeInteger(retentionDays)||retentionDays<1||retentionDays>3650)
146
149
  throw fail('TRACE_ROTATION_INVALID');
147
150
  const epoch=randomUUID();let seq=0,failures=0,lastError=null,rotations=0;
151
+ const retention=createTraceRetention({filePath,maxSegments,retentionDays,secureFile});
148
152
  const rotateIfNeeded=lineBytes=>{
149
153
  // Legacy data is never moved until an operator explicitly enables
150
154
  // rotation after preserving its historical evidence.
@@ -190,9 +194,12 @@ export function createTraceWriter({
190
194
  {errorCode:detail.errorCode}:{})
191
195
  });
192
196
  };
193
- const health=()=>({status:lastError?'TRACE_DEGRADED':'OK',
194
- errorCode:lastError,failures,writerEpoch:epoch,writerSeq:seq,
195
- rotationEnabled:enableRotation,rotations});
197
+ const health=()=>{
198
+ const retained=retention.health();
199
+ return {status:lastError||retained.error?'TRACE_DEGRADED':'OK',
200
+ errorCode:lastError||retained.error,failures,writerEpoch:epoch,writerSeq:seq,
201
+ rotationEnabled:enableRotation,rotations,retention:retained};
202
+ };
196
203
  return {record,recordControl,health};
197
204
  }
198
205
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tomflow/chatloop-trace",
3
- "version": "0.4.4",
3
+ "version": "0.4.5",
4
4
  "description": "Trace SDK and scoped read-only diagnostics for Chat Loop",
5
5
  "type": "module",
6
6
  "engines": {
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.22",
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.11",
35
- "@tomflow/chatloop-trace": "0.4.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.11"
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.24",
51
- "@tomflow/chatloop-tunnel-darwin-x64": "0.0.24"
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"
@@ -1,147 +1,180 @@
1
- // Generic ChatGPT A/B form interaction service; business meaning belongs to callers.
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
- const RESOURCE_URI='ui://chat-loop/form/review-v2';
5
- // Preserve the legacy resource locator; both URIs serve the same audited UI.
6
- const LEGACY_RESOURCE_URI='ui://chat-loop/form/review-v1';
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=(s,max)=>typeof s==='string'&&s.trim().length>0&&s.length<=max;
14
- const shape=(v,fields)=>v&&typeof v==='object'&&!Array.isArray(v)
15
- &&Object.keys(v).every(k=>fields.includes(k));
16
- const CARD=['title','description','confirmLabel','modifyLabel',
17
- 'modifyPlaceholder','submitLabel','footer'];
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','choice','comment'];
20
- const cardSchema={type:'object',additionalProperties:false,required:CARD,
21
- properties:Object.fromEntries(CARD.map(key=>[key,{type:'string',minLength:1,
22
- maxLength:['description','footer'].includes(key)?1200:180}]))};
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 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.',
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
- '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
+ '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','choice'],
35
- properties:{formId:{type:'string',pattern:FORM_ID.source},
59
+ required:['formId','traceRef','selection'],
60
+ properties:{
61
+ formId:{type:'string',pattern:FORM_ID.source},
36
62
  traceRef:{type:'string',pattern:UUID.source},
37
- choice:{type:'string',enum:['A','B']},
38
- comment:{type:'string',maxLength:4000}}},
39
- annotations:{readOnlyHint:false},
40
- _meta:{ui:{visibility:['model','app']},'openai/widgetAccessible':true}}
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(a,fields){
43
- if(!shape(a,fields)
44
- ||a.formId!==undefined&&(typeof a.formId!=='string'||!FORM_ID.test(a.formId)))
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(a){
48
- if(!shape(a.card,CARD)||CARD.some(x=>!Object.hasOwn(a.card,x)))
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
- for(const key of CARD){
51
- if(!filled(a.card[key],['description','footer'].includes(key)?1200:180))
52
- throw fail('FORM_CARD_INVALID');
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 trace(form){
73
- const parent=form?.current?.();
74
- return parent&&UUID.test(parent.traceId||'')&&UUID.test(parent.spanId||'')
75
- ?{traceId:parent.traceId,spanId:parent.spanId}:null;
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,parent,status='CONFIRMED',errorCode){
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,...(errorCode?{errorCode}:{}),...parent
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(a){
99
- const formId=a?.formId===undefined?randomUUID():a.formId;
139
+ function prepare(args){
140
+ const formId=args?.formId===undefined?randomUUID():args.formId;
100
141
  const traceRef=randomUUID();
101
- try{check(a,PREP);checkCard(a)}
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(a,formId)};
148
+ return {status:'FORM_PREPARED',formId,traceRef,view:view(args,formId)};
109
149
  }
110
- function validateSubmit(a){
111
- check(a,SUBMIT);
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))
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
- async function submit(a,form){
121
- validateSubmit(a);
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}:{})};
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(x=>x.name),
166
+ id:'form',order:5,names:tools.map(tool=>tool.name),
134
167
  create({form}={}){
135
- // Pure interaction adapter: no caller identity, business Context, form
136
- // registry, expiry, capacity limit, or process-local lifecycle state.
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,LEGACY_RESOURCE_URI].map(uri=>({
172
+ resources:()=>[RESOURCE_URI,...LEGACY_RESOURCE_URIS].map(uri=>({
140
173
  uri,name:'Chat Loop Form',mimeType:RESOURCE_MIME,
141
- description:'Reusable A/B form UI'
174
+ description:'Generic single-select form UI'
142
175
  })),
143
176
  async readResource(uri){
144
- if(uri!==RESOURCE_URI&&uri!==LEGACY_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):await submit(args,form);
160
- await observeForm(form,
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,parent);
194
+ result.formId,result.traceRef);
163
195
  return ok(result);
164
- }catch(e){
165
- await observeForm(form,
196
+ }catch(error){
197
+ void observeForm(form,
166
198
  isPrepare?'form.prepared.failed':'form.submitted.failed',
167
- e.formId||formId,e.traceRef||traceRef,parent,'FAILED',e.code||'FORM_FAILED');
168
- throw e;
199
+ error.formId||formId,error.traceRef||traceRef,error.code||'FORM_FAILED');
200
+ throw error;
169
201
  }
170
202
  }
171
203
  });
@@ -1,8 +1,5 @@
1
- // Minimal MCP Apps View bridge: JSON-RPC over postMessage, no bundled runtime.
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 reply timeout only; it never expires or deletes a prepared form.
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(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');
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(x=>x.type==='text')?.text;
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 selected=()=>options.find(x=>x.checked)?.value||null;
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 choice=selected();
51
+ const option=selectedOption(),visible=inputVisible(option);
43
52
  $('options').disabled=!connected;
44
- $('modify').hidden=choice!=='B';
45
- $('submit').disabled=!connected||!prepared||locked||!choice
46
- ||(choice==='B'&&!$('comment').value.trim());
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-review-card-v1'
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
- ||view.options?.length!==2
56
- ||view.options[0]?.value!=='A'||view.options[1]?.value!=='B')
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
- $('a-label').textContent=view.options[0].label;
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
- $('options').disabled=!connected;
69
- $('comment').value='';
70
- options.forEach(x=>x.checked=false);
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
- status(hostFailure|| (connected?'表单已准备,请选择 A 或 B。':
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('MCP_APP_HOST_REJECTED'));
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 Review',version:'1.0.1'},
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
- 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;
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 choice=selected(),comment=$('comment').value.trim();
152
- if(!['A','B'].includes(choice)||choice==='B'&&!comment)return;
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,choice,...(choice==='B'?{comment}:{})};
180
+ const args={formId,traceRef,
181
+ selection:{value:option.value,label:option.label},
182
+ ...(visible&&input?{input}:{})};
156
183
  status('正在提交表单…');
157
- let receipt;
158
- try{receipt=decode(await call('tools/call',{
159
- name:'chat_loop_form__submit',arguments:args
160
- }))}
161
- catch(error){
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'||code==='FORM_SUBMISSION_CLAIM_UNKNOWN'
166
- ?'Submit 结果未知,已锁定,禁止重复提交;请查原请求回执。'
167
- :code==='FORM_ALREADY_SUBMITTED'
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
- options.forEach(x=>x.addEventListener('change',update));
192
- $('comment').addEventListener('input',update);
207
+ $('input').addEventListener('input',update);
193
208
  $('submit').addEventListener('click',submit);
194
209
  void initialize();
@@ -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:100px;padding:10px;font:inherit;resize:vertical;border:1px solid #aaa8;border-radius:9px;background:transparent;color:inherit}
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
- <label class="option"><input type="radio" name="choice" value="A"><span id="a-label">确认</span></label>
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="modify" hidden><textarea id="comment" maxlength="4000"></textarea></div>
39
- <button id="submit" disabled>提交评审</button>
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=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();})();
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:100px;padding:10px;font:inherit;resize:vertical;border:1px solid #aaa8;border-radius:9px;background:transparent;color:inherit}
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
- <label class="option"><input type="radio" name="choice" value="A"><span id="a-label">确认</span></label>
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="modify" hidden><textarea id="comment" maxlength="4000"></textarea></div>
39
- <button id="submit" disabled>提交评审</button>
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 -->