@tomflow/chatloop-tools 0.9.19 → 0.9.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +8 -3
  2. package/index.mjs +49 -9
  3. package/lib/supervisor-observability.mjs +157 -0
  4. package/lib/supervisor-runtime.mjs +14 -111
  5. package/lib/trace-gateway.mjs +90 -11
  6. package/lib/trace-observation.mjs +17 -8
  7. package/node_modules/@tomflow/chatloop-context/README.md +240 -0
  8. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +48 -0
  9. package/node_modules/@tomflow/chatloop-context/capabilities/approval.mjs +151 -0
  10. package/node_modules/@tomflow/chatloop-context/capabilities/context.mjs +376 -0
  11. package/node_modules/@tomflow/chatloop-context/capabilities/document.mjs +266 -0
  12. package/node_modules/@tomflow/chatloop-context/capabilities/evidence.mjs +134 -0
  13. package/node_modules/@tomflow/chatloop-context/capabilities/presentation.mjs +82 -0
  14. package/node_modules/@tomflow/chatloop-context/capabilities/project.mjs +349 -0
  15. package/node_modules/@tomflow/chatloop-context/capabilities/sdk.mjs +72 -0
  16. package/node_modules/@tomflow/chatloop-context/capabilities/start.mjs +73 -0
  17. package/node_modules/@tomflow/chatloop-context/capabilities/task.mjs +507 -0
  18. package/node_modules/@tomflow/chatloop-context/capabilities.generated.mjs +11 -0
  19. package/node_modules/@tomflow/chatloop-context/docs/interfaces.md +182 -0
  20. package/node_modules/@tomflow/chatloop-context/docs/operator-and-migration.md +277 -0
  21. package/node_modules/@tomflow/chatloop-context/index.mjs +233 -0
  22. package/node_modules/@tomflow/chatloop-context/lib/api-log.mjs +86 -0
  23. package/node_modules/@tomflow/chatloop-context/lib/approval-policy.mjs +24 -0
  24. package/node_modules/@tomflow/chatloop-context/lib/capability-catalog.generated.json +1989 -0
  25. package/node_modules/@tomflow/chatloop-context/lib/capability-router.mjs +67 -0
  26. package/node_modules/@tomflow/chatloop-context/lib/cli-commands.mjs +280 -0
  27. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +298 -0
  28. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +280 -0
  29. package/node_modules/@tomflow/chatloop-context/lib/core/context.mjs +115 -0
  30. package/node_modules/@tomflow/chatloop-context/lib/core/evidence.mjs +51 -0
  31. package/node_modules/@tomflow/chatloop-context/lib/core/health.mjs +55 -0
  32. package/node_modules/@tomflow/chatloop-context/lib/core/migration.mjs +262 -0
  33. package/node_modules/@tomflow/chatloop-context/lib/core/project.mjs +246 -0
  34. package/node_modules/@tomflow/chatloop-context/lib/core/review.mjs +147 -0
  35. package/node_modules/@tomflow/chatloop-context/lib/core/run.mjs +343 -0
  36. package/node_modules/@tomflow/chatloop-context/lib/core/store.mjs +391 -0
  37. package/node_modules/@tomflow/chatloop-context/lib/core/task.mjs +166 -0
  38. package/node_modules/@tomflow/chatloop-context/lib/line-review.mjs +13 -0
  39. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +111 -0
  40. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +107 -0
  41. package/node_modules/@tomflow/chatloop-context/lib/orphan-operator.mjs +117 -0
  42. package/node_modules/@tomflow/chatloop-context/lib/process-inventory.mjs +20 -0
  43. package/node_modules/@tomflow/chatloop-context/lib/project-branch.mjs +312 -0
  44. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +153 -0
  45. package/node_modules/@tomflow/chatloop-context/lib/project-guards.mjs +19 -0
  46. package/node_modules/@tomflow/chatloop-context/lib/project-store.mjs +115 -0
  47. package/node_modules/@tomflow/chatloop-context/lib/trusted-run.mjs +86 -0
  48. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +169 -0
  49. package/node_modules/@tomflow/chatloop-context/package.json +40 -0
  50. package/node_modules/@tomflow/chatloop-context/scripts/build-capabilities.mjs +114 -0
  51. package/node_modules/@tomflow/chatloop-trace/README.md +105 -0
  52. package/node_modules/@tomflow/chatloop-trace/events/context.api.mjs +23 -0
  53. package/node_modules/@tomflow/chatloop-trace/events/typed.api.call.mjs +22 -0
  54. package/node_modules/@tomflow/chatloop-trace/events.generated.mjs +4 -0
  55. package/node_modules/@tomflow/chatloop-trace/index.mjs +59 -0
  56. package/node_modules/@tomflow/chatloop-trace/lib/api-aspect.mjs +273 -0
  57. package/node_modules/@tomflow/chatloop-trace/lib/trace-reader.mjs +265 -0
  58. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +205 -0
  59. package/node_modules/@tomflow/chatloop-trace/package.json +30 -0
  60. package/node_modules/@tomflow/chatloop-trace/scripts/build-events.mjs +68 -0
  61. package/package.json +5 -1
  62. package/providers/form.mjs +85 -206
  63. package/providers/trace.mjs +5 -2
  64. package/ui/form/review-app.js +59 -44
  65. package/ui/form/review.html +1 -1
@@ -1,19 +1,13 @@
1
- // Fixed ChatGPT card adapter, not a second approval authority.
2
- // Form IDs identify interactions; Context Issue IDs own R/P decisions.
1
+ // Generic ChatGPT A/B form interaction service; business meaning belongs to callers.
3
2
  import {randomUUID} from 'node:crypto';
4
3
  import {readFileSync} from 'node:fs';
5
4
  const RESOURCE_URI='ui://chat-loop/form/review-v2';
6
- // Previously rendered chat messages still reference v1 after an upgrade.
7
- // Preserve their resource locator; both URIs serve the same audited UI.
5
+ // Preserve the legacy resource locator; both URIs serve the same audited UI.
8
6
  const LEGACY_RESOURCE_URI='ui://chat-loop/form/review-v1';
9
7
  const RESOURCE_MIME='text/html;profile=mcp-app';
10
- const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
11
- const FORM_ID=/^[A-Za-z0-9_-]{8,80}$/;
8
+ const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
12
9
  const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
13
- const ISSUE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
14
- const HASH=/^[a-f0-9]{64}$/;
15
10
  const fail=code=>Object.assign(Error(code),{code});
16
- const err=code=>({isError:true,content:[{type:'text',text:code}]});
17
11
  const ok=value=>({content:[{type:'text',text:JSON.stringify(value)}],
18
12
  structuredContent:value});
19
13
  const filled=(s,max)=>typeof s==='string'&&s.trim().length>0&&s.length<=max;
@@ -21,70 +15,34 @@ const shape=(v,fields)=>v&&typeof v==='object'&&!Array.isArray(v)
21
15
  &&Object.keys(v).every(k=>fields.includes(k));
22
16
  const CARD=['title','description','confirmLabel','modifyLabel',
23
17
  'modifyPlaceholder','submitLabel','footer'];
