@tomflow/chatloop-tools 0.9.27 → 0.9.29

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` renders caller-defined options and optional text input, preserves or generates `formId`, and returns a random `traceRef`; `submit` returns the selected value/label and optional text to the caller. It does not send Chat messages, interpret business meaning, call Context, retain prepared-form state, or impose expiry. Prepare/Submit API spans and soft observations are correlated in the existing Trace writer by `sessionRef=traceRef` and `evidenceRef=formId`; Trace loss never blocks or changes the returned Form data.
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.
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`
@@ -109,14 +109,13 @@ to any existing Provider, the Gateway, or either npm entrypoint.
109
109
  trigger retries of unknown effects. In particular, verified Extension MCP
110
110
  results are returned **before** optional Trace transport finishes; a
111
111
  slow, rejecting or unavailable observer cannot replace the action receipt.
112
- Form submission claims are a generic Supervisor idempotency concern:
113
- the dedicated private ledger durably records the opaque `traceRef` claim
114
- independently of the 30-day Trace retention window. A failed or unknown
115
- ledger write blocks the user message and forbids retry. Once the claim is
116
- durably committed, Trace observation failure never reverses or blocks the
117
- Form result; the missing evidence is surfaced by Trace health/diagnose.
118
- Form observations remain best-effort evidence and are not an all-API AOP
119
- coverage claim.
112
+ Form Submit is a pure data-return operation: it creates no business side
113
+ effect, sends no user message, and writes no idempotency ledger. Repeating
114
+ the same Submit returns the same caller-provided selection data. The 30-day
115
+ retention policy applies only to Trace records; it does not expire a Form
116
+ or invalidate its `formId`/`traceRef`. Form observations remain best-effort
117
+ evidence; Trace failure never blocks or changes the Form result and is
118
+ surfaced through Trace health/diagnose.
120
119
 
121
120
  No legacy Task Registry MCP or JSON fallback is shipped. Historical
122
121
  SourceUnit files remain migration evidence, not alternate current facts.
