@tomflow/chatloop-tools 0.9.29 → 0.9.31

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
@@ -66,7 +66,7 @@ The six built-in Providers are:
66
66
  - `runtime`: exact-request receipt lookup without replay
67
67
  - `context`: independent Context SDK read/write schemas and fixed CLI
68
68
  - `trace`: Project-scoped diagnosis and SOFT stage observations, plus a bearer-token-scoped Form Trace lookup using the Prepare `traceRef`
69
- - `form`: a stateless generic single-select MCP App. `prepare` validates caller-defined options and optional text input, preserves or generates `formId`, and returns a random `traceRef`; the app-only `render` acknowledgement records that the view was displayed; `submit` returns the selected value/label and optional text; the UI may forward the confirmed selection to future model context with `ui/update-model-context` (never a user Turn or business approval), without showing raw receipt JSON. A Render ACK failure is exposed as DOM diagnostic state, not misreported as a confirmed Render event. It does not send Chat messages, interpret business meaning, call Context, retain prepared-form state, create a submission ledger, or impose expiry. Prepare/Render/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.
69
+ - `form`: a stateless generic single-select MCP App. `prepare` validates caller-defined options, optional plain-text read-only document (`card.document`, at most 24,000 characters, shown above the choices), and optional text input, preserves or generates `formId`, and returns a random `traceRef`; the app-only `render` acknowledgement records that the view was displayed; `submit` returns the selected value/label and optional text; the UI may forward the confirmed selection to future model context with `ui/update-model-context` (never a user Turn or business approval), without showing raw receipt JSON. A Render ACK failure is exposed as DOM diagnostic state, not misreported as a confirmed Render event. It does not send Chat messages, interpret business meaning, call Context, retain prepared-form state, create a submission ledger, or impose expiry. Prepare/Render/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.
70
70
 
71
71
  `npm run build:providers` generates `providers.generated.mjs`, the static
72
72
  assembly and release fingerprint manifest. Both `tools/list` and `tools/call`
package/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  // Sole npm SDK entry and composition root for Chat Loop Tools.
2
2
  // Modules declare named API ports. No lib module imports another lib module.
3
3
  import {randomUUID} from 'node:crypto';
4
+ import {dirname,join} from 'node:path';
4
5
  import {subscribeContextApiLog} from '@tomflow/chatloop-context';
5
6
  import {createApiAspect,subscribeTraceApiLog} from '@tomflow/chatloop-trace';
6
7
  import {providerDefinitions} from './providers.generated.mjs';
@@ -274,6 +275,14 @@ async function runtime(){
274
275
  ensurePrivateDir:control.ensurePrivateDir,ACTIONS:control.ACTIONS,
275
276
  createAdapter:adapters.createAdapter,
276
277
  createSupervisorTraceBridge:traceObservation.createSupervisorTraceBridge,
278
+ // The same owned Tunnel profile defines the MCP child's grants. Feed
279
+ // only its validated observation scopes into the Supervisor's writer;
280
+ // never export those grants into unrelated child-process environments.
281
+ readObservationGrants:()=>{
282
+ try{return releaseUpgrade.readSupervisorMcpGrants(join(
283
+ dirname(control.paths().dir),'tunnel','profiles','chat-loop.yaml'))}
284
+ catch{return {}}
285
+ },
277
286
  loadContextControlSecret:contextAuth.loadContextControlSecret,
278
287
  handleContextControl:contextRun.handleContextControl
279
288
  });
