@tomflow/chatloop-tools 0.9.16 → 0.9.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs CHANGED
@@ -209,6 +209,10 @@ async function runtime(){
209
209
  const callCache=new Map();
210
210
  const toolRouter=Object.freeze({
211
211
  list:mcpAudit.observe('mcp.tools.list',coreToolRouter.list,'mcp'),
212
+ listResources:mcpAudit.observe('mcp.resources.list',
213
+ coreToolRouter.listResources,'mcp'),
214
+ readResource:mcpAudit.observe('mcp.resources.read',
215
+ coreToolRouter.readResource,'mcp'),
212
216
  call(name,args){
213
217
  const label=typeof name==='string'&&
214
218
  /^[a-z][A-Za-z0-9_.:-]{1,119}$/.test(name)?name:'invalid';
package/lib/gateway.mjs CHANGED
@@ -7,7 +7,8 @@ export function configureGateway(ports){
7
7
  for(const key of ['CONTRACT','PACKAGE_VERSION','toolRouter','observeProtocol'])
8
8
  if(ports?.[key]===undefined)throw Error('TOOLS_PORT_MISSING:'+key);
9
9
  ({CONTRACT,PACKAGE_VERSION,toolRouter,observeProtocol}=ports);
10
- if(typeof toolRouter.list!=='function'||typeof toolRouter.call!=='function')
10
+ if(['list','call','listResources','readResource']
11
+ .some(k=>typeof toolRouter[k]!=='function'))
11
12
  throw Error('TOOLS_PORT_INVALID:toolRouter');
12
13
  if(typeof observeProtocol!=='function')
13
14
  throw Error('TOOLS_PORT_INVALID:observeProtocol');
@@ -34,7 +35,8 @@ export function runGateway(){
34
35
  return reject(m.id,-32602,'UNSUPPORTED_MCP_VERSION');
35
36
  connected=true;
36
37
  return reply(m.id,{protocolVersion:m.params.protocolVersion,
37
- capabilities:{tools:{}},serverInfo:{name:'chat-loop-local-tools',version:PACKAGE_VERSION}});
38
+ capabilities:{tools:{},resources:{}},
39
+ serverInfo:{name:'chat-loop-local-tools',version:PACKAGE_VERSION}});
38
40
  }
39
41
  if(m.method==='server/discover')return reject(m.id,-32601,'METHOD_NOT_FOUND');
40
42
  if(!connected)return reject(m.id,-32002,'NOT_INITIALIZED');
@@ -48,6 +50,16 @@ export function runGateway(){
48
50
  catch(e){return reply(m.id,failure(['ENOENT','ECONNREFUSED'].includes(e.code)
49
51
  ?'TOOL_UNAVAILABLE':e.code||'MANAGER_UNAVAILABLE'))}
50
52
  }
53
+ if(m.method==='resources/list'){
54
+ try{return reply(m.id,toolRouter.listResources())}
55
+ catch{return reject(m.id,-32603,'RESOURCE_CATALOG_INVALID')}
56
+ }
57
+ if(m.method==='resources/read'){
58
+ try{return reply(m.id,await toolRouter.readResource(m.params?.uri))}
59
+ catch(e){return reject(m.id,
60
+ e.code==='MCP_RESOURCE_NOT_FOUND'?-32002:-32602,
61
+ e.code==='MCP_RESOURCE_NOT_FOUND'?'RESOURCE_NOT_FOUND':'RESOURCE_READ_INVALID')}
62
+ }
51
63
  return reject(m.id,-32601,'METHOD_NOT_FOUND');
52
64
  };
53
65
  process.stdin.setEncoding('utf8');
@@ -67,7 +79,7 @@ export function runGateway(){
67
79
  // tools/list and tools/call already have their own runtime API spans;
68
80
  // every other addressed protocol request must also leave a trace.
69
81
  const handledByRouter=connected&&
70
- (m.method==='tools/list'||m.method==='tools/call');
82
+ ['tools/list','tools/call','resources/list','resources/read'].includes(m.method);
71
83
  const invoke=()=>processMessage(m);
72
84
  const task=handledByRouter?invoke():observeProtocol(m.method,invoke);
73
85
  void Promise.resolve(task).catch(()=>{
@@ -4,6 +4,27 @@ const failure=code=>({isError:true,content:[{type:'text',text:code}]});
4
4
  const fail=code=>Object.assign(Error(code),{code});
5
5
  const validName=name=>typeof name==='string'
6
6
  &&/^[a-z][a-z0-9_]*__[a-z][a-z0-9_]*$|^chat_loop_(?:context_get|context_mutate|trace_diagnose|trace_stage)$/.test(name);
7
+ const validUiUri=uri=>typeof uri==='string'
8
+ &&/^ui:\/\/[a-z0-9][a-z0-9._/-]{1,127}$/.test(uri);
9
+ function validToolMeta(meta,owned){
10
+ if(!meta||typeof meta!=='object'||Array.isArray(meta)
11
+ ||Object.keys(meta).some(k=>!
12
+ ['ui','openai/outputTemplate','openai/widgetAccessible'].includes(k)))return false;
13
+ const ui=meta.ui;
14
+ if(!ui||typeof ui!=='object'||Array.isArray(ui)
15
+ ||Object.keys(ui).some(k=>!['resourceUri','visibility'].includes(k)))return false;
16
+ if(ui.resourceUri!==undefined&&!owned.has(ui.resourceUri))return false;
17
+ if(ui.visibility!==undefined&&(!Array.isArray(ui.visibility)
18
+ ||!ui.visibility.length||ui.visibility.some(x=>!['model','app'].includes(x))))
19
+ return false;
20
+ if(ui.resourceUri===undefined
21
+ &&(!ui.visibility?.includes('app')||meta['openai/outputTemplate']!==undefined))
22
+ return false;
23
+ if(meta['openai/outputTemplate']!==undefined
24
+ &&meta['openai/outputTemplate']!==ui.resourceUri)return false;
25
+ return meta['openai/widgetAccessible']===undefined
26
+ ||meta['openai/widgetAccessible']===true;
27
+ }
7
28
 
8
29
  export function createMcpToolRouter(definitions,services={}){
9
30
  if(!Array.isArray(definitions)||!definitions.length)throw fail('MCP_PROVIDERS_MISSING');
@@ -28,8 +49,19 @@ export function createMcpToolRouter(definitions,services={}){
28
49
  instances.push({id:def.id,instance});
29
50
  }
30
51
  const active=()=>{
31
- const byName=new Map(),listed=[];
52
+ const byName=new Map(),listed=[],byUri=new Map(),resources=[];
32
53
  for(const {id,instance} of instances){
54
+ const owned=new Set();
55
+ for(const resource of instance.resources?.()??[]){
56
+ if(!validUiUri(resource?.uri)||byUri.has(resource.uri)
57
+ ||typeof resource.name!=='string'||!resource.name.trim()
58
+ ||resource.mimeType!=='text/html;profile=mcp-app'
59
+ ||typeof instance.readResource!=='function')
60
+ throw fail('MCP_RESOURCE_LIST_INVALID');
61
+ owned.add(resource.uri);
62
+ byUri.set(resource.uri,instance);
63
+ resources.push(resource);
64
+ }
33
65
  const tools=instance.tools();
34
66
  if(!Array.isArray(tools))throw fail('MCP_TOOL_LIST_INVALID');
35
67
  const localNames=new Set();
@@ -37,17 +69,32 @@ export function createMcpToolRouter(definitions,services={}){
37
69
  if(!tool||!validName(tool.name)||owners.get(tool.name)!==id
38
70
  ||localNames.has(tool.name)||byName.has(tool.name)
39
71
  ||!tool.inputSchema||typeof tool.description!=='string'
40
- ||Object.hasOwn(tool,'_meta'))
72
+ ||(Object.hasOwn(tool,'_meta')
73
+ &&!validToolMeta(tool._meta,owned)))
41
74
  throw fail('MCP_TOOL_LIST_INVALID');
42
75
  localNames.add(tool.name);
43
76
  byName.set(tool.name,instance);
44
77
  listed.push(tool);
45
78
  }
46
79
  }
47
- return {listed,byName};
80
+ return {listed,byName,byUri,resources};
48
81
  };
49
82
  return Object.freeze({
50
83
  list(){return active().listed;},
84
+ listResources(){return {resources:active().resources};},
85
+ async readResource(uri){
86
+ if(!validUiUri(uri))throw fail('MCP_RESOURCE_URI_INVALID');
87
+ const instance=active().byUri.get(uri);
88
+ if(!instance)throw fail('MCP_RESOURCE_NOT_FOUND');
89
+ const result=await instance.readResource(uri);
90
+ if(!result||!Array.isArray(result.contents)||result.contents.length!==1
91
+ ||result.contents[0].uri!==uri
92
+ ||result.contents[0].mimeType!=='text/html;profile=mcp-app'
93
+ ||typeof result.contents[0].text!=='string'
94
+ ||Buffer.byteLength(result.contents[0].text,'utf8')>786432)
95
+ throw fail('MCP_RESOURCE_RESULT_INVALID');
96
+ return result;
97
+ },
51
98
  async call(name,args){
52
99
  const instance=active().byName.get(name);
53
100
  if(!instance)return failure('UNKNOWN_TOOL');
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.16",
6
+ "version": "0.9.18",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -13,6 +13,7 @@
13
13
  "index.mjs",
14
14
  "providers.generated.mjs",
15
15
  "providers/",
16
+ "ui/",
16
17
  "lib/",
17
18
  "bin/",
18
19
  "scripts/",
@@ -24,22 +25,28 @@
24
25
  "test": "node --test ./test/*.test.mjs",
25
26
  "build:providers": "node ./scripts/build-providers.mjs",
26
27
  "build:providers:check": "node ./scripts/build-providers.mjs --check",
27
- "pretest": "node ./scripts/build-providers.mjs --check",
28
- "prepack": "node ./scripts/build-providers.mjs --check"
28
+ "build:form": "node ./scripts/build-form-app.mjs",
29
+ "build:form:check": "node ./scripts/build-form-app.mjs --check",
30
+ "pretest": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check",
31
+ "prepack": "node ./scripts/build-providers.mjs --check && node ./scripts/build-form-app.mjs --check"
29
32
  },
30
33
  "dependencies": {
31
- "@wonderwhy-er/desktop-commander": "0.2.44",
32
34
  "@tomflow/chatloop-context": "0.6.11",
33
- "@tomflow/chatloop-trace": "0.4.4"
35
+ "@tomflow/chatloop-trace": "0.4.4",
36
+ "@wonderwhy-er/desktop-commander": "0.2.44"
34
37
  },
35
38
  "engines": {
36
39
  "node": ">=24"
37
40
  },
38
41
  "optionalDependencies": {
39
- "@tomflow/chatloop-tunnel-darwin-x64": "0.0.24",
40
- "@tomflow/chatloop-tunnel-darwin-arm64": "0.0.24"
42
+ "@tomflow/chatloop-tunnel-darwin-arm64": "0.0.24",
43
+ "@tomflow/chatloop-tunnel-darwin-x64": "0.0.24"
41
44
  },
42
45
  "exports": {
43
46
  ".": "./index.mjs"
47
+ },
48
+ "devDependencies": {
49
+ "@modelcontextprotocol/ext-apps": "1.7.5",
50
+ "esbuild": "0.28.2"
44
51
  }
45
52
  }
@@ -1,6 +1,9 @@
1
1
  // Fixed ChatGPT card adapter, not a second approval authority.
2
2
  // Form IDs identify interactions; Context Issue IDs own R/P decisions.
3
3
  import {randomUUID} from 'node:crypto';
4
+ import {readFileSync} from 'node:fs';
5
+ const RESOURCE_URI='ui://chat-loop/form/review-v2';
6
+ const RESOURCE_MIME='text/html;profile=mcp-app';
4
7
  const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
5
8
  const FORM_ID=/^[A-Za-z0-9_-]{8,80}$/;
6
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;
@@ -8,7 +11,8 @@ const ISSUE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8
11
  const HASH=/^[a-f0-9]{64}$/;
9
12
  const fail=code=>Object.assign(Error(code),{code});
10
13
  const err=code=>({isError:true,content:[{type:'text',text:code}]});
11
- const ok=value=>({content:[{type:'text',text:JSON.stringify(value)}]});
14
+ const ok=value=>({content:[{type:'text',text:JSON.stringify(value)}],
15
+ structuredContent:value});
12
16
  const filled=(s,max)=>typeof s==='string'&&s.trim().length>0&&s.length<=max;
13
17
  const shape=(v,fields)=>v&&typeof v==='object'&&!Array.isArray(v)
14
18
  &&Object.keys(v).every(k=>fields.includes(k));
@@ -42,7 +46,9 @@ const tools=[
42
46
  required:['mode','card'],
43
47
  properties:{...common,contentHash:{type:'string',pattern:HASH.source},
44
48
  card:cardSchema}},
45
- annotations:{readOnlyHint:false}},
49
+ annotations:{readOnlyHint:false},
50
+ _meta:{ui:{resourceUri:RESOURCE_URI,visibility:['model','app']},
51
+ 'openai/outputTemplate':RESOURCE_URI,'openai/widgetAccessible':true}},
46
52
  {name:'chat_loop_form__submit',description:
47
53
  '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.',
48
54
  inputSchema:{type:'object',additionalProperties:false,
@@ -52,7 +58,9 @@ const tools=[
52
58
  comment:{type:'string',maxLength:4000},
53
59
  userTurn:{type:'string',minLength:8,maxLength:256},
54
60
  presentedAssistantRef:{type:'string',minLength:8,maxLength:256}}},
55
- annotations:{readOnlyHint:false}}
61
+ annotations:{readOnlyHint:false},
62
+ _meta:{ui:{visibility:['model','app']},
63
+ 'openai/widgetAccessible':true}}
56
64
  ];
57
65
  function check(a,fields){
58
66
  if(!shape(a,fields)||!['GENERAL','TEST_ONLY','MANAGED'].includes(a.mode)
@@ -127,7 +135,9 @@ async function prepare(a,context,form){
127
135
  const formId=a.formId||randomUUID();
128
136
  if(a.mode!=='MANAGED'){
129
137
  return {status:a.mode==='TEST_ONLY'?'TEST_ONLY_PREVIEW':'FORM_PREPARED_SOFT',
130
- formId,kind:a.kind||'CUSTOM',
138
+ formId,mode:a.mode,kind:a.kind||'CUSTOM',
139
+ ...(a.projectId?{projectId:a.projectId}:{}),
140
+ ...(a.chatRef?{chatRef:a.chatRef}:{}),
131
141
  ...(a.documentId?{documentId:a.documentId,version:a.version}:{}),
132
142
  view:view(a,formId,null,a.kind!=='CUSTOM'&&a.version>1
133
143
  ?a.documentId[0]+(a.version-1):null),
@@ -156,13 +166,14 @@ async function prepare(a,context,form){
156
166
  // a caller-supplied formId is a separate non-authoritative UI correlation ID.
157
167
  const managedFormId=a.formId||issue.issueId;
158
168
  return {status:'WAITING_APPROVAL',formId:managedFormId,issueId:issue.issueId,
169
+ mode:a.mode,projectId:a.projectId,taskId:a.taskId,
159
170
  documentId:a.documentId,version:a.version,kind:a.kind,
160
171
  taskRevision:issue.taskRevision,approvalRevision:issue.approvalRevision,
161
172
  writeRequestId:a.writeRequestId,trace:trace(form),
162
173
  view:view(a,managedFormId,issue.issueId,prior),approvalAuthority:'CONTEXT',
163
174
  businessSideEffects:true};
164
175
  }
165
- async function submit(a,context,form){
176
+ function validateSubmit(a){
166
177
  check(a,SUBMIT);
167
178
  if(!FORM_ID.test(a.formId||'')||!['A','B'].includes(a.choice)
168
179
  ||!filled(a.userTurn,256)||!filled(a.presentedAssistantRef,256)
@@ -171,6 +182,11 @@ async function submit(a,context,form){
171
182
  if(a.choice==='B'&&!filled(a.comment,4000)
172
183
  ||a.choice==='A'&&a.comment!==undefined&&a.comment!=='')
173
184
  throw fail('FORM_COMMENT_INVALID');
185
+ if(a.mode==='MANAGED'&&!ISSUE.test(a.issueId||''))
186
+ throw fail('FORM_ISSUE_REF_REQUIRED');
187
+ }
188
+ async function submit(a,context,form){
189
+ validateSubmit(a);
174
190
  if(a.mode!=='MANAGED'){
175
191
  return {status:'FORM_SUBMISSION_OBSERVED_SOFT',formId:a.formId,
176
192
  choice:a.choice,trace:trace(form),approvalAuthority:'NONE',
@@ -199,13 +215,59 @@ async function submit(a,context,form){
199
215
  export const provider=Object.freeze({
200
216
  id:'form',order:5,names:tools.map(x=>x.name),
201
217
  create({context,form}={}){
218
+ // Bounded, process-local UI correlation only. Context is still the
219
+ // authoritative MANAGED Issue store; a cache hit is NOT user proof.
220
+ const forms=new Map(),TTL=30*60*1000;
221
+ const lookup=id=>{
222
+ const record=forms.get(id);
223
+ if(!record||Date.now()-record.at>TTL){forms.delete(id);return null}
224
+ return record;
225
+ };
202
226
  return Object.freeze({
203
227
  tools:()=>tools,
228
+ resources:()=>[{uri:RESOURCE_URI,name:'Chat Loop Review',
229
+ mimeType:RESOURCE_MIME,description:'A/B review with one locked submit'}],
230
+ async readResource(uri){
231
+ if(uri!==RESOURCE_URI)throw fail('MCP_RESOURCE_NOT_FOUND');
232
+ return {contents:[{uri,mimeType:RESOURCE_MIME,
233
+ text:readFileSync(new URL('../ui/form/review.html',import.meta.url),'utf8'),
234
+ _meta:{'openai/ui':{availableDisplayModes:['inline'],
235
+ preferredDisplayMode:'inline'}}}]};
236
+ },
204
237
  async call(name,args){
205
238
  try{
206
- const result=name===tools[0].name
207
- ?await prepare(args,context,form)
208
- :name===tools[1].name?await submit(args,context,form):null;
239
+ const isPrepare=name===tools[0].name;
240
+ const isSubmit=name===tools[1].name;
241
+ if(isSubmit){
242
+ validateSubmit(args);
243
+ const prior=lookup(args?.formId);
244
+ if(!prior)throw fail('FORM_NOT_PREPARED');
245
+ if(prior.submitted)throw fail('FORM_ALREADY_SUBMITTED');
246
+ for(const key of ['mode','projectId','chatRef','taskId','kind',
247
+ 'documentId','version','issueId']){
248
+ if(args.mode==='GENERAL'&&key==='kind'&&args.kind===undefined)
249
+ continue; // Backward-compatible optional generic kind.
250
+ if(prior.args[key]!==args?.[key]&&(
251
+ prior.args[key]!==undefined||args?.[key]!==undefined))
252
+ throw fail('FORM_SCOPE_MISMATCH');
253
+ }
254
+ // Mark before async Context call. UNKNOWN is never retried with
255
+ // a different request ID; the real Context receipt remains owner.
256
+ prior.submitted=true;
257
+ }
258
+ const result=isPrepare?await prepare(args,context,form)
259
+ :isSubmit?await submit(args,context,form):null;
260
+ if(isSubmit&&result&&args.mode!=='MANAGED')
261
+ result.preparedFormIdVerified=true;
262
+ if(isPrepare&&result){
263
+ for(const [id,record] of forms){
264
+ if(Date.now()-record.at>TTL)forms.delete(id);
265
+ }
266
+ if(forms.size>=256)forms.delete(forms.keys().next().value);
267
+ forms.set(result.formId,{at:Date.now(),submitted:false,
268
+ args:{...args,kind:result.kind,formId:result.formId,
269
+ issueId:result.issueId}});
270
+ }
209
271
  if(result&&args?.projectId&&typeof form?.observe==='function'){
210
272
  const parent=trace(form);
211
273
  if(parent)setImmediate(()=>{
@@ -0,0 +1,27 @@
1
+ // Deterministic, self-contained MCP App HTML artifact. SDK is build-only.
2
+ import {build} from 'esbuild';
3
+ import {readFileSync,writeFileSync} from 'node:fs';
4
+ import {dirname,join} from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ const base=dirname(dirname(fileURLToPath(import.meta.url)));
7
+ const template=readFileSync(join(base,'ui/form/review.template.html'),'utf8');
8
+ const result=await build({
9
+ entryPoints:[join(base,'ui/form/review-app.js')],
10
+ bundle:true,platform:'browser',format:'iife',target:'es2022',
11
+ minify:true,write:false,legalComments:'none',
12
+ logLevel:'silent'
13
+ });
14
+ if(result.outputFiles.length!==1)throw Error('FORM_BUNDLE_INVALID');
15
+ const script=result.outputFiles[0].text.replace(/<\/script/gi,'<\\/script');
16
+ const token='<!-- CHAT_LOOP_FORM_SCRIPT -->';
17
+ if(template.split(token).length!==2)throw Error('FORM_TEMPLATE_INVALID');
18
+ const rendered=template.replace(token,'<script>'+script+'</script>');
19
+ const path=join(base,'ui/form/review.html');
20
+ if(process.argv.includes('--check')){
21
+ let actual;try{actual=readFileSync(path,'utf8')}catch{}
22
+ if(actual!==rendered)throw Error('FORM_APP_BUILD_STALE');
23
+ console.log('MCP_FORM_APP_CURRENT bytes='+Buffer.byteLength(rendered));
24
+ }else{
25
+ writeFileSync(path,rendered);
26
+ console.log('MCP_FORM_APP_BUILT bytes='+Buffer.byteLength(rendered));
27
+ }
@@ -0,0 +1,179 @@
1
+ // Minimal MCP Apps View bridge: JSON-RPC over postMessage, no bundled runtime.
2
+ // Protocol: https://modelcontextprotocol.io/extensions/apps
3
+ // GENERAL/TEST_ONLY only; MANAGED approval remains Context + real user Turn.
4
+ const $=id=>document.getElementById(id);
5
+ const options=[...document.querySelectorAll('input[name="choice"]')];
6
+ const idPattern=/^[A-Za-z0-9_-]{8,80}$/;
7
+ const requests=new Map();
8
+ let seq=0,connected=false,prepared=null,locked=false,toolResult=null;
9
+ function status(message,state='info'){
10
+ $('status').textContent=message;
11
+ $('status').dataset.state=state;
12
+ }
13
+ function send(message){window.parent.postMessage({jsonrpc:'2.0',...message},'*')}
14
+ function notify(method,params={}){send({method,params})}
15
+ function call(method,params){
16
+ if(!connected)throw Error('FORM_APP_NOT_INITIALIZED');
17
+ return new Promise((resolve,reject)=>{
18
+ const id=++seq;
19
+ // A timeout never authorizes a retry of a write.
20
+ const timer=setTimeout(()=>{
21
+ requests.delete(id);reject(Error('FORM_APP_REPLY_UNKNOWN'));
22
+ },30000);
23
+ requests.set(id,{resolve,reject,timer});
24
+ send({id,method,params});
25
+ });
26
+ }
27
+ function decode(result){
28
+ if(result?.isError)throw Error('FORM_TOOL_REJECTED');
29
+ if(result?.structuredContent?.status)return result.structuredContent;
30
+ const text=result?.content?.find(x=>x.type==='text')?.text;
31
+ if(typeof text!=='string'||text.length>20000)throw Error('FORM_RECEIPT_MISSING');
32
+ return JSON.parse(text);
33
+ }
34
+ const selected=()=>options.find(x=>x.checked)?.value||null;
35
+ function update(){
36
+ const choice=selected();
37
+ $('modify').hidden=choice!=='B';
38
+ $('submit').disabled=!prepared||locked||!choice
39
+ ||(choice==='B'&&!$('comment').value.trim());
40
+ resize();
41
+ }
42
+ function render(value){
43
+ const view=value?.view;
44
+ if(!view||view.template!=='chat-loop-review-card-v1'
45
+ ||!idPattern.test(value.formId||'')
46
+ ||view.formId!==value.formId
47
+ ||!['GENERAL','TEST_ONLY','MANAGED'].includes(view.mode)
48
+ ||view.options?.length!==2
49
+ ||view.options[0]?.value!=='A'||view.options[1]?.value!=='B')
50
+ throw Error('FORM_VIEW_INVALID');
51
+ const safe=view.mode==='GENERAL'||view.mode==='TEST_ONLY';
52
+ prepared={...value,mode:view.mode};
53
+ $('title').textContent=view.title;
54
+ $('description').textContent=view.description;
55
+ $('a-label').textContent=view.options[0].label;
56
+ $('b-label').textContent=view.options[1].label;
57
+ $('comment').placeholder=view.modifyField?.placeholder||'填写修改意见';
58
+ $('submit').textContent=view.submit?.label||'提交';
59
+ $('footer').textContent=view.footer||'';
60
+ $('options').disabled=!safe;
61
+ $('comment').value='';
62
+ options.forEach(x=>x.checked=false);
63
+ locked=!safe;
64
+ status(safe?'已连接 Form prepare;请选择 A 或 B。':
65
+ '正式审批需要真实用户消息身份,组件不得代签。',safe?'ok':'error');
66
+ update();
67
+ }
68
+ function receive(event){
69
+ if(event.source!==window.parent)return;
70
+ const message=event.data;
71
+ if(!message||message.jsonrpc!=='2.0'||typeof message!=='object')return;
72
+ if(Object.hasOwn(message,'id')&&!Object.hasOwn(message,'method')){
73
+ const request=requests.get(message.id);
74
+ if(!request)return;
75
+ requests.delete(message.id);clearTimeout(request.timer);
76
+ if(message.error)request.reject(Error('MCP_APP_HOST_REJECTED'));
77
+ else request.resolve(message.result);
78
+ return;
79
+ }
80
+ if(message.method==='ui/notifications/tool-result'){
81
+ toolResult=message.params;
82
+ try{render(decode(toolResult))}
83
+ catch{status('Form prepare 回执无效,禁止提交。','error')}
84
+ }
85
+ if(message.method==='ui/resource-teardown'&&message.id!==undefined)
86
+ send({id:message.id,result:{}});
87
+ }
88
+ let lastHeight=0,lastWidth=0;
89
+ function resize(){
90
+ if(!connected)return;
91
+ const height=Math.ceil(document.documentElement.scrollHeight);
92
+ const width=Math.ceil(document.documentElement.clientWidth);
93
+ if(height===lastHeight&&width===lastWidth)return;
94
+ lastHeight=height;lastWidth=width;
95
+ notify('ui/notifications/size-changed',{width,height});
96
+ }
97
+ async function initialize(){
98
+ if(window.parent===window){
99
+ status('未在 ChatGPT MCP App iframe 中运行,禁止提交。','error');
100
+ return;
101
+ }
102
+ const id=++seq;
103
+ const init=new Promise((resolve,reject)=>{
104
+ const timer=setTimeout(()=>{
105
+ requests.delete(id);reject(Error('FORM_APP_INIT_TIMEOUT'));
106
+ },12000);
107
+ requests.set(id,{resolve,reject,timer});
108
+ send({id,method:'ui/initialize',params:{
109
+ appInfo:{name:'Chat Loop Review',version:'1.0.1'},
110
+ appCapabilities:{},
111
+ protocolVersion:'2026-01-26'
112
+ }});
113
+ });
114
+ try{
115
+ const response=await init;
116
+ if(!response?.protocolVersion||!response.hostInfo)
117
+ throw Error('FORM_APP_INIT_INVALID');
118
+ connected=true;
119
+ notify('ui/notifications/initialized',{});
120
+ resize();
121
+ if(toolResult)render(decode(toolResult));
122
+ if(typeof ResizeObserver==='function')
123
+ new ResizeObserver(resize).observe(document.documentElement);
124
+ }catch{
125
+ status('MCP App 初始化失败,请核查 ChatGPT 宿主连接。','error');
126
+ }
127
+ }
128
+ async function submit(){
129
+ if(!connected||locked||!prepared
130
+ ||!['GENERAL','TEST_ONLY'].includes(prepared.mode))return;
131
+ const choice=selected(),comment=$('comment').value.trim();
132
+ if(!['A','B'].includes(choice)||choice==='B'&&!comment)return;
133
+ 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 提交唯一请求…');
145
+ let receipt;
146
+ try{receipt=decode(await call('tools/call',{
147
+ name:'chat_loop_form__submit',arguments:args
148
+ }))}
149
+ catch{
150
+ status('Submit 结果未知,禁止重复提交;请查原请求回执。','error');
151
+ return;
152
+ }
153
+ if(receipt.status!=='FORM_SUBMISSION_OBSERVED_SOFT'
154
+ ||receipt.formId!==formId||receipt.choice!==choice
155
+ ||receipt.preparedFormIdVerified!==true){
156
+ status('Submit 未验证绑定,用户消息未发送。','error');
157
+ return;
158
+ }
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 软回执成功,正在申请单次用户消息…');
166
+ try{
167
+ const result=await call('ui/message',{
168
+ role:'user',content:[{type:'text',text}]
169
+ });
170
+ status(result?.isError?'宿主拒绝消息;未完成正式审批。':
171
+ '宿主接受消息请求;userMessageId 仍需独立核验。',
172
+ result?.isError?'error':'ok');
173
+ }catch{status('宿主消息状态未知,禁止重复发送。','error')}
174
+ }
175
+ window.addEventListener('message',receive);
176
+ options.forEach(x=>x.addEventListener('change',update));
177
+ $('comment').addEventListener('input',update);
178
+ $('submit').addEventListener('click',submit);
179
+ void initialize();
@@ -0,0 +1,46 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>Chat Loop 表单</title>
7
+ <style>
8
+ :root{color-scheme:light dark;font:14px/1.5 system-ui,-apple-system,sans-serif}
9
+ *{box-sizing:border-box}
10
+ body{margin:0;padding:16px;color:var(--app-color,#191919);background:transparent}
11
+ main{max-width:760px;margin:auto;padding:16px;border:1px solid #aaa6;border-radius:12px}
12
+ h1{font-size:16px;margin:0 0 6px}
13
+ p{margin:6px 0 12px;color:inherit}
14
+ small{color:#888}
15
+ fieldset{border:0;padding:0;margin:8px 0}
16
+ label.option{display:flex;align-items:center;gap:10px;padding:10px 8px;cursor:pointer}
17
+ label.option+label.option{border-top:1px solid #aaa3}
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}
20
+ button{width:100%;margin:12px 0;padding:10px 12px;border:0;border-radius:24px;background:#186ac1;color:white;font:inherit;cursor:pointer}
21
+ button:disabled{opacity:.44;cursor:not-allowed}
22
+ [hidden]{display:none!important}
23
+ #status{font-size:12px;white-space:pre-wrap;overflow-wrap:anywhere}
24
+ #status[data-state=error]{color:#bf3030}
25
+ #status[data-state=ok]{color:#247d48}
26
+ @media(prefers-color-scheme:dark){button{background:#4295e8}textarea{border-color:#888}}
27
+ </style>
28
+ </head>
29
+ <body>
30
+ <main aria-live="polite">
31
+ <h1 id="title">Chat Loop 表单</h1>
32
+ <p id="description">正在连接表单工具…</p>
33
+ <fieldset id="options" disabled>
34
+ <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>
37
+ </fieldset>
38
+ <div id="modify" hidden><textarea id="comment" maxlength="4000"></textarea></div>
39
+ <button id="submit" disabled>提交评审</button>
40
+ <div id="status" role="status">等待真实 MCP Form prepare 回执</div>
41
+ <small id="footer"></small>
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();})();
44
+ </script>
45
+ </body>
46
+ </html>
@@ -0,0 +1,45 @@
1
+ <!DOCTYPE html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width,initial-scale=1">
6
+ <title>Chat Loop 表单</title>
7
+ <style>
8
+ :root{color-scheme:light dark;font:14px/1.5 system-ui,-apple-system,sans-serif}
9
+ *{box-sizing:border-box}
10
+ body{margin:0;padding:16px;color:var(--app-color,#191919);background:transparent}
11
+ main{max-width:760px;margin:auto;padding:16px;border:1px solid #aaa6;border-radius:12px}
12
+ h1{font-size:16px;margin:0 0 6px}
13
+ p{margin:6px 0 12px;color:inherit}
14
+ small{color:#888}
15
+ fieldset{border:0;padding:0;margin:8px 0}
16
+ label.option{display:flex;align-items:center;gap:10px;padding:10px 8px;cursor:pointer}
17
+ label.option+label.option{border-top:1px solid #aaa3}
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}
20
+ button{width:100%;margin:12px 0;padding:10px 12px;border:0;border-radius:24px;background:#186ac1;color:white;font:inherit;cursor:pointer}
21
+ button:disabled{opacity:.44;cursor:not-allowed}
22
+ [hidden]{display:none!important}
23
+ #status{font-size:12px;white-space:pre-wrap;overflow-wrap:anywhere}
24
+ #status[data-state=error]{color:#bf3030}
25
+ #status[data-state=ok]{color:#247d48}
26
+ @media(prefers-color-scheme:dark){button{background:#4295e8}textarea{border-color:#888}}
27
+ </style>
28
+ </head>
29
+ <body>
30
+ <main aria-live="polite">
31
+ <h1 id="title">Chat Loop 表单</h1>
32
+ <p id="description">正在连接表单工具…</p>
33
+ <fieldset id="options" disabled>
34
+ <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>
37
+ </fieldset>
38
+ <div id="modify" hidden><textarea id="comment" maxlength="4000"></textarea></div>
39
+ <button id="submit" disabled>提交评审</button>
40
+ <div id="status" role="status">等待真实 MCP Form prepare 回执</div>
41
+ <small id="footer"></small>
42
+ </main>
43
+ <!-- CHAT_LOOP_FORM_SCRIPT -->
44
+ </body>
45
+ </html>