24
- const PREP=['mode','formId','projectId','taskId','chatRef','kind','documentId',
25
- 'version','contentHash','expectedTaskRevision','expectedStoreEpoch',
26
- 'writeRequestId','card'];
27
- const SUBMIT=['mode','formId','issueId','projectId','taskId','chatRef','kind',
28
- 'documentId','version','choice','comment','userTurn','presentedAssistantRef',
29
- 'expectedTaskRevision','expectedStoreEpoch','writeRequestId'];
30
- const common={
31
- mode:{type:'string',enum:['GENERAL','TEST_ONLY','MANAGED']},
32
- formId:{type:'string',pattern:FORM_ID.source},projectId:{type:'string',pattern:ID.source},
33
- taskId:{type:'string',pattern:ID.source},
34
- chatRef:{type:'string',minLength:8,maxLength:256},
35
- kind:{type:'string',enum:['R','P','CUSTOM']},
36
- documentId:{type:'string',pattern:ID.source},
37
- version:{type:'integer',minimum:1},
38
- expectedTaskRevision:{type:'integer',minimum:1},
39
- expectedStoreEpoch:{type:'string',minLength:10,maxLength:64},
40
- writeRequestId:{type:'string',minLength:8,maxLength:128}
41
- };
18
+ const PREP=['formId','card'];
19
+ const SUBMIT=['formId','traceRef','choice','comment'];
42
20
  const cardSchema={type:'object',additionalProperties:false,required:CARD,
43
21
  properties:Object.fromEntries(CARD.map(key=>[key,{type:'string',minLength:1,
44
22
  maxLength:['description','footer'].includes(key)?1200:180}]))};
45
23
  const tools=[
46
24
  {name:'chat_loop_form__prepare',description:
47
- 'Prepare the fixed ChatGPT A/B card. Optional formId is preserved; otherwise a fresh UUID is generated. GENERAL/TEST_ONLY never write Context; MANAGED creates one Context R/P Issue and returns its separate issueId.',
48
- inputSchema:{type:'object',additionalProperties:false,
49
- required:['mode','card'],
50
- properties:{...common,contentHash:{type:'string',pattern:HASH.source},
51
- card:cardSchema}},
25
+ 'Render a reusable A/B form. Preserve the optional caller-supplied formId or generate a UUID; also return an opaque traceRef for correlation and one-time submission protection. No business workflow or approval state is owned here.',
26
+ inputSchema:{type:'object',additionalProperties:false,required:['card'],
27
+ properties:{formId:{type:'string',pattern:FORM_ID.source},card:cardSchema}},
52
28
  annotations:{readOnlyHint:false},
53
29
  _meta:{ui:{resourceUri:RESOURCE_URI,visibility:['model','app']},
54
30
  'openai/outputTemplate':RESOURCE_URI,'openai/widgetAccessible':true}},
55
31
  {name:'chat_loop_form__submit',description:
56
- 'Record a caller-asserted ChatGPT user-turn A/B choice for an existing formId; GENERAL/TEST_ONLY is SOFT observation only. MANAGED delegates to Context Issue authority with exact issueId, revisions and original writeRequestId. No click authentication implied.',
32
+ 'Receive the selected A/B option and optional comment for a prepared form. Requires its formId and opaque traceRef; the shared Supervisor claims the traceRef once before the app may request a user message. The caller owns all business interpretation and follow-up.',
57
33
  inputSchema:{type:'object',additionalProperties:false,
58
- required:['mode','formId','choice','userTurn','presentedAssistantRef','writeRequestId'],
59
- properties:{...common,issueId:{type:'string',pattern:ISSUE.source},
34
+ required:['formId','traceRef','choice'],
35
+ properties:{formId:{type:'string',pattern:FORM_ID.source},
36
+ traceRef:{type:'string',pattern:UUID.source},
60
37
  choice:{type:'string',enum:['A','B']},
61
- comment:{type:'string',maxLength:4000},
62
- userTurn:{type:'string',minLength:8,maxLength:256},
63
- presentedAssistantRef:{type:'string',minLength:8,maxLength:256}}},
38
+ comment:{type:'string',maxLength:4000}}},
64
39
  annotations:{readOnlyHint:false},
65
- _meta:{ui:{visibility:['model','app']},
66
- 'openai/widgetAccessible':true}}
40
+ _meta:{ui:{visibility:['model','app']},'openai/widgetAccessible':true}}
67
41
  ];
68
42
  function check(a,fields){
69
- if(!shape(a,fields)||!['GENERAL','TEST_ONLY','MANAGED'].includes(a.mode)
70
- ||a.formId!==undefined&&!FORM_ID.test(a.formId)
71
- ||a.projectId!==undefined&&!ID.test(a.projectId)
72
- ||a.documentId!==undefined&&!ID.test(a.documentId)
73
- ||a.version!==undefined&&(!Number.isSafeInteger(a.version)||a.version<1)
74
- ||a.kind!==undefined&&!['R','P','CUSTOM'].includes(a.kind))
43
+ if(!shape(a,fields)
44
+ ||a.formId!==undefined&&(typeof a.formId!=='string'||!FORM_ID.test(a.formId)))
75
45
  throw fail('FORM_INVALID_ARGUMENT');
76
- if(['R','P'].includes(a.kind)&&(!ID.test(a.documentId||'')
77
- ||!Number.isSafeInteger(a.version)))throw fail('FORM_REVIEW_SCOPE_REQUIRED');
78
- if(a.mode!=='GENERAL'&&(!ID.test(a.projectId||'')
79
- ||!ID.test(a.documentId||'')||!Number.isSafeInteger(a.version)
80
- ||!['R','P'].includes(a.kind)))throw fail('FORM_REVIEW_SCOPE_REQUIRED');
81
- if(a.mode==='TEST_ONLY'&&(!filled(a.chatRef,256)||a.chatRef.length<8))
82
- throw fail('FORM_TEST_CHAT_REQUIRED');
83
- if(a.mode==='MANAGED'&&(!ID.test(a.taskId||'')
84
- ||!Number.isSafeInteger(a.expectedTaskRevision)
85
- ||a.expectedTaskRevision<1||!filled(a.expectedStoreEpoch,64)
86
- ||!filled(a.writeRequestId,128)))
87
- throw fail('FORM_MANAGED_SCOPE_REQUIRED');
88
46
  }
89
47
  function checkCard(a){
90
48
  if(!shape(a.card,CARD)||CARD.some(x=>!Object.hasOwn(a.card,x)))
@@ -94,21 +52,14 @@ function checkCard(a){
94
52
  throw fail('FORM_CARD_INVALID');
95
53
  }
96
54
  if(!/^A\s*[—-]/.test(a.card.confirmLabel)
97
- ||!/^B\s*[—-]/.test(a.card.modifyLabel)
98
- ||a.kind==='R'&&a.card.submitLabel!=='提交需求评审'
99
- ||a.kind==='P'&&a.card.submitLabel!=='提交方案评审')
55
+ ||!/^B\s*[—-]/.test(a.card.modifyLabel))
100
56
  throw fail('FORM_CARD_LAYOUT_INVALID');
101
57
  }