@@ -96,7 +96,7 @@ export async function verifyMcpTools(p,ports={}){
96
96
  if(!names.includes(name))throw Object.assign(Error('MCP_PROBE_REQUIRED_TOOL_MISSING'),{
97
97
  code:'MCP_PROBE_REQUIRED_TOOL_MISSING'});
98
98
  const resources=await request('resources/list');
99
- const uri=resources.result?.resources?.find(x=>x.uri==='ui://chat-loop/form/v3')?.uri;
99
+ const uri=resources.result?.resources?.find(x=>x.uri==='ui://chat-loop/form/v4')?.uri;
100
100
  if(!uri)throw Object.assign(Error('MCP_PROBE_FORM_RESOURCE_MISSING'),{
101
101
  code:'MCP_PROBE_FORM_RESOURCE_MISSING'});
102
102
  const view=await request('resources/read',{uri});
@@ -90,6 +90,39 @@ export function preservedMcpEnvironmentPrefix(command){
90
90
  return match[0]+' ';
91
91
  }
92
92
 
93
+ // The Tunnel profile is the authority for the MCP child grants. A Supervisor
94
+ // launched by an ordinary CLI may not inherit those grants; recover only the
95
+ // non-secret, single-Project observation grants from the trusted profile.
96
+ const SUPERVISOR_GRANT_KEYS=new Set([
97
+ 'CHAT_LOOP_CONTEXT_API_ENABLE','CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS',
98
+ 'CHAT_LOOP_TRACE_API_ENABLE','CHAT_LOOP_TRACE_ALLOWED_PROJECTS'
99
+ ]);
100
+ const SINGLE_PROJECT=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
101
+ export function readSupervisorMcpGrants(profilePath){
102
+ const file=lstatSync(profilePath);
103
+ if(!file.isFile()||file.isSymbolicLink()||(file.mode&0o077)
104
+ ||(process.getuid&&file.uid!==process.getuid()))
105
+ throw Object.assign(Error('RELEASE_PROFILE_UNTRUSTED'),{code:'RELEASE_PROFILE_UNTRUSTED'});
106
+ const profile=JSON.parse(readFileSync(profilePath,'utf8'));
107
+ const main=profile?.mcp?.commands?.filter(x=>x.channel==='main');
108
+ if(main?.length!==1||typeof main[0].command!=='string')
109
+ throw Object.assign(Error('RELEASE_PROFILE_MCP_NOT_FOUND'),{code:'RELEASE_PROFILE_MCP_NOT_FOUND'});
110
+ const prefix=preservedMcpEnvironmentPrefix(main[0].command),grants={};
111
+ for(const [,assignment] of prefix.matchAll(/ "([^"]+)"/g)){
112
+ const offset=assignment.indexOf('='),key=assignment.slice(0,offset);
113
+ if(SUPERVISOR_GRANT_KEYS.has(key))grants[key]=assignment.slice(offset+1);
114
+ }
115
+ for(const [enabled,project] of [
116
+ ['CHAT_LOOP_CONTEXT_API_ENABLE','CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS'],
117
+ ['CHAT_LOOP_TRACE_API_ENABLE','CHAT_LOOP_TRACE_ALLOWED_PROJECTS']]){
118
+ if(grants[enabled]!==undefined&&grants[enabled]!=='1'||
119
+ grants[enabled]==='1'&&!SINGLE_PROJECT.test(grants[project]||''))
120
+ throw Object.assign(Error('RELEASE_PROFILE_GRANT_INVALID'),
121
+ {code:'RELEASE_PROFILE_GRANT_INVALID'});
122
+ }
123
+ return grants;
124
+ }
125
+
93
126
  export async function upgradeRuntime(options={}){
94
127
  if(options.args?.length)return freshResult('FAILED',{code:'INVALID_ARGUMENT'});
95
128
  const base=checkedUpgradeBase(options);
@@ -7,7 +7,8 @@ const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
7
7
  'ownerNonce','managerPid']);
8
8
 