@@ -0,0 +1,113 @@
1
+ import {spawn} from 'node:child_process';
2
+ import {existsSync} from 'node:fs';
3
+ import {homedir} from 'node:os';
4
+ import {join} from 'node:path';
5
+
6
+ export function tunnelBinaryPath(stage,platform=process.platform+'-'+process.arch){
7
+ if(typeof stage!=='string'||!stage.startsWith('/')
8
+ ||!/^darwin-(?:arm64|x64)$/.test(platform))
9
+ throw Object.assign(Error('TUNNEL_PROBE_PATH_INVALID'),{
10
+ code:'TUNNEL_PROBE_PATH_INVALID'});
11
+ return join(stage,'node_modules','@tomflow',
12
+ 'chatloop-tunnel-'+platform,'bin','tunnel-client');
13
+ }
14
+
15
+ export async function verifyTunnelConnection(p,verified,ports={}){
16
+ if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return {result:'ok',testOnly:true};
17
+ const {run,runtimeLaunchEnv}=ports;
18
+ if(typeof run!=='function'||typeof runtimeLaunchEnv!=='function')
19
+ throw Object.assign(Error('TUNNEL_PROBE_PORT_MISSING'),{
20
+ code:'TUNNEL_PROBE_PORT_MISSING'});
21
+ const tunnel=verified.results?.find(x=>x.toolId==='tunnel');
22
+ const binary=tunnelBinaryPath(p.stage);
23
+ const healthFile=ports.healthFile||join(homedir(),'Library',
24
+ 'Application Support','tunnel-client','health','chat-loop.url');
25
+ if(!Number.isSafeInteger(tunnel?.pid)||!existsSync(binary)
26
+ ||!existsSync(healthFile))
27
+ throw Object.assign(Error('NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'),{
28
+ code:'NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'});
29
+ let last;
30
+ for(let attempt=0;attempt<30;attempt++){
31
+ try{
32
+ const output=await run(binary,['health','--url-file',healthFile,
33
+ '--pid',String(tunnel.pid),'--require-control-plane-poll','--json'],
34
+ {env:runtimeLaunchEnv()});
35
+ const result=JSON.parse(output.trim());
36
+ if(result.result==='ok'&&result.healthz?.ok===true
37
+ &&result.readyz?.ok===true&&result.control_plane_poll?.ok===true)
38
+ return {result:'ok',pid:tunnel.pid,controlPlanePoll:true};
39
+ last=result;
40
+ }catch(error){last={code:error.code||'TUNNEL_HEALTH_FAILED'};}
41
+ await new Promise(resolve=>setTimeout(resolve,500));
42
+ }
43
+ throw Object.assign(Error('NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY'),{
44
+ code:'NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY',tunnelStatus:last});
45
+ }
46
+ export async function verifyMcpTools(p,ports={}){
47
+ if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return {ok:true,testOnly:true};
48
+ const {runtimeLaunchEnv}=ports;
49
+ if(typeof runtimeLaunchEnv!=='function')
50
+ throw Object.assign(Error('MCP_PROBE_PORT_MISSING'),{
51
+ code:'MCP_PROBE_PORT_MISSING'});
52
+ const child=spawn(process.execPath,[p.entry,'mcp'],{
53
+ env:{...runtimeLaunchEnv(),CHAT_LOOP_API_LOG_STDERR:'0'},
54
+ stdio:['pipe','pipe','pipe'],windowsHide:true
55
+ });
56
+ let buffer='',stderr='',nextId=0;
57
+ const waiting=new Map();
58
+ const rejectPending=error=>{
59
+ for(const pending of waiting.values()){
60
+ clearTimeout(pending.timer);pending.reject(error);
61
+ }
62
+ waiting.clear();
63
+ };
64
+ child.stdout.setEncoding('utf8');
65
+ child.stderr.setEncoding('utf8');
66
+ child.stdout.on('data',chunk=>{
67
+ buffer+=chunk;
68
+ let end;
69
+ while((end=buffer.indexOf('\n'))>=0){
70
+ const line=buffer.slice(0,end);buffer=buffer.slice(end+1);
71
+ let packet;try{packet=JSON.parse(line)}catch{continue;}
72
+ const pending=waiting.get(packet.id);
73
+ if(pending){waiting.delete(packet.id);clearTimeout(pending.timer);pending.resolve(packet);}
74
+ }
75
+ });
76
+ child.stderr.on('data',chunk=>{stderr=(stderr+chunk).slice(-2048)});
77
+ child.once('error',error=>rejectPending(error));
78
+ child.once('exit',code=>rejectPending(Error('MCP_PROBE_EXIT:'+code+':'+stderr.slice(-500))));
79
+ const request=(method,params={})=>new Promise((resolve,reject)=>{
80
+ const id=++nextId;
81
+ const timer=setTimeout(()=>{waiting.delete(id);reject(Error('MCP_PROBE_TIMEOUT:'+method))},8000);
82
+ waiting.set(id,{resolve,reject,timer});
83
+ child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');
84
+ });
85
+ try{
86
+ const init=await request('initialize',{protocolVersion:'2025-11-25',
87
+ capabilities:{},clientInfo:{name:'chat-loop-upgrade-probe',version:p.version}});
88
+ if(init.result?.serverInfo?.version!==p.version)
89
+ throw Object.assign(Error('MCP_PROBE_VERSION_MISMATCH'),{
90
+ code:'MCP_PROBE_VERSION_MISMATCH'});
91
+ child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');
92
+ const listed=await request('tools/list');
93
+ const names=listed.result?.tools?.map(x=>x.name)||[];
94
+ for(const name of ['chat_loop_form__prepare','chat_loop_form__render',
95
+ 'chat_loop_form__submit'])
96
+ if(!names.includes(name))throw Object.assign(Error('MCP_PROBE_REQUIRED_TOOL_MISSING'),{
97
+ code:'MCP_PROBE_REQUIRED_TOOL_MISSING'});
98
+ const resources=await request('resources/list');
99
+ const uri=resources.result?.resources?.find(x=>x.uri==='ui://chat-loop/form/v3')?.uri;
100
+ if(!uri)throw Object.assign(Error('MCP_PROBE_FORM_RESOURCE_MISSING'),{
101
+ code:'MCP_PROBE_FORM_RESOURCE_MISSING'});
102
+ const view=await request('resources/read',{uri});
103
+ const html=view.result?.contents?.[0]?.text||'';
104
+ if(!html.includes('chat_loop_form__render'))
105
+ throw Object.assign(Error('MCP_PROBE_FORM_APP_OUTDATED'),{
106
+ code:'MCP_PROBE_FORM_APP_OUTDATED'});
107
+ return {ok:true,toolCount:names.length,formResource:uri};
108
+ }finally{
109
+ try{child.stdin.end();child.kill('SIGTERM')}catch{}
110
+ await Promise.race([new Promise(resolve=>child.once('exit',resolve)),
111
+ new Promise(resolve=>setTimeout(resolve,1000))]);
112
+ }
113
+ }
@@ -1,10 +1,9 @@
1
1
  // Supervisor cutover lifecycle. All package/runtime helpers arrive as