102
- function view(a,formId,issueId,prior){
103
- const review=a.kind==='R'||a.kind==='P';
104
- return {template:'chat-loop-review-card-v1',formId,mode:a.mode,
58
+ function view(a,formId){
59
+ return {template:'chat-loop-review-card-v1',formId,
105
60
  layout:{card:'rounded-border',radiusPx:12,paddingPx:12,gapPx:12,
106
61
  direction:'column',optionDirection:'column',buttonWidth:'full',
107
62
  buttonShape:'pill'},
108
- badges:review
109
- ?[...(prior?[{text:prior+' SUPERSEDED'}]:[]),
110
- {text:a.documentId+' CURRENT'},{text:'WAITING_APPROVAL'}]
111
- :[{text:'WAITING_INPUT'}],
112
63
  title:a.card.title,description:a.card.description,
113
64
  options:[{value:'A',label:a.card.confirmLabel},
114
65
  {value:'B',label:a.card.modifyLabel}],
@@ -116,121 +67,78 @@ function view(a,formId,issueId,prior){
116
67
  placeholder:a.card.modifyPlaceholder},
117
68
  submit:{label:a.card.submitLabel,disabledInitially:true,
118
69
  singleClickLock:true,issueNewUserTurn:true},
119
- footer:a.card.footer,
120
- ...(review?{documentId:a.documentId,version:a.version}:{}),
121
- authority:issueId?'CONTEXT_ISSUE':'NONE'};
70
+ footer:a.card.footer};
122
71
  }
123
72
  function trace(form){
124
73
  const parent=form?.current?.();
125
74
  return parent&&UUID.test(parent.traceId||'')&&UUID.test(parent.spanId||'')
126
75
  ?{traceId:parent.traceId,spanId:parent.spanId}:null;
127
76
  }
128
- function contextAccess(context){
129
- if(context?.contextGatewayEnabled?.()!==true)
130
- throw fail('FORM_CONTEXT_UNAVAILABLE');
131
- }
132
- async function request(context,kind,args){
133
- return context.runContextGateway(
134
- kind==='get'?'chat_loop_context_get':'chat_loop_context_mutate',args);
77
+ async function observeForm(form,event,formId,traceRef,parent,status='CONFIRMED',errorCode){
78
+ if(typeof form?.observe!=='function'||!FORM_ID.test(formId||'')
79
+ ||!UUID.test(traceRef||''))return false;
80
+ if(!parent){
81
+ form?.lost?.();
82
+ return false;
83
+ }
84
+ try{
85
+ const result=await form.observe({
86
+ event,formId,traceRef,status,...(errorCode?{errorCode}:{}),...parent
87
+ });
88
+ if(result?.status!=='OK'||!UUID.test(result.eventId||'')){
89
+ form?.lost?.();
90
+ return false;
91
+ }
92
+ return true;
93
+ }catch{
94
+ form?.lost?.();
95
+ return false;
96
+ }
135
97
  }
136
- async function prepare(a,context,form){
137
- check(a,PREP);checkCard(a);
138
- const formId=a.formId||randomUUID();
139
- if(a.mode!=='MANAGED'){
140
- return {status:a.mode==='TEST_ONLY'?'TEST_ONLY_PREVIEW':'FORM_PREPARED_SOFT',
141
- formId,mode:a.mode,kind:a.kind||'CUSTOM',
142
- ...(a.projectId?{projectId:a.projectId}:{}),
143
- ...(a.chatRef?{chatRef:a.chatRef}:{}),
144
- ...(a.documentId?{documentId:a.documentId,version:a.version}:{}),
145
- view:view(a,formId,null,a.kind!=='CUSTOM'&&a.version>1
146
- ?a.documentId[0]+(a.version-1):null),
147
- trace:trace(form),approvalAuthority:'NONE',businessSideEffects:false,
148
- provenance:'FORM_ID_ONLY_NO_DURABLE_ISSUE'};
98
+ function prepare(a){
99
+ const formId=a?.formId===undefined?randomUUID():a.formId;
100
+ const traceRef=randomUUID();
101
+ try{check(a,PREP);checkCard(a)}
102
+ catch(error){
103
+ error.formId=typeof formId==='string'&&FORM_ID.test(formId)
104
+ ?formId:randomUUID();
105
+ error.traceRef=traceRef;
106
+ throw error;
149
107
  }
150
- if(!HASH.test(a.contentHash||''))throw fail('FORM_CONTENT_HASH_REQUIRED');
151
- contextAccess(context);
152
- const doc=await request(context,'get',{operation:'document.get',projectId:a.projectId,
153
- taskId:a.taskId,documentId:a.documentId,version:a.version});
154
- if(doc?.kind!==a.kind||doc?.contentHash!==a.contentHash)
155
- throw fail('FORM_DOCUMENT_MISMATCH');
156
- const list=await request(context,'get',{operation:'document.list',
157
- projectId:a.projectId,taskId:a.taskId});
158
- const prior=Array.isArray(list)&&list.some(x=>x.kind===a.kind&&
159
- x.version===a.version-1&&x.documentId===a.documentId[0]+(a.version-1))
160
- ?a.documentId[0]+(a.version-1):null;
161
- const issue=await request(context,'mutate',{operation:'document.prepareIssue',
162
- projectId:a.projectId,taskId:a.taskId,documentId:a.documentId,
163
- version:a.version,contentHash:a.contentHash,
164
- expectedTaskRevision:a.expectedTaskRevision,
165
- expectedStoreEpoch:a.expectedStoreEpoch,writeRequestId:a.writeRequestId});
166
- if(issue?.status!=='ISSUE_PENDING'||!ISSUE.test(issue.issueId||''))
167
- throw fail('FORM_ISSUE_RECEIPT_INVALID');
168
- // Reuse the durable Issue identity by default to keep MANAGED retries stable;
169
- // a caller-supplied formId is a separate non-authoritative UI correlation ID.
170
- const managedFormId=a.formId||issue.issueId;
171
- return {status:'WAITING_APPROVAL',formId:managedFormId,issueId:issue.issueId,
172
- mode:a.mode,projectId:a.projectId,taskId:a.taskId,
173
- documentId:a.documentId,version:a.version,kind:a.kind,
174
- taskRevision:issue.taskRevision,approvalRevision:issue.approvalRevision,
175
- writeRequestId:a.writeRequestId,trace:trace(form),
176
- view:view(a,managedFormId,issue.issueId,prior),approvalAuthority:'CONTEXT',
177
- businessSideEffects:true};
108
+ return {status:'FORM_PREPARED',formId,traceRef,view:view(a,formId)};
178
109
  }
179
110
  function validateSubmit(a){
180
111
  check(a,SUBMIT);
181
- if(!FORM_ID.test(a.formId||'')||!['A','B'].includes(a.choice)
182
- ||!filled(a.userTurn,256)||!filled(a.presentedAssistantRef,256)
183
- ||!filled(a.writeRequestId,128))
112
+ if(typeof a.formId!=='string'||!FORM_ID.test(a.formId)
113
+ ||typeof a.traceRef!=='string'||!UUID.test(a.traceRef)
114
+ ||!['A','B'].includes(a.choice))
184
115
  throw fail('FORM_SUBMISSION_INVALID');
185
116
  if(a.choice==='B'&&!filled(a.comment,4000)
186
117
  ||a.choice==='A'&&a.comment!==undefined&&a.comment!=='')
187
118
  throw fail('FORM_COMMENT_INVALID');
188
- if(a.mode==='MANAGED'&&!ISSUE.test(a.issueId||''))
189
- throw fail('FORM_ISSUE_REF_REQUIRED');
190
119
  }
191
- async function submit(a,context,form){
120
+ async function submit(a,form){
192
121
  validateSubmit(a);
193
- if(a.mode!=='MANAGED'){
194
- return {status:'FORM_SUBMISSION_OBSERVED_SOFT',formId:a.formId,
195
- choice:a.choice,trace:trace(form),approvalAuthority:'NONE',
196
- businessSideEffects:false,preparedFormIdVerified:false,
197
- platformProvenance:'AGENT_ASSERTED_UNVERIFIED'};
198
- }
199
- if(!ISSUE.test(a.issueId||''))throw fail('FORM_ISSUE_REF_REQUIRED');
200
- contextAccess(context);
201
- const result=await request(context,'mutate',{operation:'approval.observe',
202
- projectId:a.projectId,taskId:a.taskId,issueId:a.issueId,
203
- decision:a.choice==='A'?'APPROVE':'REQUEST_CHANGE',
204
- sourceRole:'user',userTurn:a.userTurn,
205
- presentedAssistantRef:a.presentedAssistantRef,
206
- expectedTaskRevision:a.expectedTaskRevision,
207
- expectedStoreEpoch:a.expectedStoreEpoch,writeRequestId:a.writeRequestId});
208
- if(!['APPROVED_SOFT','CHANGE_REQUESTED'].includes(result?.status))
209
- throw fail('FORM_APPROVAL_RECEIPT_INVALID');
210
- return {status:result.status,formId:a.formId,issueId:a.issueId,
211
- kind:result.kind,choice:a.choice,taskRevision:result.taskRevision,
212
- ...(result.approvalRevision?{approvalRevision:result.approvalRevision}:{}),
213
- writeRequestId:a.writeRequestId,trace:trace(form),
214
- approvalAuthority:'CONTEXT',proofLevel:'SOFT_USER_TURN',
215
- formIssueBinding:'CALLER_ASSERTED_UNVERIFIED',
216
- platformProvenance:'AGENT_ASSERTED_UNVERIFIED'};
122
+ if(typeof form?.claimSubmission!=='function')
123
+ throw fail('FORM_SUBMISSION_CLAIM_UNAVAILABLE');
124
+ let claim;
125
+ try{claim=await form.claimSubmission({formId:a.formId,traceRef:a.traceRef})}
126
+ catch(error){throw fail(error?.code||'FORM_SUBMISSION_CLAIM_UNKNOWN')}
127
+ if(claim?.status!=='FORM_SUBMISSION_CLAIMED')
128
+ throw fail(claim?.error?.code||'FORM_SUBMISSION_CLAIM_UNKNOWN');
129
+ return {status:'FORM_SUBMITTED',formId:a.formId,traceRef:a.traceRef,
130
+ choice:a.choice,...(a.comment?{comment:a.comment}:{})};
217
131
  }
218
132
  export const provider=Object.freeze({
219
133
  id:'form',order:5,names:tools.map(x=>x.name),
220
- create({context,form}={}){
221
- // Bounded, process-local UI correlation only. Context is still the
222
- // authoritative MANAGED Issue store; a cache hit is NOT user proof.
223
- const forms=new Map(),TTL=30*60*1000;
224
- const lookup=id=>{
225
- const record=forms.get(id);
226
- if(!record||Date.now()-record.at>TTL){forms.delete(id);return null}
227
- return record;
228
- };
134
+ create({form}={}){
135
+ // Pure interaction adapter: no caller identity, business Context, form
136
+ // registry, expiry, capacity limit, or process-local lifecycle state.
229
137
  return Object.freeze({
230
138
  tools:()=>tools,
231
139
  resources:()=>[RESOURCE_URI,LEGACY_RESOURCE_URI].map(uri=>({
232
- uri,name:'Chat Loop Review',mimeType:RESOURCE_MIME,
233
- description:'A/B review with one locked submit'
140
+ uri,name:'Chat Loop Form',mimeType:RESOURCE_MIME,
141
+ description:'Reusable A/B form UI'
234
142
  })),
235
143
  async readResource(uri){
236
144
  if(uri!==RESOURCE_URI&&uri!==LEGACY_RESOURCE_URI)
@@ -241,53 +149,24 @@ export const provider=Object.freeze({
241
149
  preferredDisplayMode:'inline'}}}]};
242
150
  },
243
151
  async call(name,args){
152
+ const isPrepare=name===tools[0].name;
153
+ const isSubmit=name===tools[1].name;
154
+ if(!isPrepare&&!isSubmit)throw fail('UNKNOWN_TOOL');
155
+ const parent=trace(form);
156
+ const formId=typeof args?.formId==='string'?args.formId:null;
157
+ const traceRef=typeof args?.traceRef==='string'?args.traceRef:null;
244
158
  try{
245
- const isPrepare=name===tools[0].name;
246
- const isSubmit=name===tools[1].name;
247
- if(isSubmit){
248
- validateSubmit(args);
249
- const prior=lookup(args?.formId);
250
- if(!prior)throw fail('FORM_NOT_PREPARED');
251
- if(prior.submitted)throw fail('FORM_ALREADY_SUBMITTED');
252
- for(const key of ['mode','projectId','chatRef','taskId','kind',
253
- 'documentId','version','issueId']){
254
- if(args.mode==='GENERAL'&&key==='kind'&&args.kind===undefined)
255
- continue; // Backward-compatible optional generic kind.
256
- if(prior.args[key]!==args?.[key]&&(
257
- prior.args[key]!==undefined||args?.[key]!==undefined))
258
- throw fail('FORM_SCOPE_MISMATCH');
259
- }
260
- // Mark before async Context call. UNKNOWN is never retried with
261
- // a different request ID; the real Context receipt remains owner.
262
- prior.submitted=true;
263
- }
264
- const result=isPrepare?await prepare(args,context,form)
265
- :isSubmit?await submit(args,context,form):null;
266
- if(isSubmit&&result&&args.mode!=='MANAGED')
267
- result.preparedFormIdVerified=true;
268
- if(isPrepare&&result){
269
- for(const [id,record] of forms){
270
- if(Date.now()-record.at>TTL)forms.delete(id);
271
- }
272
- if(forms.size>=256)forms.delete(forms.keys().next().value);
273
- forms.set(result.formId,{at:Date.now(),submitted:false,
274
- args:{...args,kind:result.kind,formId:result.formId,
275
- issueId:result.issueId}});
276
- }
277
- if(result&&args?.projectId&&typeof form?.observe==='function'){
278
- const parent=trace(form);
279
- if(parent)setImmediate(()=>{
280
- // Soft evidence, never an approval receipt or a retry trigger.
281
- try{void Promise.resolve(form.observe({
282
- event:name===tools[0].name?'form.prepared.soft_observed'
283
- :'form.submitted.soft_observed',
284
- projectRef:args.projectId,taskRef:args.taskId,
285
- formId:result.formId,...parent
286
- })).catch(()=>{})}catch{/* telemetry isolation */}
287
- });
288
- }
289
- return result?ok(result):err('UNKNOWN_TOOL');
290
- }catch(e){return err(e.code||'FORM_FAILED')}
159
+ const result=isPrepare?prepare(args):await submit(args,form);
160
+ await observeForm(form,
161
+ isPrepare?'form.prepared.soft_observed':'form.submitted.soft_observed',
162
+ result.formId,result.traceRef,parent);
163
+ return ok(result);
164
+ }catch(e){
165
+ await observeForm(form,
166
+ isPrepare?'form.prepared.failed':'form.submitted.failed',
167
+ e.formId||formId,e.traceRef||traceRef,parent,'FAILED',e.code||'FORM_FAILED');
168
+ throw e;
169
+ }
291
170
  }
292
171
  });
293
172
  }
@@ -6,9 +6,12 @@ export const provider=Object.freeze({
6
6
  id:'trace',order:4,names,
7
7
  create({trace}){
8
8
  return Object.freeze({
9
- tools:()=>trace.traceGatewayEnabled()?[traceDiagnoseTool,traceStageTool]:[],
9
+ tools:()=>trace.traceGatewayEnabled()
10
+ ?[traceDiagnoseTool,traceStageTool]:[traceDiagnoseTool],
10
11
  async call(name,args){
11
- if(!trace.traceGatewayEnabled())return fail('UNKNOWN_TOOL');
12
+ const formLookup=name===traceDiagnoseTool.name
13
+ &&args?.projectRef==='api_system';
14
+ if(!trace.traceGatewayEnabled()&&!formLookup)return fail('UNKNOWN_TOOL');
12
15
  try{
13
16
  const result=name===traceStageTool.name
14
17
  ?await trace.runTraceStage(args)
@@ -1,11 +1,12 @@
1
1
  // Minimal MCP Apps View bridge: JSON-RPC over postMessage, no bundled runtime.
2
2
  // Protocol: https://modelcontextprotocol.io/extensions/apps
3
- // GENERAL/TEST_ONLY only; MANAGED approval remains Context + real user Turn.
3
+ // The Form service only renders, collects and returns user selections.
4
4
  const $=id=>document.getElementById(id);
5
5
  const options=[...document.querySelectorAll('input[name="choice"]')];
6
- const idPattern=/^[A-Za-z0-9_-]{8,80}$/;
6
+ const idPattern=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
7
+ const tracePattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
7
8
  const requests=new Map();
8
- let seq=0,connected=false,prepared=null,locked=false,toolResult=null;
9
+ let seq=0,connected=false,prepared=null,locked=false,toolResult=null,hostFailure=null;
9
10
  function status(message,state='info'){
10
11
  $('status').textContent=message;
11
12
  $('status').dataset.state=state;
@@ -16,6 +17,7 @@ function call(method,params){
16
17
  if(!connected)throw Error('FORM_APP_NOT_INITIALIZED');
17
18
  return new Promise((resolve,reject)=>{
18
19
  const id=++seq;
20
+ // Transport reply timeout only; it never expires or deletes a prepared form.
19
21
  // A timeout never authorizes a retry of a write.
20
22
  const timer=setTimeout(()=>{
21
23
  requests.delete(id);reject(Error('FORM_APP_REPLY_UNKNOWN'));
@@ -25,7 +27,11 @@ function call(method,params){
25
27
  });
26
28
  }
27
29
  function decode(result){
28
- if(result?.isError)throw Error('FORM_TOOL_REJECTED');
30
+ if(result?.isError){
31
+ const code=result.content?.find(x=>x.type==='text')?.text;
32
+ throw Error(typeof code==='string'
33
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)?code:'FORM_TOOL_REJECTED');
34
+ }
29
35
  if(result?.structuredContent?.status)return result.structuredContent;
30
36
  const text=result?.content?.find(x=>x.type==='text')?.text;
31
37
  if(typeof text!=='string'||text.length>20000)throw Error('FORM_RECEIPT_MISSING');
@@ -34,22 +40,24 @@ function decode(result){
34
40
  const selected=()=>options.find(x=>x.checked)?.value||null;
35
41
  function update(){
36
42
  const choice=selected();
43
+ $('options').disabled=!connected;
37
44
  $('modify').hidden=choice!=='B';
38
- $('submit').disabled=!prepared||locked||!choice
45
+ $('submit').disabled=!connected||!prepared||locked||!choice
39
46
  ||(choice==='B'&&!$('comment').value.trim());
40
47
  resize();
41
48
  }
42
49
  function render(value){
43
50
  const view=value?.view;
44
51
  if(!view||view.template!=='chat-loop-review-card-v1'
45
- ||!idPattern.test(value.formId||'')
52
+ ||typeof value.formId!=='string'||!idPattern.test(value.formId)
53
+ ||typeof value.traceRef!=='string'||!tracePattern.test(value.traceRef)
46
54
  ||view.formId!==value.formId
47
- ||!['GENERAL','TEST_ONLY','MANAGED'].includes(view.mode)
48
55
  ||view.options?.length!==2
49
56
  ||view.options[0]?.value!=='A'||view.options[1]?.value!=='B')
50
57
  throw Error('FORM_VIEW_INVALID');
51
- const safe=view.mode==='GENERAL'||view.mode==='TEST_ONLY';
52
- prepared={...value,mode:view.mode};
58
+ const preserveLock=prepared?.formId===value.formId
59
+ &&prepared?.traceRef===value.traceRef&&locked;
60
+ prepared=value;
53
61
  $('title').textContent=view.title;
54
62
  $('description').textContent=view.description;
55
63
  $('a-label').textContent=view.options[0].label;
@@ -57,12 +65,13 @@ function render(value){
57
65
  $('comment').placeholder=view.modifyField?.placeholder||'填写修改意见';
58
66
  $('submit').textContent=view.submit?.label||'提交';
59
67
  $('footer').textContent=view.footer||'';
60
- $('options').disabled=!safe;
68
+ $('options').disabled=!connected;
61
69
  $('comment').value='';
62
70
  options.forEach(x=>x.checked=false);
63
- locked=!safe;
64
- status(safe?'已连接 Form prepare;请选择 A 或 B。':
65
- '正式审批需要真实用户消息身份,组件不得代签。',safe?'ok':'error');
71
+ locked=preserveLock;
72
+ status(hostFailure|| (connected?'表单已准备,请选择 A 或 B。':
73
+ '表单已准备,正在等待宿主能力确认。'),
74
+ hostFailure?'error':connected?'ok':'info');
66
75
  update();
67
76
  }
68
77
  function receive(event){
@@ -113,64 +122,70 @@ async function initialize(){
113
122
  });
114
123
  try{
115
124
  const response=await init;
116
- if(!response?.protocolVersion||!response.hostInfo)
125
+ if(!response?.protocolVersion||!response.hostInfo
126
+ ||!response.hostCapabilities)
117
127
  throw Error('FORM_APP_INIT_INVALID');
128
+ if(!response.hostCapabilities.serverTools
129
+ ||!response.hostCapabilities.message?.text){
130
+ hostFailure='当前宿主缺少 serverTools 或 message.text 能力,表单不可提交。';
131
+ status(hostFailure,'error');
132
+ update();
133
+ return;
134
+ }
118
135
  connected=true;
136
+ hostFailure=null;
119
137
  notify('ui/notifications/initialized',{});
120
138
  resize();
121
139
  if(toolResult)render(decode(toolResult));
122
140
  if(typeof ResizeObserver==='function')
123
141
  new ResizeObserver(resize).observe(document.documentElement);
124
142
  }catch{
125
- status('MCP App 初始化失败,请核查 ChatGPT 宿主连接。','error');
143
+ hostFailure='MCP App 初始化失败,请核查宿主连接与协议能力。';
144
+ status(hostFailure,'error');
145
+ connected=false;
146
+ update();
126
147
  }
127
148
  }
128
149
  async function submit(){
129
- if(!connected||locked||!prepared
130
- ||!['GENERAL','TEST_ONLY'].includes(prepared.mode))return;
150
+ if(!connected||locked||!prepared)return;
131
151
  const choice=selected(),comment=$('comment').value.trim();
132
152
  if(!['A','B'].includes(choice)||choice==='B'&&!comment)return;
133
153
  locked=true;update();
134
- const {formId,mode}=prepared,writeRequestId=crypto.randomUUID();
135
- const args={mode,formId,choice,kind:prepared.kind,
136
- ...(choice==='B'?{comment}:{}),
137
- userTurn:'unverified-app-'+writeRequestId,
138
- presentedAssistantRef:'app-form-'+formId,
139
- writeRequestId,
140
- ...(mode==='TEST_ONLY'?{
141
- projectId:prepared.projectId,chatRef:prepared.chatRef,
142
- documentId:prepared.documentId,version:prepared.version
143
- }:{})};
144
- status('正在向 Form submit 提交唯一请求…');
154
+ const {formId,traceRef}=prepared;
155
+ const args={formId,traceRef,choice,...(choice==='B'?{comment}:{})};
156
+ status('正在提交表单…');
145
157
  let receipt;
146
158
  try{receipt=decode(await call('tools/call',{
147
159
  name:'chat_loop_form__submit',arguments:args
148
160
  }))}
149
- catch{
150
- status('Submit 结果未知,禁止重复提交;请查原请求回执。','error');
161
+ catch(error){
162
+ const code=typeof error?.message==='string'
163
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(error.message)
164
+ ?error.message:'FORM_APP_REPLY_UNKNOWN';
165
+ status(code==='FORM_APP_REPLY_UNKNOWN'||code==='FORM_SUBMISSION_CLAIM_UNKNOWN'
166
+ ?'Submit 结果未知,已锁定,禁止重复提交;请查原请求回执。'
167
+ :code==='FORM_ALREADY_SUBMITTED'
168
+ ?'该表单已提交过,禁止重复发送;请核查原消息。'
169
+ :'Submit 明确失败('+code+'),用户消息未发送。','error');
151
170
  return;
152
171
  }
153
- if(receipt.status!=='FORM_SUBMISSION_OBSERVED_SOFT'
154
- ||receipt.formId!==formId||receipt.choice!==choice
155
- ||receipt.preparedFormIdVerified!==true){
156
- status('Submit 未验证绑定,用户消息未发送。','error');
172
+ if(receipt.status!=='FORM_SUBMITTED'
173
+ ||receipt.formId!==formId||receipt.traceRef!==traceRef
174
+ ||receipt.choice!==choice){
175
+ status('Submit 返回的信息与当前表单不匹配,用户消息未发送。','error');
157
176
  return;
158
177
  }
159
- const version=prepared.documentId
160
- ?prepared.documentId+' v'+prepared.version:'自定义表单';
161
- const text='【Chat Loop Form|'+mode+'】formId='+formId+'|'+version+'|'
162
- +(choice==='A'?'A 确认':'B 修改:'+comment)
163
- +'。组件请求发送,用户消息身份须独立核对。'
164
- +(mode==='TEST_ONLY'?'不构成正式审批,不 Start/Continue/Handoff。':'');
165
- status('Submit 软回执成功,正在申请单次用户消息…');
178
+ const text='【Chat Loop Form】formId='+formId+'|'
179
+ +(choice==='A'?'A 选择':'B 选择:'+comment)+'。';
180
+ status('单次提交已锁定,正在申请当前 Chat 用户消息…');
166
181
  try{
167
182
  const result=await call('ui/message',{
168
183
  role:'user',content:[{type:'text',text}]
169
184
  });
170
- status(result?.isError?'宿主拒绝消息;未完成正式审批。':
171
- '宿主接受消息请求;userMessageId 仍需独立核验。',
185
+ status(result?.isError?'宿主未接受表单结果消息。':
186
+ '宿主已接受用户消息请求;平台消息身份仍需独立核验。',
172
187
  result?.isError?'error':'ok');
173
- }catch{status('宿主消息状态未知,禁止重复发送。','error')}
188
+ }catch{status('用户消息发送状态未知,已锁定,禁止重试;请核查原消息。','error')}
174
189
  }
175
190
  window.addEventListener('message',receive);
176
191
  options.forEach(x=>x.addEventListener('change',update));
@@ -40,7 +40,7 @@ button:disabled{opacity:.44;cursor:not-allowed}
40
40
  <div id="status" role="status">等待真实 MCP Form prepare 回执</div>
41
41
  <small id="footer"></small>
42
42
  </main>
43
- <script>(()=>{var r=t=>document.getElementById(t),I=[...document.querySelectorAll('input[name="choice"]')],P=/^[A-Za-z0-9_-]{8,80}$/,d=new Map,v=0,l=!1,n=null,u=!1,m=null;function s(t,e="info"){r("status").textContent=t,r("status").dataset.state=e}function f(t){window.parent.postMessage({jsonrpc:"2.0",...t},"*")}function R(t,e={}){f({method:t,params:e})}function O(t,e){if(!l)throw Error("FORM_APP_NOT_INITIALIZED");return new Promise((o,i)=>{let c=++v,h=setTimeout(()=>{d.delete(c),i(Error("FORM_APP_REPLY_UNKNOWN"))},3e4);d.set(c,{resolve:o,reject:i,timer:h}),f({id:c,method:t,params:e})})}function _(t){if(t?.isError)throw Error("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 A=()=>I.find(t=>t.checked)?.value||null;function p(){let t=A();r("modify").hidden=t!=="B",r("submit").disabled=!n||u||!t||t==="B"&&!r("comment").value.trim(),E()}function C(t){let e=t?.view;if(!e||e.template!=="chat-loop-review-card-v1"||!P.test(t.formId||"")||e.formId!==t.formId||!["GENERAL","TEST_ONLY","MANAGED"].includes(e.mode)||e.options?.length!==2||e.options[0]?.value!=="A"||e.options[1]?.value!=="B")throw Error("FORM_VIEW_INVALID");let o=e.mode==="GENERAL"||e.mode==="TEST_ONLY";n={...t,mode:e.mode},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=!o,r("comment").value="",I.forEach(i=>i.checked=!1),u=!o,s(o?"\u5DF2\u8FDE\u63A5 Form prepare\uFF1B\u8BF7\u9009\u62E9 A \u6216 B\u3002":"\u6B63\u5F0F\u5BA1\u6279\u9700\u8981\u771F\u5B9E\u7528\u6237\u6D88\u606F\u8EAB\u4EFD\uFF0C\u7EC4\u4EF6\u4E0D\u5F97\u4EE3\u7B7E\u3002",o?"ok":"error"),p()}function L(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=d.get(e.id);if(!o)return;d.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"){m=e.params;try{C(_(m))}catch{s("Form prepare \u56DE\u6267\u65E0\u6548\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error")}}e.method==="ui/resource-teardown"&&e.id!==void 0&&f({id:e.id,result:{}})}}var T=0,b=0;function E(){if(!l)return;let t=Math.ceil(document.documentElement.scrollHeight),e=Math.ceil(document.documentElement.clientWidth);t===T&&e===b||(T=t,b=e,R("ui/notifications/size-changed",{width:e,height:t}))}async function S(){if(window.parent===window){s("\u672A\u5728 ChatGPT MCP App iframe \u4E2D\u8FD0\u884C\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error");return}let t=++v,e=new Promise((o,i)=>{let c=setTimeout(()=>{d.delete(t),i(Error("FORM_APP_INIT_TIMEOUT"))},12e3);d.set(t,{resolve:o,reject:i,timer:c}),f({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)throw Error("FORM_APP_INIT_INVALID");l=!0,R("ui/notifications/initialized",{}),E(),m&&C(_(m)),typeof ResizeObserver=="function"&&new ResizeObserver(E).observe(document.documentElement)}catch{s("MCP App \u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u6838\u67E5 ChatGPT \u5BBF\u4E3B\u8FDE\u63A5\u3002","error")}}async function g(){if(!l||u||!n||!["GENERAL","TEST_ONLY"].includes(n.mode))return;let t=A(),e=r("comment").value.trim();if(!["A","B"].includes(t)||t==="B"&&!e)return;u=!0,p();let{formId:o,mode:i}=n,c=crypto.randomUUID(),h={mode:i,formId:o,choice:t,kind:n.kind,...t==="B"?{comment:e}:{},userTurn:"unverified-app-"+c,presentedAssistantRef:"app-form-"+o,writeRequestId:c,...i==="TEST_ONLY"?{projectId:n.projectId,chatRef:n.chatRef,documentId:n.documentId,version:n.version}:{}};s("\u6B63\u5728\u5411 Form submit \u63D0\u4EA4\u552F\u4E00\u8BF7\u6C42\u2026");let a;try{a=_(await O("tools/call",{name:"chat_loop_form__submit",arguments:h}))}catch{s("Submit \u7ED3\u679C\u672A\u77E5\uFF0C\u7981\u6B62\u91CD\u590D\u63D0\u4EA4\uFF1B\u8BF7\u67E5\u539F\u8BF7\u6C42\u56DE\u6267\u3002","error");return}if(a.status!=="FORM_SUBMISSION_OBSERVED_SOFT"||a.formId!==o||a.choice!==t||a.preparedFormIdVerified!==!0){s("Submit \u672A\u9A8C\u8BC1\u7ED1\u5B9A\uFF0C\u7528\u6237\u6D88\u606F\u672A\u53D1\u9001\u3002","error");return}let N=n.documentId?n.documentId+" v"+n.version:"\u81EA\u5B9A\u4E49\u8868\u5355",M="\u3010Chat Loop Form\uFF5C"+i+"\u3011formId="+o+"\uFF5C"+N+"\uFF5C"+(t==="A"?"A \u786E\u8BA4":"B \u4FEE\u6539\uFF1A"+e)+"\u3002\u7EC4\u4EF6\u8BF7\u6C42\u53D1\u9001\uFF0C\u7528\u6237\u6D88\u606F\u8EAB\u4EFD\u987B\u72EC\u7ACB\u6838\u5BF9\u3002"+(i==="TEST_ONLY"?"\u4E0D\u6784\u6210\u6B63\u5F0F\u5BA1\u6279\uFF0C\u4E0D Start/Continue/Handoff\u3002":"");s("Submit \u8F6F\u56DE\u6267\u6210\u529F\uFF0C\u6B63\u5728\u7533\u8BF7\u5355\u6B21\u7528\u6237\u6D88\u606F\u2026");try{let w=await O("ui/message",{role:"user",content:[{type:"text",text:M}]});s(w?.isError?"\u5BBF\u4E3B\u62D2\u7EDD\u6D88\u606F\uFF1B\u672A\u5B8C\u6210\u6B63\u5F0F\u5BA1\u6279\u3002":"\u5BBF\u4E3B\u63A5\u53D7\u6D88\u606F\u8BF7\u6C42\uFF1BuserMessageId \u4ECD\u9700\u72EC\u7ACB\u6838\u9A8C\u3002",w?.isError?"error":"ok")}catch{s("\u5BBF\u4E3B\u6D88\u606F\u72B6\u6001\u672A\u77E5\uFF0C\u7981\u6B62\u91CD\u590D\u53D1\u9001\u3002","error")}}window.addEventListener("message",L);I.forEach(t=>t.addEventListener("change",p));r("comment").addEventListener("input",p);r("submit").addEventListener("click",g);S();})();
43
+ <script>(()=>{var r=t=>document.getElementById(t),w=[...document.querySelectorAll('input[name="choice"]')],N=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/,T=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,u=new Map,P=0,s=!1,l=null,p=!1,_=null,d=null;function i(t,e="info"){r("status").textContent=t,r("status").dataset.state=e}function E(t){window.parent.postMessage({jsonrpc:"2.0",...t},"*")}function g(t,e={}){E({method:t,params:e})}function O(t,e){if(!s)throw Error("FORM_APP_NOT_INITIALIZED");return new Promise((o,n)=>{let c=++P,a=setTimeout(()=>{u.delete(c),n(Error("FORM_APP_REPLY_UNKNOWN"))},3e4);u.set(c,{resolve:o,reject:n,timer:a}),E({id:c,method:t,params:e})})}function b(t){if(t?.isError){let o=t.content?.find(n=>n.type==="text")?.text;throw Error(typeof o=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(o)?o:"FORM_TOOL_REJECTED")}if(t?.structuredContent?.status)return t.structuredContent;let e=t?.content?.find(o=>o.type==="text")?.text;if(typeof e!="string"||e.length>2e4)throw Error("FORM_RECEIPT_MISSING");return JSON.parse(e)}var M=()=>w.find(t=>t.checked)?.value||null;function m(){let t=M();r("options").disabled=!s,r("modify").hidden=t!=="B",r("submit").disabled=!s||!l||p||!t||t==="B"&&!r("comment").value.trim(),I()}function C(t){let e=t?.view;if(!e||e.template!=="chat-loop-review-card-v1"||typeof t.formId!="string"||!N.test(t.formId)||typeof t.traceRef!="string"||!T.test(t.traceRef)||e.formId!==t.formId||e.options?.length!==2||e.options[0]?.value!=="A"||e.options[1]?.value!=="B")throw Error("FORM_VIEW_INVALID");let o=l?.formId===t.formId&&l?.traceRef===t.traceRef&&p;l=t,r("title").textContent=e.title,r("description").textContent=e.description,r("a-label").textContent=e.options[0].label,r("b-label").textContent=e.options[1].label,r("comment").placeholder=e.modifyField?.placeholder||"\u586B\u5199\u4FEE\u6539\u610F\u89C1",r("submit").textContent=e.submit?.label||"\u63D0\u4EA4",r("footer").textContent=e.footer||"",r("options").disabled=!s,r("comment").value="",w.forEach(n=>n.checked=!1),p=o,i(d||(s?"\u8868\u5355\u5DF2\u51C6\u5907\uFF0C\u8BF7\u9009\u62E9 A \u6216 B\u3002":"\u8868\u5355\u5DF2\u51C6\u5907\uFF0C\u6B63\u5728\u7B49\u5F85\u5BBF\u4E3B\u80FD\u529B\u786E\u8BA4\u3002"),d?"error":s?"ok":"info"),m()}function v(t){if(t.source!==window.parent)return;let e=t.data;if(!(!e||e.jsonrpc!=="2.0"||typeof e!="object")){if(Object.hasOwn(e,"id")&&!Object.hasOwn(e,"method")){let o=u.get(e.id);if(!o)return;u.delete(e.id),clearTimeout(o.timer),e.error?o.reject(Error("MCP_APP_HOST_REJECTED")):o.resolve(e.result);return}if(e.method==="ui/notifications/tool-result"){_=e.params;try{C(b(_))}catch{i("Form prepare \u56DE\u6267\u65E0\u6548\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error")}}e.method==="ui/resource-teardown"&&e.id!==void 0&&E({id:e.id,result:{}})}}var R=0,A=0;function I(){if(!s)return;let t=Math.ceil(document.documentElement.scrollHeight),e=Math.ceil(document.documentElement.clientWidth);t===R&&e===A||(R=t,A=e,g("ui/notifications/size-changed",{width:e,height:t}))}async function x(){if(window.parent===window){i("\u672A\u5728 ChatGPT MCP App iframe \u4E2D\u8FD0\u884C\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error");return}let t=++P,e=new Promise((o,n)=>{let c=setTimeout(()=>{u.delete(t),n(Error("FORM_APP_INIT_TIMEOUT"))},12e3);u.set(t,{resolve:o,reject:n,timer:c}),E({id:t,method:"ui/initialize",params:{appInfo:{name:"Chat Loop Review",version:"1.0.1"},appCapabilities:{},protocolVersion:"2026-01-26"}})});try{let o=await e;if(!o?.protocolVersion||!o.hostInfo||!o.hostCapabilities)throw Error("FORM_APP_INIT_INVALID");if(!o.hostCapabilities.serverTools||!o.hostCapabilities.message?.text){d="\u5F53\u524D\u5BBF\u4E3B\u7F3A\u5C11 serverTools \u6216 message.text \u80FD\u529B\uFF0C\u8868\u5355\u4E0D\u53EF\u63D0\u4EA4\u3002",i(d,"error"),m();return}s=!0,d=null,g("ui/notifications/initialized",{}),I(),_&&C(b(_)),typeof ResizeObserver=="function"&&new ResizeObserver(I).observe(document.documentElement)}catch{d="MCP App \u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u6838\u67E5\u5BBF\u4E3B\u8FDE\u63A5\u4E0E\u534F\u8BAE\u80FD\u529B\u3002",i(d,"error"),s=!1,m()}}async function F(){if(!s||p||!l)return;let t=M(),e=r("comment").value.trim();if(!["A","B"].includes(t)||t==="B"&&!e)return;p=!0,m();let{formId:o,traceRef:n}=l,c={formId:o,traceRef:n,choice:t,...t==="B"?{comment:e}:{}};i("\u6B63\u5728\u63D0\u4EA4\u8868\u5355\u2026");let a;try{a=b(await O("tools/call",{name:"chat_loop_form__submit",arguments:c}))}catch(f){let h=typeof f?.message=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(f.message)?f.message:"FORM_APP_REPLY_UNKNOWN";i(h==="FORM_APP_REPLY_UNKNOWN"||h==="FORM_SUBMISSION_CLAIM_UNKNOWN"?"Submit \u7ED3\u679C\u672A\u77E5\uFF0C\u5DF2\u9501\u5B9A\uFF0C\u7981\u6B62\u91CD\u590D\u63D0\u4EA4\uFF1B\u8BF7\u67E5\u539F\u8BF7\u6C42\u56DE\u6267\u3002":h==="FORM_ALREADY_SUBMITTED"?"\u8BE5\u8868\u5355\u5DF2\u63D0\u4EA4\u8FC7\uFF0C\u7981\u6B62\u91CD\u590D\u53D1\u9001\uFF1B\u8BF7\u6838\u67E5\u539F\u6D88\u606F\u3002":"Submit \u660E\u786E\u5931\u8D25\uFF08"+h+"\uFF09\uFF0C\u7528\u6237\u6D88\u606F\u672A\u53D1\u9001\u3002","error");return}if(a.status!=="FORM_SUBMITTED"||a.formId!==o||a.traceRef!==n||a.choice!==t){i("Submit \u8FD4\u56DE\u7684\u4FE1\u606F\u4E0E\u5F53\u524D\u8868\u5355\u4E0D\u5339\u914D\uFF0C\u7528\u6237\u6D88\u606F\u672A\u53D1\u9001\u3002","error");return}let y="\u3010Chat Loop Form\u3011formId="+o+"\uFF5C"+(t==="A"?"A \u9009\u62E9":"B \u9009\u62E9\uFF1A"+e)+"\u3002";i("\u5355\u6B21\u63D0\u4EA4\u5DF2\u9501\u5B9A\uFF0C\u6B63\u5728\u7533\u8BF7\u5F53\u524D Chat \u7528\u6237\u6D88\u606F\u2026");try{let f=await O("ui/message",{role:"user",content:[{type:"text",text:y}]});i(f?.isError?"\u5BBF\u4E3B\u672A\u63A5\u53D7\u8868\u5355\u7ED3\u679C\u6D88\u606F\u3002":"\u5BBF\u4E3B\u5DF2\u63A5\u53D7\u7528\u6237\u6D88\u606F\u8BF7\u6C42\uFF1B\u5E73\u53F0\u6D88\u606F\u8EAB\u4EFD\u4ECD\u9700\u72EC\u7ACB\u6838\u9A8C\u3002",f?.isError?"error":"ok")}catch{i("\u7528\u6237\u6D88\u606F\u53D1\u9001\u72B6\u6001\u672A\u77E5\uFF0C\u5DF2\u9501\u5B9A\uFF0C\u7981\u6B62\u91CD\u8BD5\uFF1B\u8BF7\u6838\u67E5\u539F\u6D88\u606F\u3002","error")}}window.addEventListener("message",v);w.forEach(t=>t.addEventListener("change",m));r("comment").addEventListener("input",m);r("submit").addEventListener("click",F);x();})();
44
44
  </script>
45
45
  </body>
46
46
  </html>