9
9
  export function createSupervisorObservability({
10
- filePath,rotationEnabled,contextUsageGrant,contract,nonce,processId,
10
+ filePath,rotationEnabled,contextUsageGrant,observationGrants=process.env,
11
+ contract,nonce,processId,
11
12
  createSupervisorTraceBridge,createTraceWriterImpl=createTraceWriter
12
13
  }){
13
14
  const traceWriter=createTraceWriterImpl({
@@ -57,7 +58,7 @@ export function createSupervisorObservability({
57
58
  ?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
58
59
  };
59
60
  const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
60
- traceWriter,contract
61
+ traceWriter,contract,observationGrants
61
62
  });
62
63
 
63
64
  function recordApiObservation(req){
@@ -4,13 +4,13 @@ import {createServer} from 'node:net';
4
4
  import {createSupervisorObservability} from './supervisor-observability.mjs';
5
5
  // All internal dependencies are supplied as API contracts by index.mjs.
6
6
  // Private modules never import or resolve another private implementation.
7
- let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, loadContextControlSecret, handleContextControl;
7
+ let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, readObservationGrants, loadContextControlSecret, handleContextControl;
8
8
  let connected=false;
9
9
  export function configureSupervisor(ports){
10
10
  if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
11
- for(const name of ['CONTRACT', 'VERSION', 'PACKAGE_VERSION', 'registry', 'paths', 'ensurePrivateDir', 'ACTIONS', 'createAdapter', 'createSupervisorTraceBridge', 'loadContextControlSecret', 'handleContextControl'])
11
+ for(const name of ['CONTRACT', 'VERSION', 'PACKAGE_VERSION', 'registry', 'paths', 'ensurePrivateDir', 'ACTIONS', 'createAdapter', 'createSupervisorTraceBridge', 'readObservationGrants', 'loadContextControlSecret', 'handleContextControl'])
12
12
  if(ports?.[name]===undefined)throw Error('TOOLS_PORT_MISSING:'+name);
13
- ({CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, loadContextControlSecret, handleContextControl}=ports);
13
+ ({CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, readObservationGrants, loadContextControlSecret, handleContextControl}=ports);
14
14
  connected=true;
15
15
  }
16
16
 
@@ -37,11 +37,15 @@ function rememberRequest(id,payload,promise){
37
37
  }
38
38
  const p=paths(), nonce=randomUUID();
39
39
  const error=(code,message=code)=>({code,message});
40
+ let recoveredGrants={};
41
+ try{recoveredGrants=readObservationGrants()||{}}catch{}
42
+ const observationGrants=Object.keys(recoveredGrants).length
43
+ ?recoveredGrants:process.env;
40
44
  const observability=createSupervisorObservability({
41
45
  filePath:p.log,
42
46
  rotationEnabled:process.env.CHAT_LOOP_TRACE_ROTATE_ENABLE==='1',
43
- contextUsageGrant:process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS,
44
- contract:CONTRACT,nonce,processId:process.pid,
47
+ contextUsageGrant:observationGrants.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS,
48
+ observationGrants,contract:CONTRACT,nonce,processId:process.pid,
45
49
  createSupervisorTraceBridge,error
46
50
  });
47
51
  const {log,traceHealth,handleTraceObservation,traceNativeReceipt,
@@ -1,15 +1,16 @@
1
1
  // Internal Supervisor Trace bridge: one writer owned by the Supervisor.
2
2
  // Trace events are soft evidence; they never grant Context or Browser Owner.
3
- export function createSupervisorTraceBridge({traceWriter,contract,error}){
3
+ export function createSupervisorTraceBridge({traceWriter,contract,error,
4
+ observationGrants=process.env}){
4
5
  const CONTRACT=contract;
5
6
  const allowedTraceProjects=()=>{
6
- const entries=(process.env.CHAT_LOOP_TRACE_ALLOWED_PROJECTS||'')
7
+ const entries=(observationGrants.CHAT_LOOP_TRACE_ALLOWED_PROJECTS||'')
7
8
  .split(',').map(x=>x.trim());
8
9
  // Apply the same single-project, fail-closed boundary to log submission.
9
10
  return new Set(entries.length===1 && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(entries[0])
10
11
  ? entries : []);
11
12
  };
12
- const traceEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1';
13
+ const traceEnabled=()=>observationGrants.CHAT_LOOP_TRACE_API_ENABLE==='1';
13
14
  const UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
14
15
  function handleTraceObservation(req){
15
16
  // Internal Context audit collection uses its own exact single-project
@@ -17,8 +18,8 @@ export function createSupervisorTraceBridge({traceWriter,contract,error}){
17
18
  // not become reachable merely because Context collection is active.
18
19
  const isContextApi=req?.event==='context.api';
19
20
  const form=/^form\.(prepared|rendered|submitted)\.(soft_observed|failed)$/.test(req?.event||'');
20
- const contextGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
21
- const contextAuthorized=process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
21
+ const contextGrant=observationGrants.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
22
+ const contextAuthorized=observationGrants.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
22
23
  &&typeof contextGrant==='string'
23
24
  &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextGrant)
24
25
  &&req?.projectRef===contextGrant;
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.29",
6
+ "version": "0.9.31",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -2,8 +2,9 @@
2
2
  import {randomUUID} from 'node:crypto';
3
3
  import {readFileSync} from 'node:fs';
4
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'];
5
+ const RESOURCE_URI='ui://chat-loop/form/v4';
6
+ const LEGACY_RESOURCE_URIS=['ui://chat-loop/form/v3',
7
+ 'ui://chat-loop/form/review-v2','ui://chat-loop/form/review-v1'];
7
8
  const RESOURCE_MIME='text/html;profile=mcp-app';
8
9
  const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
9
10
  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;
@@ -14,7 +15,7 @@ const filled=(value,max)=>typeof value==='string'
14
15
  &&value.trim().length>0&&value.length<=max;
15
16
  const shape=(value,fields)=>value&&typeof value==='object'
16
17
  &&!Array.isArray(value)&&Object.keys(value).every(key=>fields.includes(key));
17
- const CARD=['title','description','options','submitLabel','footer','textInput'];
18
+ const CARD=['title','description','document','options','submitLabel','footer','textInput'];
18
19
  const REQUIRED_CARD=['title','description','options','submitLabel'];
19
20
  const OPTION=['value','label'];
20
21
  const TEXT_INPUT=['label','placeholder','showWhen','requiredWhen','maxLength','rows'];
@@ -41,6 +42,7 @@ const cardSchema={type:'object',additionalProperties:false,required:REQUIRED_CAR
41
42
  properties:{
42
43
  title:{type:'string',minLength:1,maxLength:180},
43
44
  description:{type:'string',minLength:1,maxLength:1200},
45
+ document:{type:'string',minLength:1,maxLength:24000},
44
46
  options:{type:'array',minItems:1,maxItems:32,items:optionSchema},
45
47
  submitLabel:{type:'string',minLength:1,maxLength:180},
46
48
  footer:{type:'string',maxLength:1200},
@@ -48,7 +50,7 @@ const cardSchema={type:'object',additionalProperties:false,required:REQUIRED_CAR
48
50
  }};
49
51
  const tools=[
50
52
  {name:'chat_loop_form__prepare',description:
51
- '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.',
53
+ 'Present a generic single-select MCP App with caller-defined options and optional text input. Perform ALL document preparation, persistence, verification, and other tool calls BEFORE calling this tool. To keep the interactive form visible in the completed ChatGPT answer, call this tool LAST in the assistant turn and do not call any more tools afterwards; the host may collapse an earlier widget. 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.',
52
54
  inputSchema:{type:'object',additionalProperties:false,required:['card'],
53
55
  properties:{formId:{type:'string',pattern:FORM_ID.source},card:cardSchema}},
54
56
  annotations:{readOnlyHint:false},
@@ -84,6 +86,7 @@ function checkCard(args){
84
86
  const card=args.card;
85
87
  if(!shape(card,CARD)||REQUIRED_CARD.some(key=>!Object.hasOwn(card,key))
86
88
  ||!filled(card.title,180)||!filled(card.description,1200)
89
+ ||card.document!==undefined&&!filled(card.document,24000)
87
90
  ||!filled(card.submitLabel,180)
88
91
  ||card.footer!==undefined&&typeof card.footer!=='string'
89
92
  ||card.footer?.length>1200)
@@ -121,6 +124,7 @@ function view(args,formId){
121
124
  const card=args.card,field=card.textInput;
122
125
  return {template:'chat-loop-form-v1',formId,
123
126
  title:card.title,description:card.description,
127
+ ...(card.document!==undefined?{document:card.document}:{}),
124
128
  options:card.options.map(option=>({value:option.value,label:option.label})),
125
129
  textInput:field?{
126
130
  label:field.label,placeholder:field.placeholder,
@@ -93,6 +93,14 @@ function render(value){
93
93
  const preserveLock=prepared?.formId===value.formId
94
94
  &&prepared?.traceRef===value.traceRef&&locked;
95
95
  prepared=value;
96
+ // A caller-supplied read-only document appears before the generic choices.
97
+ // textContent prevents HTML/script injection; Form owns no document state.
98
+ const documentValue=view.document;
99
+ if(documentValue!==undefined&&(typeof documentValue!=='string'
100
+ ||!documentValue.trim()||documentValue.length>24000))
101
+ throw Error('FORM_DOCUMENT_INVALID');
102
+ $('document').textContent=documentValue||'';
103
+ $('document').hidden=!documentValue;
96
104
  $('title').textContent=view.title;
97
105
  $('description').textContent=view.description;
98
106
  $('submit').textContent=view.submitLabel||'提交';
@@ -11,6 +11,8 @@ body{margin:0;padding:16px;color:var(--app-color,#191919);background:transparent
11
11
  main{max-width:760px;margin:auto;padding:16px;border:1px solid #aaa6;border-radius:12px}
12
12
  h1{font-size:16px;margin:0 0 6px}
13
13
  p{margin:6px 0 12px;color:inherit}
14
+ #document{white-space:pre-wrap;overflow-wrap:anywhere;margin:14px 0 18px;padding:12px 0;border-bottom:1px solid #aaa6;font:inherit;line-height:1.65}
15
+ #review-controls{margin-top:12px}
14
16
  small{color:#888}
15
17
  fieldset{border:0;padding:0;margin:8px 0}
16
18
  label.option{display:flex;align-items:center;gap:10px;padding:10px 8px;cursor:pointer}
@@ -30,6 +32,8 @@ button:disabled{opacity:.44;cursor:not-allowed}
30
32
  <body>
31
33
  <main aria-live="polite">
32
34
  <h1 id="title">Chat Loop 表单</h1>
35
+ <article id="document" aria-label="待阅读内容" hidden></article>
36
+ <section id="review-controls">
33
37
  <p id="description">正在连接表单工具…</p>
34
38
  <fieldset id="options" disabled>
35
39
  <legend id="legend">请选择一项</legend>
@@ -43,8 +47,9 @@ button:disabled{opacity:.44;cursor:not-allowed}
43
47
  <div id="status" role="status">等待真实 MCP Form prepare 回执</div>
44
48
  <pre id="result" hidden></pre>
45
49
  <small id="footer"></small>
50
+ </section>
46
51
  </main>
47
- <script>(()=>{var r=e=>document.getElementById(e),F=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/,L=/^[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,N=0,a=!1,d=null,E=!1,_=null,l=null,g=null;function c(e,t="info"){r("status").textContent=e,r("status").dataset.state=t}function R(e){window.parent.postMessage({jsonrpc:"2.0",...e},"*")}function x(e,t={}){R({method:e,params:t})}function w(e,t){if(!a)throw Error("FORM_APP_NOT_INITIALIZED");return new Promise((n,i)=>{let s=++N,u=setTimeout(()=>{p.delete(s),i(Error("FORM_APP_REPLY_UNKNOWN"))},3e4);p.set(s,{resolve:n,reject:i,timer:u}),R({id:s,method:e,params:t})})}function I(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"]')],D=()=>T().find(e=>e.checked)?.value||null;function A(){let e=D();return d?.view.options.find(t=>t.value===e)||null}function P(e){let t=d?.view.textInput;return!!(t&&e&&t.showWhen.includes(e.value))}function C(e){let t=d?.view.textInput;return!!(t&&e&&t.requiredWhen.includes(e.value))}function m(){let e=A(),t=P(e);r("options").disabled=!a,r("text-input").hidden=!t;let n=r("input").value.trim();r("submit").disabled=!a||!d||E||!e||t&&C(e)&&!n,O()}function W(e){if(!a||!e)return;let t=e.formId+":"+e.traceRef;g!==t&&(g=t,r("status").dataset.renderObservation="pending",w("tools/call",{name:"chat_loop_form__render",arguments:{formId:e.formId,traceRef:e.traceRef}}).then(I).then(n=>{if(n.status!=="FORM_RENDERED"||n.formId!==e.formId||n.traceRef!==e.traceRef)throw Error("FORM_RENDER_RECEIPT_INVALID");r("status").dataset.renderObservation="confirmed"}).catch(()=>{r("status").dataset.renderObservation="unverified",console.warn("FORM_RENDER_OBSERVATION_UNVERIFIED")}))}function M(e){let t=e?.view,n=t?.options;if(!t||t.template!=="chat-loop-form-v1"||typeof e.formId!="string"||!F.test(e.formId)||typeof e.traceRef!="string"||!L.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=d?.formId===e.formId&&d?.traceRef===e.traceRef&&E;d=e,r("title").textContent=t.title,r("description").textContent=t.description,r("submit").textContent=t.submitLabel||"\u63D0\u4EA4",r("footer").textContent=t.footer||"";let u=r("option-list");u.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 b=document.createElement("span");b.textContent=o.label,f.append(h,b),u.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="",E=s,r("result").hidden=!0,r("result").textContent="",c(l||(a?"\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"),l?"error":a?"ok":"info"),m(),W(e)}function V(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{M(I(_))}catch{c("Form prepare \u56DE\u6267\u65E0\u6548\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error")}}t.method==="ui/resource-teardown"&&t.id!==void 0&&R({id:t.id,result:{}})}}var v=0,y=0;function O(){if(!a)return;let e=Math.ceil(document.documentElement.scrollHeight),t=Math.ceil(document.documentElement.clientWidth);e===v&&t===y||(v=e,y=t,x("ui/notifications/size-changed",{width:t,height:e}))}async function z(){if(window.parent===window){c("\u672A\u5728 ChatGPT MCP App iframe \u4E2D\u8FD0\u884C\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error");return}let e=++N,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}),R({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){l="\u5F53\u524D\u5BBF\u4E3B\u7F3A\u5C11 serverTools \u80FD\u529B\uFF0C\u8868\u5355\u4E0D\u53EF\u63D0\u4EA4\u3002",c(l,"error"),m();return}a=!0,l=null,x("ui/notifications/initialized",{}),O(),_&&M(I(_)),typeof ResizeObserver=="function"&&new ResizeObserver(O).observe(document.documentElement)}catch{l="MCP App \u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u6838\u67E5\u5BBF\u4E3B\u8FDE\u63A5\u4E0E\u534F\u8BAE\u80FD\u529B\u3002",c(l,"error"),a=!1,m()}}async function k(){if(!a||E||!d)return;let e=A();if(!e)return;let t=P(e),n=r("input").value.trim();if(t&&C(e)&&!n)return;E=!0,m();let{formId:i,traceRef:s}=d,u={formId:i,traceRef:s,selection:{value:e.value,label:e.label},...t&&n?{input:n}:{}};c("\u6B63\u5728\u63D0\u4EA4\u8868\u5355\u2026");try{let o=I(await w("tools/call",{name:"chat_loop_form__submit",arguments:u}));if(o.status!=="FORM_SUBMITTED"||o.formId!==i||o.traceRef!==s||o.selection?.value!==e.value||o.selection?.label!==e.label){c("Submit \u8FD4\u56DE\u7684\u6570\u636E\u4E0E\u5F53\u524D\u8868\u5355\u4E0D\u5339\u914D\u3002","error");return}r("status").dataset.modelContextDelivery="pending",w("ui/update-model-context",{content:[{type:"text",text:JSON.stringify({kind:"form-selection",formId:i,traceRef:s,selection:o.selection,...o.input!==void 0?{input:o.input}:{}})}]}).then(()=>{r("status").dataset.modelContextDelivery="acknowledged"}).catch(()=>{r("status").dataset.modelContextDelivery="unverified",console.warn("FORM_MODEL_CONTEXT_DELIVERY_UNVERIFIED")}),r("result").textContent="",r("result").hidden=!0,c("\u5DF2\u63D0\u4EA4\u8868\u5355\uFF0C\u7B49\u5F85\u5F53\u524D\u4E1A\u52A1\u6D41\u7A0B\u5904\u7406\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";c(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",V);r("input").addEventListener("input",m);r("submit").addEventListener("click",k);z();})();
52
+ <script>(()=>{var r=e=>document.getElementById(e),L=/^[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,m=new Map,x=0,d=!1,l=null,E=!1,_=null,f=null,v=null;function u(e,t="info"){r("status").textContent=e,r("status").dataset.state=t}function I(e){window.parent.postMessage({jsonrpc:"2.0",...e},"*")}function A(e,t={}){I({method:e,params:t})}function O(e,t){if(!d)throw Error("FORM_APP_NOT_INITIALIZED");return new Promise((n,o)=>{let a=++x,c=setTimeout(()=>{m.delete(a),o(Error("FORM_APP_REPLY_UNKNOWN"))},3e4);m.set(a,{resolve:n,reject:o,timer:c}),I({id:a,method:e,params:t})})}function R(e){if(e?.isError){let n=e.content?.find(o=>o.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 D=()=>[...document.querySelectorAll('input[name="choice"]')],V=()=>D().find(e=>e.checked)?.value||null;function C(){let e=V();return l?.view.options.find(t=>t.value===e)||null}function M(e){let t=l?.view.textInput;return!!(t&&e&&t.showWhen.includes(e.value))}function P(e){let t=l?.view.textInput;return!!(t&&e&&t.requiredWhen.includes(e.value))}function p(){let e=C(),t=M(e);r("options").disabled=!d,r("text-input").hidden=!t;let n=r("input").value.trim();r("submit").disabled=!d||!l||E||!e||t&&P(e)&&!n,b()}function W(e){if(!d||!e)return;let t=e.formId+":"+e.traceRef;v!==t&&(v=t,r("status").dataset.renderObservation="pending",O("tools/call",{name:"chat_loop_form__render",arguments:{formId:e.formId,traceRef:e.traceRef}}).then(R).then(n=>{if(n.status!=="FORM_RENDERED"||n.formId!==e.formId||n.traceRef!==e.traceRef)throw Error("FORM_RENDER_RECEIPT_INVALID");r("status").dataset.renderObservation="confirmed"}).catch(()=>{r("status").dataset.renderObservation="unverified",console.warn("FORM_RENDER_OBSERVATION_UNVERIFIED")}))}function F(e){let t=e?.view,n=t?.options;if(!t||t.template!=="chat-loop-form-v1"||typeof e.formId!="string"||!L.test(e.formId)||typeof e.traceRef!="string"||!T.test(e.traceRef)||t.formId!==e.formId||!Array.isArray(n)||n.length<1||n.length>32||n.some(s=>!s||typeof s.value!="string"||!s.value.trim()||typeof s.label!="string"||!s.label.trim())||new Set(n.map(s=>s.value)).size!==n.length)throw Error("FORM_VIEW_INVALID");let o=t.textInput;if(o&&(!Array.isArray(o.showWhen)||!Array.isArray(o.requiredWhen)||o.requiredWhen.some(s=>!o.showWhen.includes(s))))throw Error("FORM_VIEW_INVALID");let a=l?.formId===e.formId&&l?.traceRef===e.traceRef&&E;l=e;let c=t.document;if(c!==void 0&&(typeof c!="string"||!c.trim()||c.length>24e3))throw Error("FORM_DOCUMENT_INVALID");r("document").textContent=c||"",r("document").hidden=!c,r("title").textContent=t.title,r("description").textContent=t.description,r("submit").textContent=t.submitLabel||"\u63D0\u4EA4",r("footer").textContent=t.footer||"";let i=r("option-list");i.replaceChildren();for(let s of n){let w=document.createElement("label");w.className="option";let h=document.createElement("input");h.type="radio",h.name="choice",h.value=s.value,h.addEventListener("change",p);let g=document.createElement("span");g.textContent=s.label,w.append(h,g),i.append(w)}r("text-label").textContent=o?.label||"\u8865\u5145\u4FE1\u606F",r("input").placeholder=o?.placeholder||"",r("input").maxLength=o?.maxLength||4e3,r("input").rows=o?.rows||4,r("text-input").hidden=!0,r("input").value="",E=a,r("result").hidden=!0,r("result").textContent="",u(f||(d?"\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"),f?"error":d?"ok":"info"),p(),W(e)}function z(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=m.get(t.id);if(!n)return;m.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{F(R(_))}catch{u("Form prepare \u56DE\u6267\u65E0\u6548\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error")}}t.method==="ui/resource-teardown"&&t.id!==void 0&&I({id:t.id,result:{}})}}var y=0,N=0;function b(){if(!d)return;let e=Math.ceil(document.documentElement.scrollHeight),t=Math.ceil(document.documentElement.clientWidth);e===y&&t===N||(y=e,N=t,A("ui/notifications/size-changed",{width:t,height:e}))}async function k(){if(window.parent===window){u("\u672A\u5728 ChatGPT MCP App iframe \u4E2D\u8FD0\u884C\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error");return}let e=++x,t=new Promise((n,o)=>{let a=setTimeout(()=>{m.delete(e),o(Error("FORM_APP_INIT_TIMEOUT"))},12e3);m.set(e,{resolve:n,reject:o,timer:a}),I({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){f="\u5F53\u524D\u5BBF\u4E3B\u7F3A\u5C11 serverTools \u80FD\u529B\uFF0C\u8868\u5355\u4E0D\u53EF\u63D0\u4EA4\u3002",u(f,"error"),p();return}d=!0,f=null,A("ui/notifications/initialized",{}),b(),_&&F(R(_)),typeof ResizeObserver=="function"&&new ResizeObserver(b).observe(document.documentElement)}catch{f="MCP App \u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u6838\u67E5\u5BBF\u4E3B\u8FDE\u63A5\u4E0E\u534F\u8BAE\u80FD\u529B\u3002",u(f,"error"),d=!1,p()}}async function S(){if(!d||E||!l)return;let e=C();if(!e)return;let t=M(e),n=r("input").value.trim();if(t&&P(e)&&!n)return;E=!0,p();let{formId:o,traceRef:a}=l,c={formId:o,traceRef:a,selection:{value:e.value,label:e.label},...t&&n?{input:n}:{}};u("\u6B63\u5728\u63D0\u4EA4\u8868\u5355\u2026");try{let i=R(await O("tools/call",{name:"chat_loop_form__submit",arguments:c}));if(i.status!=="FORM_SUBMITTED"||i.formId!==o||i.traceRef!==a||i.selection?.value!==e.value||i.selection?.label!==e.label){u("Submit \u8FD4\u56DE\u7684\u6570\u636E\u4E0E\u5F53\u524D\u8868\u5355\u4E0D\u5339\u914D\u3002","error");return}r("status").dataset.modelContextDelivery="pending",O("ui/update-model-context",{content:[{type:"text",text:JSON.stringify({kind:"form-selection",formId:o,traceRef:a,selection:i.selection,...i.input!==void 0?{input:i.input}:{}})}]}).then(()=>{r("status").dataset.modelContextDelivery="acknowledged"}).catch(()=>{r("status").dataset.modelContextDelivery="unverified",console.warn("FORM_MODEL_CONTEXT_DELIVERY_UNVERIFIED")}),r("result").textContent="",r("result").hidden=!0,u("\u5DF2\u63D0\u4EA4\u8868\u5355\uFF0C\u7B49\u5F85\u5F53\u524D\u4E1A\u52A1\u6D41\u7A0B\u5904\u7406\u3002","ok")}catch(i){let s=typeof i?.message=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(i.message)?i.message:"FORM_APP_REPLY_UNKNOWN";u(s==="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"+s+"\uFF09\u3002","error")}}window.addEventListener("message",z);r("input").addEventListener("input",p);r("submit").addEventListener("click",S);k();})();
48
53
  </script>
49
54
  </body>
50
55
  </html>
@@ -11,6 +11,8 @@ body{margin:0;padding:16px;color:var(--app-color,#191919);background:transparent
11
11
  main{max-width:760px;margin:auto;padding:16px;border:1px solid #aaa6;border-radius:12px}
12
12
  h1{font-size:16px;margin:0 0 6px}
13
13
  p{margin:6px 0 12px;color:inherit}
14
+ #document{white-space:pre-wrap;overflow-wrap:anywhere;margin:14px 0 18px;padding:12px 0;border-bottom:1px solid #aaa6;font:inherit;line-height:1.65}
15
+ #review-controls{margin-top:12px}
14
16
  small{color:#888}
15
17
  fieldset{border:0;padding:0;margin:8px 0}
16
18
  label.option{display:flex;align-items:center;gap:10px;padding:10px 8px;cursor:pointer}
@@ -30,6 +32,8 @@ button:disabled{opacity:.44;cursor:not-allowed}
30
32
  <body>
31
33
  <main aria-live="polite">
32
34
  <h1 id="title">Chat Loop 表单</h1>
35
+ <article id="document" aria-label="待阅读内容" hidden></article>
36
+ <section id="review-controls">
33
37
  <p id="description">正在连接表单工具…</p>
34
38
  <fieldset id="options" disabled>
35
39
  <legend id="legend">请选择一项</legend>
@@ -43,6 +47,7 @@ button:disabled{opacity:.44;cursor:not-allowed}
43
47
  <div id="status" role="status">等待真实 MCP Form prepare 回执</div>
44
48
  <pre id="result" hidden></pre>
45
49
  <small id="footer"></small>
50
+ </section>
46
51
  </main>
47
52
  <!-- CHAT_LOOP_FORM_SCRIPT -->
48
53
  </body>