2
2
  // explicit ports from the SDK composition root; this module owns no state.
3
3
  import {randomUUID} from 'node:crypto';
4
- import {spawn} from 'node:child_process';
5
4
  import {existsSync,mkdirSync,openSync,closeSync,unlinkSync,lstatSync,readFileSync,writeFileSync} from 'node:fs';
6
- import {homedir} from 'node:os';
7
5
  import {join,dirname} from 'node:path';
6
+ import {verifyTunnelConnection,verifyMcpTools} from './release-health-checks.mjs';
8
7
  let PACKAGE_VERSION,CONTRACT,lifecycleDeadlineMs,talkForUpgrade,
9
8
  activeDesktopCommands,awaitStopped,checkedUpgradeBase,upgradeLayout,
10
9
  run,cli,runtimeLaunchEnv,verifyPreparedRelease,atomicWrite,readJson,
@@ -61,98 +60,34 @@ function backupConfiguration(p){
61
60
  return directory;
62
61
  }
63
62
 
64
- async function verifyTunnelConnection(p,verified){
65
- if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return {result:'ok',testOnly:true};
66
- const tunnel=verified.results?.find(x=>x.toolId==='tunnel');
67
- const platform=process.platform+'-'+process.arch;
68
- const binary=join(dirname(dirname(p.entry)),'node_modules','@tomflow',
69
- 'chatloop-tunnel-'+platform,'bin','tunnel-client');
70
- const healthFile=join(homedir(),'Library','Application Support',
71
- 'tunnel-client','health','chat-loop.url');
72
- if(!Number.isSafeInteger(tunnel?.pid)||!existsSync(binary)||!existsSync(healthFile))
73
- throw Object.assign(Error('NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'),{
74
- code:'NEW_RUNTIME_TUNNEL_PROBE_UNAVAILABLE'});
75
- let last;
76
- for(let attempt=0;attempt<30;attempt++){
77
- try{
78
- const output=await run(binary,['health','--url-file',healthFile,
79
- '--pid',String(tunnel.pid),'--require-control-plane-poll','--json'],
80
- {env:runtimeLaunchEnv()});
81
- const result=JSON.parse(output.trim());
82
- if(result.result==='ok'&&result.healthz?.ok===true
83
- &&result.readyz?.ok===true&&result.control_plane_poll?.ok===true)
84
- return {result:'ok',pid:tunnel.pid,controlPlanePoll:true};
85
- last=result;
86
- }catch(error){last={code:error.code||'TUNNEL_HEALTH_FAILED'};}
87
- await new Promise(resolve=>setTimeout(resolve,500));
88
- }
89
- throw Object.assign(Error('NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY'),{
90
- code:'NEW_RUNTIME_TUNNEL_CONNECTION_UNHEALTHY',tunnelStatus:last});
91
- }
92
-
93
- async function verifyMcpTools(p){
94
- if(process.env.CHAT_LOOP_TEST_UPGRADE_TRACE)return {ok:true,testOnly:true};
95
- const child=spawn(process.execPath,[p.entry,'mcp'],{
96
- env:{...runtimeLaunchEnv(),CHAT_LOOP_API_LOG_STDERR:'0'},
97
- stdio:['pipe','pipe','pipe'],windowsHide:true
98
- });
99
- let buffer='',stderr='',nextId=0;
100
- const waiting=new Map();
101
- const rejectPending=error=>{
102
- for(const pending of waiting.values()){
103
- clearTimeout(pending.timer);pending.reject(error);
104
- }
105
- waiting.clear();
106
- };
107
- child.stdout.setEncoding('utf8');
108
- child.stderr.setEncoding('utf8');
109
- child.stdout.on('data',chunk=>{
110
- buffer+=chunk;
111
- let end;
112
- while((end=buffer.indexOf('\n'))>=0){
113
- const line=buffer.slice(0,end);buffer=buffer.slice(end+1);
114
- let packet;try{packet=JSON.parse(line)}catch{continue;}
115
- const pending=waiting.get(packet.id);
116
- if(pending){waiting.delete(packet.id);clearTimeout(pending.timer);pending.resolve(packet);}
117
- }
118
- });
119
- child.stderr.on('data',chunk=>{stderr=(stderr+chunk).slice(-2048)});
120
- child.once('error',error=>rejectPending(error));
121
- child.once('exit',code=>rejectPending(Error('MCP_PROBE_EXIT:'+code+':'+stderr.slice(-500))));
122
- const request=(method,params={})=>new Promise((resolve,reject)=>{
123
- const id=++nextId;
124
- const timer=setTimeout(()=>{waiting.delete(id);reject(Error('MCP_PROBE_TIMEOUT:'+method))},8000);
125
- waiting.set(id,{resolve,reject,timer});
126
- child.stdin.write(JSON.stringify({jsonrpc:'2.0',id,method,params})+'\n');
127
- });
128
- try{
129
- const init=await request('initialize',{protocolVersion:'2025-11-25',
130
- capabilities:{},clientInfo:{name:'chat-loop-upgrade-probe',version:p.version}});
131
- if(init.result?.serverInfo?.version!==p.version)
132
- throw Object.assign(Error('MCP_PROBE_VERSION_MISMATCH'),{
133
- code:'MCP_PROBE_VERSION_MISMATCH'});
134
- child.stdin.write(JSON.stringify({jsonrpc:'2.0',method:'notifications/initialized'})+'\n');
135
- const listed=await request('tools/list');
136
- const names=listed.result?.tools?.map(x=>x.name)||[];
137
- for(const name of ['chat_loop_form__prepare','chat_loop_form__render',
138
- 'chat_loop_form__submit'])
139
- if(!names.includes(name))throw Object.assign(Error('MCP_PROBE_REQUIRED_TOOL_MISSING'),{
140
- code:'MCP_PROBE_REQUIRED_TOOL_MISSING'});
141
- const resources=await request('resources/list');
142
- const uri=resources.result?.resources?.find(x=>x.uri==='ui://chat-loop/form/v3')?.uri;
143
- if(!uri)throw Object.assign(Error('MCP_PROBE_FORM_RESOURCE_MISSING'),{
144
- code:'MCP_PROBE_FORM_RESOURCE_MISSING'});
145
- const view=await request('resources/read',{uri});
146
- const html=view.result?.contents?.[0]?.text||'';
147
- if(!html.includes('chat_loop_form__render'))
148
- throw Object.assign(Error('MCP_PROBE_FORM_APP_OUTDATED'),{
149
- code:'MCP_PROBE_FORM_APP_OUTDATED'});
150
- return {ok:true,toolCount:names.length,formResource:uri};
151
- }finally{
152
- try{child.stdin.end();child.kill('SIGTERM')}catch{}
153
- await Promise.race([new Promise(resolve=>child.once('exit',resolve)),
154
- new Promise(resolve=>setTimeout(resolve,1000))]);
63
+ // Preserve only explicit, single-Project MCP grants from the local Tunnel
64
+ // command. A plain profile has no prefix. An unsupported /usr/bin/env
65
+ // assignment fails before the current Supervisor is stopped.
66
+ const MCP_PROFILE_ENV=new Set([
67
+ 'CHAT_LOOP_CONTEXT_API_ENABLE','CHAT_LOOP_CONTEXT_ROOT',
68
+ 'CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS','CHAT_LOOP_TRACE_API_ENABLE',
69
+ 'CHAT_LOOP_TRACE_ALLOWED_PROJECTS'
70
+ ]);
71
+ export function preservedMcpEnvironmentPrefix(command){
72
+ if(typeof command!=='string'||!command.startsWith('"/usr/bin/env" '))return '';
73
+ const match=command.match(/^"\/usr\/bin\/env"((?: "CHAT_LOOP_[A-Z_]+=[^"]*")+)/);
74
+ if(!match)throw Object.assign(Error('RELEASE_PROFILE_ENV_INVALID'),
75
+ {code:'RELEASE_PROFILE_ENV_INVALID'});
76
+ const items=[...match[1].matchAll(/ "([^"]+)"/g)].map(x=>x[1]);
77
+ const keys=new Set();
78
+ for(const item of items){
79
+ const index=item.indexOf('='),key=item.slice(0,index),value=item.slice(index+1);
80
+ if(!MCP_PROFILE_ENV.has(key)||keys.has(key)||!value
81
+ ||/[\r\n"\\]/.test(value))
82
+ throw Object.assign(Error('RELEASE_PROFILE_ENV_INVALID'),
83
+ {code:'RELEASE_PROFILE_ENV_INVALID'});
84
+ keys.add(key);
155
85
  }
86
+ const remaining=command.slice(match[0].length).trimStart();
87
+ if(!remaining.startsWith('"')||/^"[^" ]+=[^"]*"/.test(remaining))
88
+ throw Object.assign(Error('RELEASE_PROFILE_ENV_INVALID'),
89
+ {code:'RELEASE_PROFILE_ENV_INVALID'});
90
+ return match[0]+' ';
156
91
  }
157
92
 
158
93
  export async function upgradeRuntime(options={}){
@@ -172,6 +107,8 @@ export async function upgradeRuntime(options={}){
172
107
  const profile=readJson(p.profile);
173
108
  if(!profile?.mcp?.commands?.some(x=>x.channel==='main'))
174
109
  return freshResult('BLOCKED',{code:'PROFILE_MCP_NOT_FOUND'});
110
+ const existingMain=profile.mcp.commands.find(x=>x.channel==='main');
111
+ const preservedEnvPrefix=preservedMcpEnvironmentPrefix(existingMain.command);
175
112
  runtime=existsSync(p.current)?readJson(p.current):null;
176
113
  oldEntry=runtime?.entry||p.legacy;
177
114
  const currentVersion=runtime?.version||
@@ -256,7 +193,7 @@ export async function upgradeRuntime(options={}){
256
193
  }
257
194
  phase='configure-new';
258
195
  const main=profile.mcp.commands.find(x=>x.channel==='main');
259
- main.command=quote(process.execPath)+' '+quote(p.entry)+' mcp';
196
+ main.command=preservedEnvPrefix+quote(process.execPath)+' '+quote(p.entry)+' mcp';
260
197
  atomicWrite(p.profile,JSON.stringify(profile,null,2)+'\n');
261
198
  phase='inspect-candidate';
262
199
  const existing=await cli(p.entry,'status');
@@ -319,9 +256,9 @@ export async function upgradeRuntime(options={}){
319
256
  code:'NEW_RUNTIME_TUNNEL_UNHEALTHY'
320
257
  });
321
258
  phase='verify-tunnel-connection';
322
- const tunnelConnection=await verifyTunnelConnection(p,verified);
259
+ const tunnelConnection=await verifyTunnelConnection(p,verified,{run,runtimeLaunchEnv});
323
260
  phase='verify-mcp';
324
- const mcp=await verifyMcpTools(p);
261
+ const mcp=await verifyMcpTools(p,{runtimeLaunchEnv});
325
262
  phase='record-new';
326
263
  atomicWrite(p.current,JSON.stringify({version:p.version,entry:p.entry,
327
264
  status:'ACTIVE'},null,2)+'\n');
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.27",
6
+ "version": "0.9.29",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -61,13 +61,19 @@ function reportRendered(value){
61
61
  const key=value.formId+':'+value.traceRef;
62
62
  if(renderReported===key)return;
63
63
  renderReported=key;
64
+ $('status').dataset.renderObservation='pending';
64
65
  // Rendering is observed asynchronously; a Trace failure never blocks the UI.
65
66
  void call('tools/call',{name:'chat_loop_form__render',arguments:{
66
67
  formId:value.formId,traceRef:value.traceRef
67
68
  }}).then(decode).then(receipt=>{
68
69
  if(receipt.status!=='FORM_RENDERED'||receipt.formId!==value.formId
69
70
  ||receipt.traceRef!==value.traceRef)throw Error('FORM_RENDER_RECEIPT_INVALID');
70
- }).catch(()=>{});
71
+ $('status').dataset.renderObservation='confirmed';
72
+ }).catch(()=>{
73
+ // Leave the Form usable, but expose a machine-readable gap for DOM audits.
74
+ $('status').dataset.renderObservation='unverified';
75
+ console.warn('FORM_RENDER_OBSERVATION_UNVERIFIED');
76
+ });
71
77
  }
72
78
  function render(value){
73
79
  const view=value?.view,options=view?.options;
@@ -205,9 +211,23 @@ async function submit(){
205
211
  ||receipt.selection?.label!==option.label){
206
212
  status('Submit 返回的数据与当前表单不匹配。','error');return;
207
213
  }
208
- $('result').textContent=JSON.stringify(receipt,null,2);
209
- $('result').hidden=false;
210
- status('提交成功,表单数据已返回。','ok');
214
+ // Update model-visible context without posting a new Chat message.
215
+ // This is not proof of a user Turn, business approval, or model consumption.
216
+ $('status').dataset.modelContextDelivery='pending';
217
+ void call('ui/update-model-context',{content:[{type:'text',
218
+ text:JSON.stringify({kind:'form-selection',formId,traceRef,
219
+ selection:receipt.selection,
220
+ ...(receipt.input!==undefined?{input:receipt.input}:{})})
221
+ }]}).then(()=>{
222
+ $('status').dataset.modelContextDelivery='acknowledged';
223
+ }).catch(()=>{
224
+ $('status').dataset.modelContextDelivery='unverified';
225
+ console.warn('FORM_MODEL_CONTEXT_DELIVERY_UNVERIFIED');
226
+ });
227
+ // Opaque receipts are for the caller, not the normal user-facing card.
228
+ $('result').textContent='';
229
+ $('result').hidden=true;
230
+ status('已提交表单,等待当前业务流程处理。','ok');
211
231
  }catch(error){
212
232
  const code=typeof error?.message==='string'
213
233
  &&/^[A-Z][A-Z0-9_]{1,95}$/.test(error.message)
@@ -44,7 +44,7 @@ button:disabled{opacity:.44;cursor:not-allowed}
44
44
  <pre id="result" hidden></pre>
45
45
  <small id="footer"></small>
46
46
  </main>
47
- <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,A=0,a=!1,l=null,_=!1,E=null,u=null,g=null;function c(e,t="info"){r("status").textContent=e,r("status").dataset.state=t}function I(e){window.parent.postMessage({jsonrpc:"2.0",...e},"*")}function P(e,t={}){I({method:e,params:t})}function N(e,t){if(!a)throw Error("FORM_APP_NOT_INITIALIZED");return new Promise((n,i)=>{let s=++A,d=setTimeout(()=>{m.delete(s),i(Error("FORM_APP_REPLY_UNKNOWN"))},3e4);m.set(s,{resolve:n,reject:i,timer:d}),I({id:s,method:e,params:t})})}function R(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 F=()=>[...document.querySelectorAll('input[name="choice"]')],W=()=>F().find(e=>e.checked)?.value||null;function v(){let e=W();return l?.view.options.find(t=>t.value===e)||null}function x(e){let t=l?.view.textInput;return!!(t&&e&&t.showWhen.includes(e.value))}function M(e){let t=l?.view.textInput;return!!(t&&e&&t.requiredWhen.includes(e.value))}function p(){let e=v(),t=x(e);r("options").disabled=!a,r("text-input").hidden=!t;let n=r("input").value.trim();r("submit").disabled=!a||!l||_||!e||t&&M(e)&&!n,w()}function z(e){if(!a||!e)return;let t=e.formId+":"+e.traceRef;g!==t&&(g=t,N("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")}).catch(()=>{}))}function C(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(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=l?.formId===e.formId&&l?.traceRef===e.traceRef&&_;l=e,r("title").textContent=t.title,r("description").textContent=t.description,r("submit").textContent=t.submitLabel||"\u63D0\u4EA4",r("footer").textContent=t.footer||"";let d=r("option-list");d.replaceChildren();for(let o of n){let f=document.createElement("label");f.className="option";let h=document.createElement("input");h.type="radio",h.name="choice",h.value=o.value,h.addEventListener("change",p);let b=document.createElement("span");b.textContent=o.label,f.append(h,b),d.append(f)}r("text-label").textContent=i?.label||"\u8865\u5145\u4FE1\u606F",r("input").placeholder=i?.placeholder||"",r("input").maxLength=i?.maxLength||4e3,r("input").rows=i?.rows||4,r("text-input").hidden=!0,r("input").value="",_=s,r("result").hidden=!0,r("result").textContent="",c(u||(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"),u?"error":a?"ok":"info"),p(),z(e)}function D(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"){E=t.params;try{C(R(E))}catch{c("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 O=0,y=0;function w(){if(!a)return;let e=Math.ceil(document.documentElement.scrollHeight),t=Math.ceil(document.documentElement.clientWidth);e===O&&t===y||(O=e,y=t,P("ui/notifications/size-changed",{width:t,height:e}))}async function V(){if(window.parent===window){c("\u672A\u5728 ChatGPT MCP App iframe \u4E2D\u8FD0\u884C\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error");return}let e=++A,t=new Promise((n,i)=>{let s=setTimeout(()=>{m.delete(e),i(Error("FORM_APP_INIT_TIMEOUT"))},12e3);m.set(e,{resolve:n,reject:i,timer:s}),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){u="\u5F53\u524D\u5BBF\u4E3B\u7F3A\u5C11 serverTools \u80FD\u529B\uFF0C\u8868\u5355\u4E0D\u53EF\u63D0\u4EA4\u3002",c(u,"error"),p();return}a=!0,u=null,P("ui/notifications/initialized",{}),w(),E&&C(R(E)),typeof ResizeObserver=="function"&&new ResizeObserver(w).observe(document.documentElement)}catch{u="MCP App \u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u6838\u67E5\u5BBF\u4E3B\u8FDE\u63A5\u4E0E\u534F\u8BAE\u80FD\u529B\u3002",c(u,"error"),a=!1,p()}}async function q(){if(!a||_||!l)return;let e=v();if(!e)return;let t=x(e),n=r("input").value.trim();if(t&&M(e)&&!n)return;_=!0,p();let{formId:i,traceRef:s}=l,d={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=R(await N("tools/call",{name:"chat_loop_form__submit",arguments:d}));if(o.status!=="FORM_SUBMITTED"||o.formId!==i||o.traceRef!==s||o.selection?.value!==e.value||o.selection?.label!==e.label){c("Submit \u8FD4\u56DE\u7684\u6570\u636E\u4E0E\u5F53\u524D\u8868\u5355\u4E0D\u5339\u914D\u3002","error");return}r("result").textContent=JSON.stringify(o,null,2),r("result").hidden=!1,c("\u63D0\u4EA4\u6210\u529F\uFF0C\u8868\u5355\u6570\u636E\u5DF2\u8FD4\u56DE\u3002","ok")}catch(o){let f=typeof o?.message=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(o.message)?o.message:"FORM_APP_REPLY_UNKNOWN";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",D);r("input").addEventListener("input",p);r("submit").addEventListener("click",q);V();})();
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();})();
48
48
  </script>
49
49
  </body>
50
50
  </html>