@tomflow/chatloop-tools 0.9.18 → 0.9.20

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
@@ -63,8 +63,8 @@ The six built-in Providers are:
63
63
  - `extension`: official pinned Extension CLI and nine scoped actions
64
64
  - `runtime`: exact-request receipt lookup without replay
65
65
  - `context`: independent Context SDK read/write schemas and fixed CLI
66
- - `trace`: Project-scoped diagnosis and SOFT stage observations
67
- - `form`: two ChatGPT-only fixed-card adapters, `chat_loop_form__prepare` and `chat_loop_form__submit`; optional generated `formId`, no independent approval authority, managed writes delegate to Context
66
+ - `trace`: Project-scoped diagnosis and SOFT stage observations, plus a bearer-token-scoped Form Trace lookup using the Prepare `traceRef`
67
+ - `form`: a stateless ChatGPT A/B MCP App adapter; `prepare` renders a caller-supplied card, preserves or generates `formId`, and returns a random `traceRef`; `submit` validates the choice/comment and asks the shared Supervisor to durably claim that `traceRef` once before the App may request `ui/message`. The claim is an at-most-once UI side-effect guard, not business state, user identity, message delivery or approval. Form owns no Context, approval, caller, workflow, expiry, cache or form lifecycle; Prepare/Submit observations and the claim are correlated in the existing Trace by `sessionRef=traceRef` and `evidenceRef=formId`.
68
68
 
69
69
  `npm run build:providers` generates `providers.generated.mjs`, the static
70
70
  assembly and release fingerprint manifest. Both `tools/list` and `tools/call`
@@ -107,7 +107,12 @@ to any existing Provider, the Gateway, or either npm entrypoint.
107
107
  trigger retries of unknown effects. In particular, verified Extension MCP
108
108
  results are returned **before** optional Trace transport finishes; a
109
109
  slow, rejecting or unavailable observer cannot replace the action receipt.
110
- These events are best-effort evidence, not an all-API AOP coverage claim.
110
+ Form submission claims are different: the Supervisor must durably append
111
+ the at-most-once claim before Submit returns success; if that receipt is
112
+ unknown or the Trace writer is unhealthy, the App must not request a user
113
+ message or retry. Form observations remain best-effort evidence and
114
+ dropped observations are surfaced by Trace health; they are not an
115
+ all-API AOP coverage claim.
111
116
 
112
117
  No legacy Task Registry MCP or JSON fallback is shipped. Historical
113
118
  SourceUnit files remain migration evidence, not alternate current facts.
package/index.mjs CHANGED
@@ -12,6 +12,9 @@ import {createCliCommandRouter} from './lib/cli-command-router.mjs';
12
12
  let auditPort=null;
13
13
  const auditBacklog=[];
14
14
  let auditDraining=false,auditRetryTimer=null,auditNoOwnerRetries=0,auditLost=0;
15
+ let formObservationLost=0;
16
+ const OBSERVER_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;
17
+ const localError=code=>Object.assign(Error(code),{code});
15
18
  const MAX_AUDIT_BACKLOG=1024,MAX_NO_OWNER_RETRIES=20;
16
19
  // The CLI can emit BEGIN before a cold Supervisor has opened its IPC socket.
17
20
  // Keep ordered, bounded soft observations until that exact socket exists;
@@ -153,8 +156,15 @@ async function runtime(){
153
156
  release.configureRelease({PACKAGE_VERSION:control.PACKAGE_VERSION,
154
157
  activeDesktopCommands:releasePreflight.activeDesktopCommands,
155
158
  awaitStopped:releasePreflight.awaitStopped});
159
+ const traceTalk=async request=>{
160
+ const result=await control.talk(request);
161
+ if(request?.action!=='__trace_health'||!result?.traceHealth)return result;
162
+ const health={...result.traceHealth,formObservationLost};
163
+ if(formObservationLost>0&&health.status==='OK')health.status='TRACE_DEGRADED';
164
+ return {...result,traceHealth:health};
165
+ };
156
166
  traceGateway.configureTraceGateway({paths:control.paths,
157
- talk:control.talk,CONTRACT:control.CONTRACT});
167
+ talk:traceTalk,CONTRACT:control.CONTRACT});
158
168
  contextGateway.configureContextApiLog({
159
169
  current:apiAspect.current,
160
170
  record:entry=>control.talk({
@@ -168,14 +178,44 @@ async function runtime(){
168
178
  // tools/call. Adding an independent provider never edits this Gateway.
169
179
  const coreToolRouter=createMcpToolRouter(providerDefinitions,{
170
180
  control,release,terminal:terminalPolicy,context:contextGateway,
171
- form:{current:apiAspect.current,observe:payload=>control.talk({
172
- contract:control.CONTRACT,action:'__trace_observation',
173
- requestId:randomUUID(),event:payload.event,status:'CONFIRMED',
174
- traceId:payload.traceId,spanId:payload.spanId,
175
- projectRef:payload.projectRef,
176
- ...(payload.taskRef?{taskRef:payload.taskRef}:{}),
177
- evidenceRef:payload.formId
178
- },1800)},trace:traceGateway,
181
+ form:{
182
+ current:apiAspect.current,
183
+ claimSubmission:async ({formId,traceRef})=>{
184
+ const parent=apiAspect.current();
185
+ if(!parent||!OBSERVER_UUID.test(parent.traceId||'')
186
+ ||!OBSERVER_UUID.test(parent.spanId||''))
187
+ throw localError('FORM_SUBMISSION_CLAIM_PARENT_MISSING');
188
+ let result;
189
+ try{
190
+ result=await control.talk({
191
+ contract:control.CONTRACT,action:'__form_submission_claim',
192
+ requestId:randomUUID(),formId,traceRef,
193
+ traceId:parent.traceId,spanId:parent.spanId
194
+ },1800);
195
+ }catch{
196
+ throw localError('FORM_SUBMISSION_CLAIM_UNKNOWN');
197
+ }
198
+ if(result?.status!=='FORM_SUBMISSION_CLAIMED'
199
+ ||!OBSERVER_UUID.test(result.eventId||''))
200
+ throw localError(result?.error?.code||'FORM_SUBMISSION_CLAIM_UNKNOWN');
201
+ return result;
202
+ },
203
+ observe:async payload=>{
204
+ const result=await control.talk({
205
+ contract:control.CONTRACT,action:'__trace_observation',
206
+ requestId:randomUUID(),event:payload.event,
207
+ status:payload.status||'CONFIRMED',
208
+ traceId:payload.traceId,spanId:payload.spanId,
209
+ projectRef:'api_system',sessionRef:payload.traceRef,
210
+ evidenceRef:payload.formId,
211
+ ...(payload.errorCode?{errorCode:payload.errorCode}:{})
212
+ },1800);
213
+ if(result?.status!=='OK'||!OBSERVER_UUID.test(result.eventId||''))
214
+ throw localError(result?.error?.code||'FORM_TRACE_OBSERVATION_UNCONFIRMED');
215
+ return result;
216
+ },
217
+ lost:()=>{formObservationLost++}
218
+ },trace:traceGateway,
179
219
  extension:{
180
220
  forwardExtensionAction:extensionProxy.forwardExtensionAction,
181
221
  observeExtensionResult:traceGateway.observeExtensionResult
@@ -0,0 +1,157 @@
1
+ import {createTraceWriter,createTraceReader} from '@tomflow/chatloop-trace';
2
+
3
+ const OBSERVER_ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
4
+ const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
5
+ const OBSERVER_NAME=/^(?:mcp|extension|tools|context|trace|tunnel)\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
6
+ const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
7
+ 'traceId','spanId','parentSpanId','apiName','phase','durationMs','errorCode',
8
+ 'ownerNonce','managerPid']);
9
+
10
+ export function createSupervisorObservability({
11
+ filePath,rotationEnabled,contextUsageGrant,contract,nonce,processId,
12
+ createSupervisorTraceBridge,error
13
+ }){
14
+ const traceWriter=createTraceWriter({
15
+ filePath,enableRotation:rotationEnabled
16
+ });
17
+ const usageScopes=['api_system',...(
18
+ typeof contextUsageGrant==='string'&&
19
+ /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextUsageGrant)
20
+ ?[contextUsageGrant]:[])];
21
+ const usageReader=createTraceReader({filePath,allowedProjects:usageScopes});
22
+ const formClaimInFlight=new Set();
23
+
24
+ // Control telemetry is bounded and asynchronous; it never changes a
25
+ // confirmed or unknown business result.
26
+ const MAX_CONTROL_AUDIT=1024,CONTROL_AUDIT_BATCH=64,controlAudit=[];
27
+ let controlAuditScheduled=false,controlAuditDropped=0;
28
+ const flushControlAudit=()=>{
29
+ controlAuditScheduled=false;
30
+ for(let i=0;i<CONTROL_AUDIT_BATCH&&controlAudit.length;i++){
31
+ const {event,detail}=controlAudit.shift();
32
+ try{traceWriter.recordControl(event,detail)}catch{}
33
+ }
34
+ if(controlAudit.length){
35
+ controlAuditScheduled=true;
36
+ setImmediate(flushControlAudit);
37
+ }
38
+ };
39
+ const flushPending=()=>{while(controlAudit.length)flushControlAudit()};
40
+ const log=(event,detail={})=>{
41
+ if(controlAudit.length>=MAX_CONTROL_AUDIT){controlAuditDropped++;return}
42
+ controlAudit.push({event,detail:{
43
+ status:detail?.status,requestId:detail?.requestId,
44
+ errorCode:detail?.errorCode
45
+ }});
46
+ if(!controlAuditScheduled){
47
+ controlAuditScheduled=true;
48
+ setImmediate(flushControlAudit);
49
+ }
50
+ };
51
+ const traceHealth=()=>{
52
+ const health=traceWriter.health();
53
+ const writerAuditLost=(health.apiObservation?.dropped||0)>0||
54
+ (health.apiObservation?.sinkFailures||0)>0;
55
+ return {...health,controlAuditDropped,controlAuditPending:controlAudit.length,
56
+ ...(writerAuditLost&&health.status==='OK'
57
+ ?{status:'TRACE_DEGRADED',errorCode:'TRACE_WRITER_API_LOG_GAP'}:{}),
58
+ ...(controlAuditDropped>0&&health.status==='OK'
59
+ ?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
60
+ };
61
+ const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
62
+ traceWriter,contract,error
63
+ });
64
+
65
+ function recordApiObservation(req){
66
+ if(req?.ownerNonce!==undefined||req?.managerPid!==undefined){
67
+ if(req.ownerNonce!==nonce||req.managerPid!==processId)
68
+ throw Object.assign(Error('TRACE_API_OWNER_MISMATCH'),
69
+ {code:'TRACE_API_OWNER_MISMATCH'});
70
+ }
71
+ if(req?.contract!==contract||!OBSERVER_ID.test(req.requestId||'')||
72
+ !OBSERVER_ID.test(req.callId||'')||!OBSERVER_ID.test(req.traceId||'')||
73
+ req.spanId!==req.callId||
74
+ (req.parentSpanId!==undefined&&
75
+ (!OBSERVER_ID.test(req.parentSpanId)||req.parentSpanId===req.spanId))||
76
+ !OBSERVER_NAME.test(req.apiName||'')||
77
+ !['BEGIN','OK','FAILED'].includes(req.phase)||
78
+ Object.keys(req).some(k=>!OBSERVER_KEYS.has(k))||
79
+ (req.phase==='BEGIN'
80
+ ?req.durationMs!==undefined||req.errorCode!==undefined
81
+ :!Number.isSafeInteger(req.durationMs)||req.durationMs<0||
82
+ (req.phase==='FAILED'
83
+ ?req.errorCode!=='MCP_TOOL_ERROR'&&
84
+ !/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode||'')
85
+ :req.errorCode!==undefined)))
86
+ throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
87
+ const written=traceWriter.record({
88
+ event:'typed.api.call',component:'gateway',projectRef:'api_system',
89
+ traceId:req.traceId,spanId:req.spanId,
90
+ ...(req.parentSpanId?{parentSpanId:req.parentSpanId}:{}),
91
+ apiName:req.apiName,
92
+ status:req.phase==='BEGIN'?'BEGIN':req.phase==='OK'?'CONFIRMED':'FAILED',
93
+ ...(req.phase!=='BEGIN'?{durationMs:req.durationMs}:{}),
94
+ ...(req.phase==='FAILED'?{errorCode:req.errorCode}:{})
95
+ });
96
+ return {contract,requestId:req.requestId,status:'OK',eventId:written.eventId};
97
+ }
98
+
99
+ async function apiUsage(req){
100
+ if(req?.contract!==contract||
101
+ Object.keys(req).some(k=>!['contract','action','requestId',
102
+ 'windowMinutes','limit'].includes(k))||
103
+ !OBSERVER_ID.test(req.requestId||''))
104
+ throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
105
+ const summary=await usageReader.apiUsage({
106
+ windowMinutes:req.windowMinutes??60,limit:req.limit??100});
107
+ return {contract,requestId:req.requestId,status:'OK',summary};
108
+ }
109
+
110
+ async function claimFormSubmission(req){
111
+ const allowed=new Set(['contract','action','requestId','formId','traceRef',
112
+ 'traceId','spanId']);
113
+ if(req?.contract!==contract||Object.keys(req).some(key=>!allowed.has(key))||
114
+ !OBSERVER_ID.test(req.requestId||'')||
115
+ typeof req.formId!=='string'||!FORM_ID.test(req.formId)||
116
+ !OBSERVER_ID.test(req.traceRef||'')||!OBSERVER_ID.test(req.traceId||'')||
117
+ !OBSERVER_ID.test(req.spanId||''))
118
+ throw error('FORM_SUBMISSION_CLAIM_INVALID');
119
+ if(formClaimInFlight.has(req.traceRef))
120
+ throw error('FORM_ALREADY_SUBMITTED');
121
+ formClaimInFlight.add(req.traceRef);
122
+ try{
123
+ if(traceWriter.health().status!=='OK')
124
+ throw error('FORM_SUBMISSION_CLAIM_UNVERIFIED');
125
+ const prior=await usageReader.diagnose({projectRef:'api_system',
126
+ sessionRef:req.traceRef,maxEvents:200});
127
+ const preparations=prior.timeline.filter(event=>
128
+ event.event==='form.prepared.soft_observed');
129
+ if(prior.gaps.some(gap=>gap!=='NO_MATCHING_EVENTS')||!preparations.length)
130
+ throw error('FORM_SUBMISSION_CLAIM_UNVERIFIED');
131
+ if(preparations.some(event=>event.evidenceRef!==req.formId))
132
+ throw error('FORM_TRACE_REF_REUSED');
133
+ const claims=prior.timeline.filter(event=>
134
+ event.event==='form.submission.claimed');
135
+ if(claims.length){
136
+ if(claims.some(event=>event.evidenceRef!==req.formId))
137
+ throw error('FORM_TRACE_REF_REUSED');
138
+ throw error('FORM_ALREADY_SUBMITTED');
139
+ }
140
+ const written=traceWriter.record({
141
+ traceId:req.traceId,parentSpanId:req.spanId,
142
+ projectRef:'api_system',sessionRef:req.traceRef,
143
+ requestId:req.requestId,component:'gateway',
144
+ event:'form.submission.claimed',status:'CONFIRMED',
145
+ evidenceRef:req.formId
146
+ });
147
+ if(!written?.eventId)throw error('FORM_SUBMISSION_CLAIM_UNRECORDED');
148
+ return {contract,requestId:req.requestId,
149
+ status:'FORM_SUBMISSION_CLAIMED',eventId:written.eventId};
150
+ }finally{
151
+ formClaimInFlight.delete(req.traceRef);
152
+ }
153
+ }
154
+
155
+ return {log,traceHealth,handleTraceObservation,traceNativeReceipt,
156
+ recordApiObservation,apiUsage,claimFormSubmission,flushPending};
157
+ }
@@ -1,7 +1,7 @@
1
1
  import {randomUUID} from 'node:crypto';
2
- import {createTraceWriter,createTraceReader} from '@tomflow/chatloop-trace';
3
2
  import {closeSync, existsSync, openSync, readFileSync, unlinkSync, writeFileSync, chmodSync} from 'node:fs';
4
3
  import {createServer} from 'node:net';
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
7
  let CONTRACT, VERSION, PACKAGE_VERSION, registry, paths, ensurePrivateDir, ACTIONS, createAdapter, createSupervisorTraceBridge, loadContextControlSecret, handleContextControl;
@@ -36,118 +36,18 @@ function rememberRequest(id,payload,promise){
36
36
  if(seen.size>MAX_REPLAY_RESULTS)seen.delete(seen.keys().next().value);
37
37
  }
38
38
  const p=paths(), nonce=randomUUID();
39
- const traceWriter=createTraceWriter({
40
- filePath:p.log,enableRotation:process.env.CHAT_LOOP_TRACE_ROTATE_ENABLE==='1'
41
- });
42
- // One exact Context grant may contribute only sanitized method counts to
43
- // the local usage view. Never widen authorization with a multi-project string.
44
- const contextUsageGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
45
- const usageScopes=['api_system',...(
46
- typeof contextUsageGrant==='string'&&
47
- /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextUsageGrant)
48
- ?[contextUsageGrant]:[])];
49
- const usageReader=createTraceReader({
50
- filePath:p.log,allowedProjects:usageScopes
39
+ const error=(code,message=code)=>({code,message});
40
+ const observability=createSupervisorObservability({
41
+ filePath:p.log,
42
+ 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,
45
+ createSupervisorTraceBridge,error
51
46
  });
52
- const OBSERVER_ID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
53
- // Namespaced, sanitized public entrypoints: MCP, SDK, CLI, Native and Browser.
54
- // Never accept raw UI text, arguments, URLs or other caller payloads.
55
- const OBSERVER_NAME=/^(?:mcp|extension|tools|context|trace|tunnel)\.[A-Za-z][A-Za-z0-9_.:-]{1,119}$/;
56
- const OBSERVER_KEYS=new Set(['contract','action','requestId','callId',
57
- 'traceId','spanId','parentSpanId','apiName','phase','durationMs','errorCode',
58
- 'ownerNonce','managerPid']);
59
- function recordApiObservation(req){
60
- // Native audit carries its exact Manager lock identity on the same IPC
61
- // request. The internal Tools producer uses the existing trusted channel.
62
- if(req?.ownerNonce!==undefined||req?.managerPid!==undefined){
63
- if(req.ownerNonce!==nonce||req.managerPid!==process.pid)
64
- throw Object.assign(Error('TRACE_API_OWNER_MISMATCH'),
65
- {code:'TRACE_API_OWNER_MISMATCH'});
66
- }
67
- if(req?.contract!==CONTRACT||!OBSERVER_ID.test(req.requestId||'')||
68
- !OBSERVER_ID.test(req.callId||'')||
69
- !OBSERVER_ID.test(req.traceId||'')||
70
- req.spanId!==req.callId||
71
- (req.parentSpanId!==undefined&&
72
- (!OBSERVER_ID.test(req.parentSpanId)||req.parentSpanId===req.spanId))||
73
- !OBSERVER_NAME.test(req.apiName||'')||
74
- !['BEGIN','OK','FAILED'].includes(req.phase)||
75
- Object.keys(req).some(k=>!OBSERVER_KEYS.has(k))||
76
- (req.phase==='BEGIN'
77
- ?req.durationMs!==undefined||req.errorCode!==undefined
78
- :!Number.isSafeInteger(req.durationMs)||req.durationMs<0||
79
- (req.phase==='FAILED'
80
- ?req.errorCode!=='MCP_TOOL_ERROR'&&
81
- !/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode||'')
82
- :req.errorCode!==undefined)))
83
- throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
84
- const written=traceWriter.record({
85
- event:'typed.api.call',component:'gateway',projectRef:'api_system',
86
- traceId:req.traceId,spanId:req.spanId,
87
- ...(req.parentSpanId?{parentSpanId:req.parentSpanId}:{}),
88
- apiName:req.apiName,
89
- status:req.phase==='BEGIN'?'BEGIN':req.phase==='OK'?'CONFIRMED':'FAILED',
90
- ...(req.phase!=='BEGIN'?{durationMs:req.durationMs}:{}),
91
- ...(req.phase==='FAILED'?{errorCode:req.errorCode}:{})
92
- });
93
- return {contract:CONTRACT,requestId:req.requestId,status:'OK',
94
- eventId:written.eventId};
95
- }
96
- async function apiUsage(req){
97
- if(req?.contract!==CONTRACT||
98
- Object.keys(req).some(k=>!['contract','action','requestId',
99
- 'windowMinutes','limit'].includes(k))||
100
- !OBSERVER_ID.test(req.requestId||''))
101
- throw Object.assign(Error('TRACE_API_INVALID'),{code:'TRACE_API_INVALID'});
102
- const summary=await usageReader.apiUsage({
103
- windowMinutes:req.windowMinutes??60,limit:req.limit??100});
104
- return {contract:CONTRACT,requestId:req.requestId,status:'OK',summary};
105
- }
47
+ const {log,traceHealth,handleTraceObservation,traceNativeReceipt,
48
+ recordApiObservation,apiUsage,claimFormSubmission,flushPending}=observability;
106
49
  const desiredTunnel=new Set(), recoveryAttempts=new Map();
107
50
  let lockFd, server, idleTimer;
108
- // Internal process/control events never perform disk I/O on a business
109
- // response path. This queue is bounded, asynchronous, and drops telemetry
110
- // rather than delaying or replaying a confirmed/unknown operation.
111
- const MAX_CONTROL_AUDIT=1024,CONTROL_AUDIT_BATCH=64,controlAudit=[];
112
- let controlAuditScheduled=false,controlAuditDropped=0;
113
- const flushControlAudit=()=>{
114
- controlAuditScheduled=false;
115
- for(let i=0;i<CONTROL_AUDIT_BATCH&&controlAudit.length;i++){
116
- const {event,detail}=controlAudit.shift();
117
- try{traceWriter.recordControl(event,detail);}
118
- catch{/* Writer health carries the last error, never a business error. */}
119
- }
120
- if(controlAudit.length){
121
- controlAuditScheduled=true;setImmediate(flushControlAudit);
122
- }
123
- };
124
- const log=(event,detail={})=>{
125
- if(controlAudit.length>=MAX_CONTROL_AUDIT){controlAuditDropped++;return}
126
- // Project only the fields the existing Trace recordControl consumes.
127
- controlAudit.push({event,detail:{
128
- status:detail?.status,requestId:detail?.requestId,
129
- errorCode:detail?.errorCode
130
- }});
131
- if(!controlAuditScheduled){
132
- controlAuditScheduled=true;setImmediate(flushControlAudit);
133
- }
134
- };
135
- const traceHealth=()=>{
136
- const health=traceWriter.health();
137
- const writerAuditLost=(health.apiObservation?.dropped||0)>0||
138
- (health.apiObservation?.sinkFailures||0)>0;
139
- return {...health,controlAuditDropped,controlAuditPending:controlAudit.length,
140
- ...(writerAuditLost&&health.status==='OK'
141
- ?{status:'TRACE_DEGRADED',errorCode:'TRACE_WRITER_API_LOG_GAP'}:{}),
142
- ...(controlAuditDropped>0&&health.status==='OK'
143
- ?{status:'TRACE_DEGRADED',errorCode:'TRACE_AUDIT_QUEUE_SATURATED'}:{})};
144
- };
145
- const error=(code,message=code)=>({code,message});
146
- // One Trace owner; this module only handles native/soft event admission.
147
- const {handleTraceObservation,traceNativeReceipt}=createSupervisorTraceBridge({
148
- traceWriter,contract:CONTRACT,error
149
- });
150
-
151
51
  const after=rec=>rec ? rec.state : 'STOPPED';
152
52
  function saveReceipt(id,state,result=null,errorCode=null){
153
53
  receipts.delete(id);
@@ -298,7 +198,7 @@ async function execute(req){
298
198
  async function shutdown(){
299
199
  if([...records.values()].some(r=>!r.exited))return;
300
200
  // Closeout may flush final soft evidence, but never re-authorizes an action.
301
- while(controlAudit.length)flushControlAudit();
201
+ flushPending();
302
202
  server?.close();
303
203
  try{if(existsSync(p.socket))unlinkSync(p.socket);}catch{}
304
204
  try{if(existsSync(p.lock) && JSON.parse(readFileSync(p.lock,'utf8')).nonce===nonce)unlinkSync(p.lock);}catch{}
@@ -344,6 +244,9 @@ async function main(){
344
244
  :req?.action==='__api_usage'
345
245
  ?Promise.resolve().then(()=>apiUsage(req))
346
246
  .catch(e=>bad(req,e.code||'TRACE_USAGE_FAILED'))
247
+ :req?.action==='__form_submission_claim'
248
+ ?Promise.resolve().then(()=>claimFormSubmission(req))
249
+ .catch(e=>bad(req,e.code||'FORM_SUBMISSION_CLAIM_FAILED'))
347
250
  :req?.action==='context-control'
348
251
  ?handleContextControl(req).then(result=>{
349
252
  traceNativeReceipt(req);
@@ -24,7 +24,7 @@ export const traceGatewayEnabled=()=>process.env.CHAT_LOOP_TRACE_API_ENABLE==='1
24
24
  &&getAllowedProjects().length===1;
25
25
  export const traceDiagnoseTool={
26
26
  name:'chat_loop_trace_diagnose',
27
- description:'Read-only local Trace timeline for one explicitly authorized Project and exact traceId/sessionRef. Shows gaps and unknown receipts; cannot replay actions or grant Browser Owner.',
27
+ description:'Read-only Trace timeline for an explicitly authorized Project. A separate api_system lookup is allowed only with the unguessable form traceRef returned by Form Prepare, and exposes only that form plus its parent MCP API spans.',
28
28
  inputSchema:{
29
29
  type:'object',additionalProperties:false,
30
30
  required:['projectRef'],
@@ -43,6 +43,10 @@ export const traceDiagnoseTool={
43
43
  const STAGE_NAMES=['intent','project','tooling','requirements','plan','approval'];
44
44
  const STAGE_OUTCOMES=['OBSERVED','BLOCKED','UNVERIFIED'];
45
45
  const USER_EVIDENCE=/^user:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
46
+ const FORM_TRACE_REF=new RegExp(UUID);
47
+ const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
48
+ const FORM_EVENT=/^form\.(?:prepared|submitted)\.(?:soft_observed|failed)$|^form\.submission\.claimed$/;
49
+ const FORM_APIS=new Set(['mcp.chat_loop_form__prepare','mcp.chat_loop_form__submit']);
46
50
  export const traceStageTool={
47
51
  name:'chat_loop_trace_stage',
48
52
  description:'Record an explicitly SOFT agent-stage observation (including R/P revision) in the existing Trace writer. Optional user:<uuid> evidenceRef is a caller assertion, NOT verified host-click provenance; no approval/Owner/content is stored. Return traceId for later calls; never use this as task approval.',
@@ -94,29 +98,104 @@ const getAllowedProjects=()=>{
94
98
  // syntax; filtering entries could silently broaden a malformed config.
95
99
  return entries.length===1&&PROJECT.test(entries[0])?entries:[];
96
100
  };
101
+ async function diagnoseFormTrace(args){
102
+ const reader=createTraceReader({filePath:paths().log,allowedProjects:['api_system']});
103
+ const base=await reader.diagnose({projectRef:'api_system',
104
+ sessionRef:args.sessionRef,maxEvents:args.maxEvents});
105
+ const formEvents=base.timeline.filter(event=>
106
+ event.sessionRef===args.sessionRef&&FORM_EVENT.test(event.event||'')
107
+ &&typeof event.evidenceRef==='string'&&FORM_ID.test(event.evidenceRef));
108
+ const gaps=base.gaps.filter(gap=>gap!=='NO_MATCHING_EVENTS');
109
+ const parentKeys=new Map();
110
+ for(const event of formEvents){
111
+ const apiName=event.event==='form.prepared.soft_observed'
112
+ ||event.event==='form.prepared.failed'
113
+ ?'mcp.chat_loop_form__prepare':'mcp.chat_loop_form__submit';
114
+ if(!event.parentSpanId){gaps.push('FORM_API_PARENT_MISSING');continue}
115
+ parentKeys.set(event.traceId+':'+event.parentSpanId,apiName);
116
+ }
117
+ const apiEvents=[];
118
+ for(const traceId of new Set(formEvents.map(event=>event.traceId))){
119
+ const query=await reader.diagnose({projectRef:'api_system',traceId,maxEvents:200});
120
+ for(const gap of query.gaps)
121
+ if(['TRACE_MALFORMED_LINES','TRACE_WINDOW_TRUNCATED',
122
+ 'TRACE_WRITER_RESTART_UNVERIFIED','LEGACY_EVENTS_UNCORRELATED']
123
+ .includes(gap))gaps.push(gap);
124
+ for(const event of query.timeline){
125
+ const key=event.traceId+':'+event.spanId;
126
+ if(event.event==='typed.api.call'&&parentKeys.get(key)===event.apiName
127
+ &&FORM_APIS.has(event.apiName))apiEvents.push(event);
128
+ }
129
+ }
130
+ for(const [key,apiName] of parentKeys){
131
+ const [traceId,spanId]=key.split(':');
132
+ const linked=apiEvents.filter(event=>event.traceId===traceId
133
+ &&event.spanId===spanId&&event.apiName===apiName);
134
+ const begins=linked.filter(event=>event.status==='BEGIN');
135
+ const terminals=linked.filter(event=>
136
+ ['CONFIRMED','FAILED'].includes(event.status));
137
+ if(begins.length!==1||terminals.length!==1)
138
+ gaps.push('FORM_API_PARENT_GAP');
139
+ const terminal=terminals[0];
140
+ if(terminal&&formEvents.some(event=>event.traceId===traceId
141
+ &&event.parentSpanId===spanId&&event.status!==terminal.status))
142
+ gaps.push('FORM_API_STATUS_MISMATCH');
143
+ }
144
+ const formIds=[...new Set(formEvents.map(event=>event.evidenceRef))];
145
+ if(formIds.length>1)gaps.push('FORM_TRACE_REF_REUSED');
146
+ if(!formEvents.length)gaps.push('NO_MATCHING_EVENTS');
147
+ const timeline=[...formEvents,...apiEvents]
148
+ .sort((a,b)=>Date.parse(a.time)-Date.parse(b.time));
149
+ const last=timeline.at(-1)||null;
150
+ const unknown=formEvents.some(event=>['UNKNOWN','BLOCKED'].includes(event.status));
151
+ return {traceId:null,projectRef:'api_system',formTraceRef:args.sessionRef,
152
+ formId:formIds.length===1?formIds[0]:null,
153
+ inspected:timeline.length,totalMatched:timeline.length,
154
+ lastConfirmed:[...timeline].reverse().find(event=>event.status==='CONFIRMED')
155
+ ?{eventId:[...timeline].reverse().find(event=>event.status==='CONFIRMED').eventId,
156
+ event:[...timeline].reverse().find(event=>event.status==='CONFIRMED').event,
157
+ time:[...timeline].reverse().find(event=>event.status==='CONFIRMED').time,
158
+ component:[...timeline].reverse().find(event=>event.status==='CONFIRMED').component}
159
+ :null,
160
+ incompleteApiSpans:[],unmatchedApiTerminals:[],lastEvent:last,unknown,
161
+ gaps:[...new Set(gaps)],confidence:gaps.length?'INCOMPLETE':'TRACE_ONLY',
162
+ retryDisposition:unknown||gaps.length
163
+ ?'VERIFY_AUTHORITATIVE_RECEIPT_FIRST':'NO_AUTOMATIC_RETRY',timeline};
164
+ }
97
165
  export async function runTraceDiagnose(args){
98
- if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
99
166
  if(!args||typeof args!=='object'||Array.isArray(args)||
100
167
  Object.keys(args).some(k=>!Object.hasOwn(traceDiagnoseTool.inputSchema.properties,k)))
101
168
  throw fail('TRACE_INVALID_ARGUMENT');
102
- if(typeof args.projectRef!=='string'||!getAllowedProjects().includes(args.projectRef))
103
- throw fail('TRACE_PROJECT_ACCESS_DENIED');
104
- const result=await createTraceReader({
105
- filePath:paths().log,allowedProjects:getAllowedProjects()
106
- }).diagnose(args);
169
+ if(args.projectRef==='api_system'){
170
+ if(args.traceId!==undefined||typeof args.sessionRef!=='string'
171
+ ||!FORM_TRACE_REF.test(args.sessionRef))
172
+ throw fail('TRACE_FORM_LOOKUP_INVALID');
173
+ }else{
174
+ if(!traceGatewayEnabled())throw fail('TRACE_API_DISABLED');
175
+ if(typeof args.projectRef!=='string'||!getAllowedProjects().includes(args.projectRef))
176
+ throw fail('TRACE_PROJECT_ACCESS_DENIED');
177
+ }
178
+ const result=args.projectRef==='api_system'
179
+ ?await diagnoseFormTrace(args)
180
+ :await createTraceReader({filePath:paths().log,
181
+ allowedProjects:getAllowedProjects()}).diagnose(args);
107
182
  try{
108
183
  const response=await talk({contract:CONTRACT,action:'__trace_health',
109
184
  requestId:randomUUID()},1400);
110
185
  result.writerHealth=response.status==='OK'?response.traceHealth?.status||'UNKNOWN':'UNAVAILABLE';
186
+ if(args.projectRef==='api_system'&&response.traceHealth?.formObservationLost>0)
187
+ result.gaps.push('FORM_TRACE_OBSERVATION_LOSS');
111
188
  }catch{result.writerHealth='UNAVAILABLE'}
112
189
  if(result.writerHealth!=='OK'){
113
- result.gaps.push('TRACE_WRITER_UNAVAILABLE');
190
+ if(['UNKNOWN','UNAVAILABLE'].includes(result.writerHealth))
191
+ result.gaps.push('TRACE_WRITER_UNAVAILABLE');
192
+ if(result.writerHealth==='TRACE_DEGRADED')
193
+ result.gaps.push('FORM_TRACE_OBSERVATION_LOSS');
114
194
  result.confidence='INCOMPLETE';
115
- // An offline / unhealthy writer invalidates any claim that the visible
116
- // timeline is complete, even when every retained event is CONFIRMED.
117
- // Only the original authoritative receipt can settle an unknown effect.
118
195
  result.retryDisposition='VERIFY_AUTHORITATIVE_RECEIPT_FIRST';
119
196
  }
197
+ result.gaps=[...new Set(result.gaps)];
198
+ if(result.gaps.length)result.confidence='INCOMPLETE';
120
199
  return result;
121
200
  }
122
201
 
@@ -16,12 +16,17 @@ export function createSupervisorTraceBridge({traceWriter,contract,error}){
16
16
  // grant. Public Trace MCP observation/diagnosis remains opt-in and does
17
17
  // not become reachable merely because Context collection is active.
18
18
  const isContextApi=req?.event==='context.api';
19
+ const form=/^form\.(prepared|submitted)\.(soft_observed|failed)$/.test(req?.event||'');
19
20
  const contextGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
20
21
  const contextAuthorized=process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
21
22
  &&typeof contextGrant==='string'
22
23
  &&/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(contextGrant)
23
24
  &&req?.projectRef===contextGrant;
25
+ // Form IDs are system-local correlation metadata, not user Project data.
26
+ // Keep them in the existing api_system Writer without requiring a
27
+ // per-Project Trace grant or exposing Project/Chat/task identifiers.
24
28
  if(isContextApi?!contextAuthorized:
29
+ form?req?.projectRef!=='api_system':
25
30
  !traceEnabled()||!allowedTraceProjects().has(req?.projectRef))
26
31
  throw error('TRACE_PROJECT_ACCESS_DENIED');
27
32
  // Context call observation has a stable event ID and typed API fields.
@@ -67,21 +72,25 @@ export function createSupervisorTraceBridge({traceWriter,contract,error}){
67
72
  return {contract:CONTRACT,requestId:req.requestId,status:'OK',
68
73
  eventId:recorded.eventId};
69
74
  }
70
- const form=/^form\.(prepared|submitted)\.soft_observed$/.test(req?.event||'');
71
75
  if(form){
76
+ const success=req.event.endsWith('.soft_observed');
72
77
  const allowed=new Set(['contract','action','requestId','traceId','spanId',
73
- 'projectRef','taskRef','evidenceRef','event','status']);
74
- if(req.contract!==CONTRACT||req.status!=='CONFIRMED'
78
+ 'projectRef','sessionRef','evidenceRef','event','status','errorCode']);
79
+ const validError=typeof req.errorCode==='string'
80
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(req.errorCode);
81
+ if(req.contract!==CONTRACT||req.projectRef!=='api_system'
82
+ ||req.status!==(success?'CONFIRMED':'FAILED')
75
83
  ||!UUID_RE.test(req.requestId||'')||!UUID_RE.test(req.traceId||'')
76
84
  ||!UUID_RE.test(req.spanId||'')
77
- ||!(/^[A-Za-z0-9_-]{8,80}$/).test(req.evidenceRef||'')
78
- ||req.taskRef!==undefined&&!(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/).test(req.taskRef)
85
+ ||!UUID_RE.test(req.sessionRef||'')
86
+ ||!(/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/).test(req.evidenceRef||'')
87
+ ||(success?req.errorCode!==undefined:!validError)
79
88
  ||Object.keys(req).some(k=>!allowed.has(k)))
80
89
  throw error('TRACE_INVALID_ARGUMENT');
81
90
  const written=traceWriter.record({traceId:req.traceId,
82
- parentSpanId:req.spanId,projectRef:req.projectRef,
83
- ...(req.taskRef?{taskRef:req.taskRef}:{}),requestId:req.requestId,
84
- component:'gateway',event:req.event,status:'CONFIRMED',
91
+ parentSpanId:req.spanId,sessionRef:req.sessionRef,projectRef:'api_system',
92
+ requestId:req.requestId,component:'gateway',event:req.event,
93
+ status:req.status,...(req.errorCode?{errorCode:req.errorCode}:{}),
85
94
  evidenceRef:req.evidenceRef});
86
95
  return {contract:CONTRACT,requestId:req.requestId,status:'OK',
87
96
  eventId:written.eventId};
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.9.18",
6
+ "version": "0.9.20",
7
7
  "type": "module",
8
8
  "description": "Chat Loop local tools: MCP gateway, isolated bundled tunnel-client and unified CLI",
9
9
  "bin": {
@@ -1,16 +1,13 @@
1
- // Fixed ChatGPT card adapter, not a second approval authority.
2
- // Form IDs identify interactions; Context Issue IDs own R/P decisions.
1
+ // Generic ChatGPT A/B form interaction service; business meaning belongs to callers.
3
2
  import {randomUUID} from 'node:crypto';
4
3
  import {readFileSync} from 'node:fs';
5
4
  const RESOURCE_URI='ui://chat-loop/form/review-v2';
5
+ // Preserve the legacy resource locator; both URIs serve the same audited UI.
6
+ const LEGACY_RESOURCE_URI='ui://chat-loop/form/review-v1';
6
7
  const RESOURCE_MIME='text/html;profile=mcp-app';
7
- const ID=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
8
- const FORM_ID=/^[A-Za-z0-9_-]{8,80}$/;
8
+ const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
9
9
  const UUID=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10
- const ISSUE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11
- const HASH=/^[a-f0-9]{64}$/;
12
10
  const fail=code=>Object.assign(Error(code),{code});
13
- const err=code=>({isError:true,content:[{type:'text',text:code}]});
14
11
  const ok=value=>({content:[{type:'text',text:JSON.stringify(value)}],
15
12
  structuredContent:value});
16
13
  const filled=(s,max)=>typeof s==='string'&&s.trim().length>0&&s.length<=max;
@@ -18,70 +15,34 @@ const shape=(v,fields)=>v&&typeof v==='object'&&!Array.isArray(v)
18
15
  &&Object.keys(v).every(k=>fields.includes(k));
19
16
  const CARD=['title','description','confirmLabel','modifyLabel',
20
17
  'modifyPlaceholder','submitLabel','footer'];
21
- const PREP=['mode','formId','projectId','taskId','chatRef','kind','documentId',
22
- 'version','contentHash','expectedTaskRevision','expectedStoreEpoch',
23
- 'writeRequestId','card'];
24
- const SUBMIT=['mode','formId','issueId','projectId','taskId','chatRef','kind',
25
- 'documentId','version','choice','comment','userTurn','presentedAssistantRef',
26
- 'expectedTaskRevision','expectedStoreEpoch','writeRequestId'];
27
- const common={
28
- mode:{type:'string',enum:['GENERAL','TEST_ONLY','MANAGED']},
29
- formId:{type:'string',pattern:FORM_ID.source},projectId:{type:'string',pattern:ID.source},
30
- taskId:{type:'string',pattern:ID.source},
31
- chatRef:{type:'string',minLength:8,maxLength:256},
32
- kind:{type:'string',enum:['R','P','CUSTOM']},
33
- documentId:{type:'string',pattern:ID.source},
34
- version:{type:'integer',minimum:1},
35
- expectedTaskRevision:{type:'integer',minimum:1},
36
- expectedStoreEpoch:{type:'string',minLength:10,maxLength:64},
37
- writeRequestId:{type:'string',minLength:8,maxLength:128}
38
- };
18
+ const PREP=['formId','card'];
19
+ const SUBMIT=['formId','traceRef','choice','comment'];
39
20
  const cardSchema={type:'object',additionalProperties:false,required:CARD,
40
21
  properties:Object.fromEntries(CARD.map(key=>[key,{type:'string',minLength:1,
41
22
  maxLength:['description','footer'].includes(key)?1200:180}]))};
42
23
  const tools=[
43
24
  {name:'chat_loop_form__prepare',description:
44
- 'Prepare the fixed ChatGPT A/B card. Optional formId is preserved; otherwise a fresh UUID is generated. GENERAL/TEST_ONLY never write Context; MANAGED creates one Context R/P Issue and returns its separate issueId.',
45
- inputSchema:{type:'object',additionalProperties:false,
46
- required:['mode','card'],
47
- properties:{...common,contentHash:{type:'string',pattern:HASH.source},
48
- card:cardSchema}},
25
+ 'Render a reusable A/B form. Preserve the optional caller-supplied formId or generate a UUID; also return an opaque traceRef for correlation and one-time submission protection. No business workflow or approval state is owned here.',
26
+ inputSchema:{type:'object',additionalProperties:false,required:['card'],
27
+ properties:{formId:{type:'string',pattern:FORM_ID.source},card:cardSchema}},
49
28
  annotations:{readOnlyHint:false},
50
29
  _meta:{ui:{resourceUri:RESOURCE_URI,visibility:['model','app']},
51
30
  'openai/outputTemplate':RESOURCE_URI,'openai/widgetAccessible':true}},
52
31
  {name:'chat_loop_form__submit',description:
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.',
32
+ 'Receive the selected A/B option and optional comment for a prepared form. Requires its formId and opaque traceRef; the shared Supervisor claims the traceRef once before the app may request a user message. The caller owns all business interpretation and follow-up.',
54
33
  inputSchema:{type:'object',additionalProperties:false,
55
- required:['mode','formId','choice','userTurn','presentedAssistantRef','writeRequestId'],
56
- properties:{...common,issueId:{type:'string',pattern:ISSUE.source},
34
+ required:['formId','traceRef','choice'],
35
+ properties:{formId:{type:'string',pattern:FORM_ID.source},
36
+ traceRef:{type:'string',pattern:UUID.source},
57
37
  choice:{type:'string',enum:['A','B']},
58
- comment:{type:'string',maxLength:4000},
59
- userTurn:{type:'string',minLength:8,maxLength:256},
60
- presentedAssistantRef:{type:'string',minLength:8,maxLength:256}}},
38
+ comment:{type:'string',maxLength:4000}}},
61
39
  annotations:{readOnlyHint:false},
62
- _meta:{ui:{visibility:['model','app']},
63
- 'openai/widgetAccessible':true}}
40
+ _meta:{ui:{visibility:['model','app']},'openai/widgetAccessible':true}}
64
41
  ];
65
42
  function check(a,fields){
66
- if(!shape(a,fields)||!['GENERAL','TEST_ONLY','MANAGED'].includes(a.mode)
67
- ||a.formId!==undefined&&!FORM_ID.test(a.formId)
68
- ||a.projectId!==undefined&&!ID.test(a.projectId)
69
- ||a.documentId!==undefined&&!ID.test(a.documentId)
70
- ||a.version!==undefined&&(!Number.isSafeInteger(a.version)||a.version<1)
71
- ||a.kind!==undefined&&!['R','P','CUSTOM'].includes(a.kind))
43
+ if(!shape(a,fields)
44
+ ||a.formId!==undefined&&(typeof a.formId!=='string'||!FORM_ID.test(a.formId)))
72
45
  throw fail('FORM_INVALID_ARGUMENT');
73
- if(['R','P'].includes(a.kind)&&(!ID.test(a.documentId||'')
74
- ||!Number.isSafeInteger(a.version)))throw fail('FORM_REVIEW_SCOPE_REQUIRED');
75
- if(a.mode!=='GENERAL'&&(!ID.test(a.projectId||'')
76
- ||!ID.test(a.documentId||'')||!Number.isSafeInteger(a.version)
77
- ||!['R','P'].includes(a.kind)))throw fail('FORM_REVIEW_SCOPE_REQUIRED');
78
- if(a.mode==='TEST_ONLY'&&(!filled(a.chatRef,256)||a.chatRef.length<8))
79
- throw fail('FORM_TEST_CHAT_REQUIRED');
80
- if(a.mode==='MANAGED'&&(!ID.test(a.taskId||'')
81
- ||!Number.isSafeInteger(a.expectedTaskRevision)
82
- ||a.expectedTaskRevision<1||!filled(a.expectedStoreEpoch,64)
83
- ||!filled(a.writeRequestId,128)))
84
- throw fail('FORM_MANAGED_SCOPE_REQUIRED');
85
46
  }
86
47
  function checkCard(a){
87
48
  if(!shape(a.card,CARD)||CARD.some(x=>!Object.hasOwn(a.card,x)))
@@ -91,21 +52,14 @@ function checkCard(a){
91
52
  throw fail('FORM_CARD_INVALID');
92
53
  }
93
54
  if(!/^A\s*[—-]/.test(a.card.confirmLabel)
94
- ||!/^B\s*[—-]/.test(a.card.modifyLabel)
95
- ||a.kind==='R'&&a.card.submitLabel!=='提交需求评审'
96
- ||a.kind==='P'&&a.card.submitLabel!=='提交方案评审')
55
+ ||!/^B\s*[—-]/.test(a.card.modifyLabel))
97
56
  throw fail('FORM_CARD_LAYOUT_INVALID');
98
57
  }
99
- function view(a,formId,issueId,prior){
100
- const review=a.kind==='R'||a.kind==='P';
101
- return {template:'chat-loop-review-card-v1',formId,mode:a.mode,
58
+ function view(a,formId){
59
+ return {template:'chat-loop-review-card-v1',formId,
102
60
  layout:{card:'rounded-border',radiusPx:12,paddingPx:12,gapPx:12,
103
61
  direction:'column',optionDirection:'column',buttonWidth:'full',
104
62
  buttonShape:'pill'},
105
- badges:review
106
- ?[...(prior?[{text:prior+' SUPERSEDED'}]:[]),
107
- {text:a.documentId+' CURRENT'},{text:'WAITING_APPROVAL'}]
108
- :[{text:'WAITING_INPUT'}],
109
63
  title:a.card.title,description:a.card.description,
110
64
  options:[{value:'A',label:a.card.confirmLabel},
111
65
  {value:'B',label:a.card.modifyLabel}],
@@ -113,175 +67,106 @@ function view(a,formId,issueId,prior){
113
67
  placeholder:a.card.modifyPlaceholder},
114
68
  submit:{label:a.card.submitLabel,disabledInitially:true,
115
69
  singleClickLock:true,issueNewUserTurn:true},
116
- footer:a.card.footer,
117
- ...(review?{documentId:a.documentId,version:a.version}:{}),
118
- authority:issueId?'CONTEXT_ISSUE':'NONE'};
70
+ footer:a.card.footer};
119
71
  }
120
72
  function trace(form){
121
73
  const parent=form?.current?.();
122
74
  return parent&&UUID.test(parent.traceId||'')&&UUID.test(parent.spanId||'')
123
75
  ?{traceId:parent.traceId,spanId:parent.spanId}:null;
124
76
  }
125
- function contextAccess(context){
126
- if(context?.contextGatewayEnabled?.()!==true)
127
- throw fail('FORM_CONTEXT_UNAVAILABLE');
128
- }
129
- async function request(context,kind,args){
130
- return context.runContextGateway(
131
- kind==='get'?'chat_loop_context_get':'chat_loop_context_mutate',args);
77
+ async function observeForm(form,event,formId,traceRef,parent,status='CONFIRMED',errorCode){
78
+ if(typeof form?.observe!=='function'||!FORM_ID.test(formId||'')
79
+ ||!UUID.test(traceRef||''))return false;
80
+ if(!parent){
81
+ form?.lost?.();
82
+ return false;
83
+ }
84
+ try{
85
+ const result=await form.observe({
86
+ event,formId,traceRef,status,...(errorCode?{errorCode}:{}),...parent
87
+ });
88
+ if(result?.status!=='OK'||!UUID.test(result.eventId||'')){
89
+ form?.lost?.();
90
+ return false;
91
+ }
92
+ return true;
93
+ }catch{
94
+ form?.lost?.();
95
+ return false;
96
+ }
132
97
  }
133
- async function prepare(a,context,form){
134
- check(a,PREP);checkCard(a);
135
- const formId=a.formId||randomUUID();
136
- if(a.mode!=='MANAGED'){
137
- return {status:a.mode==='TEST_ONLY'?'TEST_ONLY_PREVIEW':'FORM_PREPARED_SOFT',
138
- formId,mode:a.mode,kind:a.kind||'CUSTOM',
139
- ...(a.projectId?{projectId:a.projectId}:{}),
140
- ...(a.chatRef?{chatRef:a.chatRef}:{}),
141
- ...(a.documentId?{documentId:a.documentId,version:a.version}:{}),
142
- view:view(a,formId,null,a.kind!=='CUSTOM'&&a.version>1
143
- ?a.documentId[0]+(a.version-1):null),
144
- trace:trace(form),approvalAuthority:'NONE',businessSideEffects:false,
145
- provenance:'FORM_ID_ONLY_NO_DURABLE_ISSUE'};
98
+ function prepare(a){
99
+ const formId=a?.formId===undefined?randomUUID():a.formId;
100
+ const traceRef=randomUUID();
101
+ try{check(a,PREP);checkCard(a)}
102
+ catch(error){
103
+ error.formId=typeof formId==='string'&&FORM_ID.test(formId)
104
+ ?formId:randomUUID();
105
+ error.traceRef=traceRef;
106
+ throw error;
146
107
  }
147
- if(!HASH.test(a.contentHash||''))throw fail('FORM_CONTENT_HASH_REQUIRED');
148
- contextAccess(context);
149
- const doc=await request(context,'get',{operation:'document.get',projectId:a.projectId,
150
- taskId:a.taskId,documentId:a.documentId,version:a.version});
151
- if(doc?.kind!==a.kind||doc?.contentHash!==a.contentHash)
152
- throw fail('FORM_DOCUMENT_MISMATCH');
153
- const list=await request(context,'get',{operation:'document.list',
154
- projectId:a.projectId,taskId:a.taskId});
155
- const prior=Array.isArray(list)&&list.some(x=>x.kind===a.kind&&
156
- x.version===a.version-1&&x.documentId===a.documentId[0]+(a.version-1))
157
- ?a.documentId[0]+(a.version-1):null;
158
- const issue=await request(context,'mutate',{operation:'document.prepareIssue',
159
- projectId:a.projectId,taskId:a.taskId,documentId:a.documentId,
160
- version:a.version,contentHash:a.contentHash,
161
- expectedTaskRevision:a.expectedTaskRevision,
162
- expectedStoreEpoch:a.expectedStoreEpoch,writeRequestId:a.writeRequestId});
163
- if(issue?.status!=='ISSUE_PENDING'||!ISSUE.test(issue.issueId||''))
164
- throw fail('FORM_ISSUE_RECEIPT_INVALID');
165
- // Reuse the durable Issue identity by default to keep MANAGED retries stable;
166
- // a caller-supplied formId is a separate non-authoritative UI correlation ID.
167
- const managedFormId=a.formId||issue.issueId;
168
- return {status:'WAITING_APPROVAL',formId:managedFormId,issueId:issue.issueId,
169
- mode:a.mode,projectId:a.projectId,taskId:a.taskId,
170
- documentId:a.documentId,version:a.version,kind:a.kind,
171
- taskRevision:issue.taskRevision,approvalRevision:issue.approvalRevision,
172
- writeRequestId:a.writeRequestId,trace:trace(form),
173
- view:view(a,managedFormId,issue.issueId,prior),approvalAuthority:'CONTEXT',
174
- businessSideEffects:true};
108
+ return {status:'FORM_PREPARED',formId,traceRef,view:view(a,formId)};
175
109
  }
176
110
  function validateSubmit(a){
177
111
  check(a,SUBMIT);
178
- if(!FORM_ID.test(a.formId||'')||!['A','B'].includes(a.choice)
179
- ||!filled(a.userTurn,256)||!filled(a.presentedAssistantRef,256)
180
- ||!filled(a.writeRequestId,128))
112
+ if(typeof a.formId!=='string'||!FORM_ID.test(a.formId)
113
+ ||typeof a.traceRef!=='string'||!UUID.test(a.traceRef)
114
+ ||!['A','B'].includes(a.choice))
181
115
  throw fail('FORM_SUBMISSION_INVALID');
182
116
  if(a.choice==='B'&&!filled(a.comment,4000)
183
117
  ||a.choice==='A'&&a.comment!==undefined&&a.comment!=='')
184
118
  throw fail('FORM_COMMENT_INVALID');
185
- if(a.mode==='MANAGED'&&!ISSUE.test(a.issueId||''))
186
- throw fail('FORM_ISSUE_REF_REQUIRED');
187
119
  }
188
- async function submit(a,context,form){
120
+ async function submit(a,form){
189
121
  validateSubmit(a);
190
- if(a.mode!=='MANAGED'){
191
- return {status:'FORM_SUBMISSION_OBSERVED_SOFT',formId:a.formId,
192
- choice:a.choice,trace:trace(form),approvalAuthority:'NONE',
193
- businessSideEffects:false,preparedFormIdVerified:false,
194
- platformProvenance:'AGENT_ASSERTED_UNVERIFIED'};
195
- }
196
- if(!ISSUE.test(a.issueId||''))throw fail('FORM_ISSUE_REF_REQUIRED');
197
- contextAccess(context);
198
- const result=await request(context,'mutate',{operation:'approval.observe',
199
- projectId:a.projectId,taskId:a.taskId,issueId:a.issueId,
200
- decision:a.choice==='A'?'APPROVE':'REQUEST_CHANGE',
201
- sourceRole:'user',userTurn:a.userTurn,
202
- presentedAssistantRef:a.presentedAssistantRef,
203
- expectedTaskRevision:a.expectedTaskRevision,
204
- expectedStoreEpoch:a.expectedStoreEpoch,writeRequestId:a.writeRequestId});
205
- if(!['APPROVED_SOFT','CHANGE_REQUESTED'].includes(result?.status))
206
- throw fail('FORM_APPROVAL_RECEIPT_INVALID');
207
- return {status:result.status,formId:a.formId,issueId:a.issueId,
208
- kind:result.kind,choice:a.choice,taskRevision:result.taskRevision,
209
- ...(result.approvalRevision?{approvalRevision:result.approvalRevision}:{}),
210
- writeRequestId:a.writeRequestId,trace:trace(form),
211
- approvalAuthority:'CONTEXT',proofLevel:'SOFT_USER_TURN',
212
- formIssueBinding:'CALLER_ASSERTED_UNVERIFIED',
213
- platformProvenance:'AGENT_ASSERTED_UNVERIFIED'};
122
+ if(typeof form?.claimSubmission!=='function')
123
+ throw fail('FORM_SUBMISSION_CLAIM_UNAVAILABLE');
124
+ let claim;
125
+ try{claim=await form.claimSubmission({formId:a.formId,traceRef:a.traceRef})}
126
+ catch(error){throw fail(error?.code||'FORM_SUBMISSION_CLAIM_UNKNOWN')}
127
+ if(claim?.status!=='FORM_SUBMISSION_CLAIMED')
128
+ throw fail(claim?.error?.code||'FORM_SUBMISSION_CLAIM_UNKNOWN');
129
+ return {status:'FORM_SUBMITTED',formId:a.formId,traceRef:a.traceRef,
130
+ choice:a.choice,...(a.comment?{comment:a.comment}:{})};
214
131
  }
215
132
  export const provider=Object.freeze({
216
133
  id:'form',order:5,names:tools.map(x=>x.name),
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
- };
134
+ create({form}={}){
135
+ // Pure interaction adapter: no caller identity, business Context, form
136
+ // registry, expiry, capacity limit, or process-local lifecycle state.
226
137
  return Object.freeze({
227
138
  tools:()=>tools,
228
- resources:()=>[{uri:RESOURCE_URI,name:'Chat Loop Review',
229
- mimeType:RESOURCE_MIME,description:'A/B review with one locked submit'}],
139
+ resources:()=>[RESOURCE_URI,LEGACY_RESOURCE_URI].map(uri=>({
140
+ uri,name:'Chat Loop Form',mimeType:RESOURCE_MIME,
141
+ description:'Reusable A/B form UI'
142
+ })),
230
143
  async readResource(uri){
231
- if(uri!==RESOURCE_URI)throw fail('MCP_RESOURCE_NOT_FOUND');
144
+ if(uri!==RESOURCE_URI&&uri!==LEGACY_RESOURCE_URI)
145
+ throw fail('MCP_RESOURCE_NOT_FOUND');
232
146
  return {contents:[{uri,mimeType:RESOURCE_MIME,
233
147
  text:readFileSync(new URL('../ui/form/review.html',import.meta.url),'utf8'),
234
148
  _meta:{'openai/ui':{availableDisplayModes:['inline'],
235
149
  preferredDisplayMode:'inline'}}}]};
236
150
  },
237
151
  async call(name,args){
152
+ const isPrepare=name===tools[0].name;
153
+ const isSubmit=name===tools[1].name;
154
+ if(!isPrepare&&!isSubmit)throw fail('UNKNOWN_TOOL');
155
+ const parent=trace(form);
156
+ const formId=typeof args?.formId==='string'?args.formId:null;
157
+ const traceRef=typeof args?.traceRef==='string'?args.traceRef:null;
238
158
  try{
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
- }
271
- if(result&&args?.projectId&&typeof form?.observe==='function'){
272
- const parent=trace(form);
273
- if(parent)setImmediate(()=>{
274
- // Soft evidence, never an approval receipt or a retry trigger.
275
- try{void Promise.resolve(form.observe({
276
- event:name===tools[0].name?'form.prepared.soft_observed'
277
- :'form.submitted.soft_observed',
278
- projectRef:args.projectId,taskRef:args.taskId,
279
- formId:result.formId,...parent
280
- })).catch(()=>{})}catch{/* telemetry isolation */}
281
- });
282
- }
283
- return result?ok(result):err('UNKNOWN_TOOL');
284
- }catch(e){return err(e.code||'FORM_FAILED')}
159
+ const result=isPrepare?prepare(args):await submit(args,form);
160
+ await observeForm(form,
161
+ isPrepare?'form.prepared.soft_observed':'form.submitted.soft_observed',
162
+ result.formId,result.traceRef,parent);
163
+ return ok(result);
164
+ }catch(e){
165
+ await observeForm(form,
166
+ isPrepare?'form.prepared.failed':'form.submitted.failed',
167
+ e.formId||formId,e.traceRef||traceRef,parent,'FAILED',e.code||'FORM_FAILED');
168
+ throw e;
169
+ }
285
170
  }
286
171
  });
287
172
  }
@@ -6,9 +6,12 @@ export const provider=Object.freeze({
6
6
  id:'trace',order:4,names,
7
7
  create({trace}){
8
8
  return Object.freeze({
9
- tools:()=>trace.traceGatewayEnabled()?[traceDiagnoseTool,traceStageTool]:[],
9
+ tools:()=>trace.traceGatewayEnabled()
10
+ ?[traceDiagnoseTool,traceStageTool]:[traceDiagnoseTool],
10
11
  async call(name,args){
11
- if(!trace.traceGatewayEnabled())return fail('UNKNOWN_TOOL');
12
+ const formLookup=name===traceDiagnoseTool.name
13
+ &&args?.projectRef==='api_system';
14
+ if(!trace.traceGatewayEnabled()&&!formLookup)return fail('UNKNOWN_TOOL');
12
15
  try{
13
16
  const result=name===traceStageTool.name
14
17
  ?await trace.runTraceStage(args)
@@ -1,11 +1,12 @@
1
1
  // Minimal MCP Apps View bridge: JSON-RPC over postMessage, no bundled runtime.
2
2
  // Protocol: https://modelcontextprotocol.io/extensions/apps
3
- // GENERAL/TEST_ONLY only; MANAGED approval remains Context + real user Turn.
3
+ // The Form service only renders, collects and returns user selections.
4
4
  const $=id=>document.getElementById(id);
5
5
  const options=[...document.querySelectorAll('input[name="choice"]')];
6
- const idPattern=/^[A-Za-z0-9_-]{8,80}$/;
6
+ const idPattern=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
7
+ const tracePattern=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
7
8
  const requests=new Map();
8
- let seq=0,connected=false,prepared=null,locked=false,toolResult=null;
9
+ let seq=0,connected=false,prepared=null,locked=false,toolResult=null,hostFailure=null;
9
10
  function status(message,state='info'){
10
11
  $('status').textContent=message;
11
12
  $('status').dataset.state=state;
@@ -16,6 +17,7 @@ function call(method,params){
16
17
  if(!connected)throw Error('FORM_APP_NOT_INITIALIZED');
17
18
  return new Promise((resolve,reject)=>{
18
19
  const id=++seq;
20
+ // Transport reply timeout only; it never expires or deletes a prepared form.
19
21
  // A timeout never authorizes a retry of a write.
20
22
  const timer=setTimeout(()=>{
21
23
  requests.delete(id);reject(Error('FORM_APP_REPLY_UNKNOWN'));
@@ -25,7 +27,11 @@ function call(method,params){
25
27
  });
26
28
  }
27
29
  function decode(result){
28
- if(result?.isError)throw Error('FORM_TOOL_REJECTED');
30
+ if(result?.isError){
31
+ const code=result.content?.find(x=>x.type==='text')?.text;
32
+ throw Error(typeof code==='string'
33
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(code)?code:'FORM_TOOL_REJECTED');
34
+ }
29
35
  if(result?.structuredContent?.status)return result.structuredContent;
30
36
  const text=result?.content?.find(x=>x.type==='text')?.text;
31
37
  if(typeof text!=='string'||text.length>20000)throw Error('FORM_RECEIPT_MISSING');
@@ -34,22 +40,24 @@ function decode(result){
34
40
  const selected=()=>options.find(x=>x.checked)?.value||null;
35
41
  function update(){
36
42
  const choice=selected();
43
+ $('options').disabled=!connected;
37
44
  $('modify').hidden=choice!=='B';
38
- $('submit').disabled=!prepared||locked||!choice
45
+ $('submit').disabled=!connected||!prepared||locked||!choice
39
46
  ||(choice==='B'&&!$('comment').value.trim());
40
47
  resize();
41
48
  }
42
49
  function render(value){
43
50
  const view=value?.view;
44
51
  if(!view||view.template!=='chat-loop-review-card-v1'
45
- ||!idPattern.test(value.formId||'')
52
+ ||typeof value.formId!=='string'||!idPattern.test(value.formId)
53
+ ||typeof value.traceRef!=='string'||!tracePattern.test(value.traceRef)
46
54
  ||view.formId!==value.formId
47
- ||!['GENERAL','TEST_ONLY','MANAGED'].includes(view.mode)
48
55
  ||view.options?.length!==2
49
56
  ||view.options[0]?.value!=='A'||view.options[1]?.value!=='B')
50
57
  throw Error('FORM_VIEW_INVALID');
51
- const safe=view.mode==='GENERAL'||view.mode==='TEST_ONLY';
52
- prepared={...value,mode:view.mode};
58
+ const preserveLock=prepared?.formId===value.formId
59
+ &&prepared?.traceRef===value.traceRef&&locked;
60
+ prepared=value;
53
61
  $('title').textContent=view.title;
54
62
  $('description').textContent=view.description;
55
63
  $('a-label').textContent=view.options[0].label;
@@ -57,12 +65,13 @@ function render(value){
57
65
  $('comment').placeholder=view.modifyField?.placeholder||'填写修改意见';
58
66
  $('submit').textContent=view.submit?.label||'提交';
59
67
  $('footer').textContent=view.footer||'';
60
- $('options').disabled=!safe;
68
+ $('options').disabled=!connected;
61
69
  $('comment').value='';
62
70
  options.forEach(x=>x.checked=false);
63
- locked=!safe;
64
- status(safe?'已连接 Form prepare;请选择 A 或 B。':
65
- '正式审批需要真实用户消息身份,组件不得代签。',safe?'ok':'error');
71
+ locked=preserveLock;
72
+ status(hostFailure|| (connected?'表单已准备,请选择 A 或 B。':
73
+ '表单已准备,正在等待宿主能力确认。'),
74
+ hostFailure?'error':connected?'ok':'info');
66
75
  update();
67
76
  }
68
77
  function receive(event){
@@ -113,64 +122,70 @@ async function initialize(){
113
122
  });
114
123
  try{
115
124
  const response=await init;
116
- if(!response?.protocolVersion||!response.hostInfo)
125
+ if(!response?.protocolVersion||!response.hostInfo
126
+ ||!response.hostCapabilities)
117
127
  throw Error('FORM_APP_INIT_INVALID');
128
+ if(!response.hostCapabilities.serverTools
129
+ ||!response.hostCapabilities.message?.text){
130
+ hostFailure='当前宿主缺少 serverTools 或 message.text 能力,表单不可提交。';
131
+ status(hostFailure,'error');
132
+ update();
133
+ return;
134
+ }
118
135
  connected=true;
136
+ hostFailure=null;
119
137
  notify('ui/notifications/initialized',{});
120
138
  resize();
121
139
  if(toolResult)render(decode(toolResult));
122
140
  if(typeof ResizeObserver==='function')
123
141
  new ResizeObserver(resize).observe(document.documentElement);
124
142
  }catch{
125
- status('MCP App 初始化失败,请核查 ChatGPT 宿主连接。','error');
143
+ hostFailure='MCP App 初始化失败,请核查宿主连接与协议能力。';
144
+ status(hostFailure,'error');
145
+ connected=false;
146
+ update();
126
147
  }
127
148
  }
128
149
  async function submit(){
129
- if(!connected||locked||!prepared
130
- ||!['GENERAL','TEST_ONLY'].includes(prepared.mode))return;
150
+ if(!connected||locked||!prepared)return;
131
151
  const choice=selected(),comment=$('comment').value.trim();
132
152
  if(!['A','B'].includes(choice)||choice==='B'&&!comment)return;
133
153
  locked=true;update();
134
- const {formId,mode}=prepared,writeRequestId=crypto.randomUUID();
135
- const args={mode,formId,choice,kind:prepared.kind,
136
- ...(choice==='B'?{comment}:{}),
137
- userTurn:'unverified-app-'+writeRequestId,
138
- presentedAssistantRef:'app-form-'+formId,
139
- writeRequestId,
140
- ...(mode==='TEST_ONLY'?{
141
- projectId:prepared.projectId,chatRef:prepared.chatRef,
142
- documentId:prepared.documentId,version:prepared.version
143
- }:{})};
144
- status('正在向 Form submit 提交唯一请求…');
154
+ const {formId,traceRef}=prepared;
155
+ const args={formId,traceRef,choice,...(choice==='B'?{comment}:{})};
156
+ status('正在提交表单…');
145
157
  let receipt;
146
158
  try{receipt=decode(await call('tools/call',{
147
159
  name:'chat_loop_form__submit',arguments:args
148
160
  }))}
149
- catch{
150
- status('Submit 结果未知,禁止重复提交;请查原请求回执。','error');
161
+ catch(error){
162
+ const code=typeof error?.message==='string'
163
+ &&/^[A-Z][A-Z0-9_]{1,95}$/.test(error.message)
164
+ ?error.message:'FORM_APP_REPLY_UNKNOWN';
165
+ status(code==='FORM_APP_REPLY_UNKNOWN'||code==='FORM_SUBMISSION_CLAIM_UNKNOWN'
166
+ ?'Submit 结果未知,已锁定,禁止重复提交;请查原请求回执。'
167
+ :code==='FORM_ALREADY_SUBMITTED'
168
+ ?'该表单已提交过,禁止重复发送;请核查原消息。'
169
+ :'Submit 明确失败('+code+'),用户消息未发送。','error');
151
170
  return;
152
171
  }
153
- if(receipt.status!=='FORM_SUBMISSION_OBSERVED_SOFT'
154
- ||receipt.formId!==formId||receipt.choice!==choice
155
- ||receipt.preparedFormIdVerified!==true){
156
- status('Submit 未验证绑定,用户消息未发送。','error');
172
+ if(receipt.status!=='FORM_SUBMITTED'
173
+ ||receipt.formId!==formId||receipt.traceRef!==traceRef
174
+ ||receipt.choice!==choice){
175
+ status('Submit 返回的信息与当前表单不匹配,用户消息未发送。','error');
157
176
  return;
158
177
  }
159
- const version=prepared.documentId
160
- ?prepared.documentId+' v'+prepared.version:'自定义表单';
161
- const text='【Chat Loop Form|'+mode+'】formId='+formId+'|'+version+'|'
162
- +(choice==='A'?'A 确认':'B 修改:'+comment)
163
- +'。组件请求发送,用户消息身份须独立核对。'
164
- +(mode==='TEST_ONLY'?'不构成正式审批,不 Start/Continue/Handoff。':'');
165
- status('Submit 软回执成功,正在申请单次用户消息…');
178
+ const text='【Chat Loop Form】formId='+formId+'|'
179
+ +(choice==='A'?'A 选择':'B 选择:'+comment)+'。';
180
+ status('单次提交已锁定,正在申请当前 Chat 用户消息…');
166
181
  try{
167
182
  const result=await call('ui/message',{
168
183
  role:'user',content:[{type:'text',text}]
169
184
  });
170
- status(result?.isError?'宿主拒绝消息;未完成正式审批。':
171
- '宿主接受消息请求;userMessageId 仍需独立核验。',
185
+ status(result?.isError?'宿主未接受表单结果消息。':
186
+ '宿主已接受用户消息请求;平台消息身份仍需独立核验。',
172
187
  result?.isError?'error':'ok');
173
- }catch{status('宿主消息状态未知,禁止重复发送。','error')}
188
+ }catch{status('用户消息发送状态未知,已锁定,禁止重试;请核查原消息。','error')}
174
189
  }
175
190
  window.addEventListener('message',receive);
176
191
  options.forEach(x=>x.addEventListener('change',update));
@@ -40,7 +40,7 @@ button:disabled{opacity:.44;cursor:not-allowed}
40
40
  <div id="status" role="status">等待真实 MCP Form prepare 回执</div>
41
41
  <small id="footer"></small>
42
42
  </main>
43
- <script>(()=>{var r=t=>document.getElementById(t),I=[...document.querySelectorAll('input[name="choice"]')],P=/^[A-Za-z0-9_-]{8,80}$/,d=new Map,v=0,l=!1,n=null,u=!1,m=null;function s(t,e="info"){r("status").textContent=t,r("status").dataset.state=e}function f(t){window.parent.postMessage({jsonrpc:"2.0",...t},"*")}function R(t,e={}){f({method:t,params:e})}function O(t,e){if(!l)throw Error("FORM_APP_NOT_INITIALIZED");return new Promise((o,i)=>{let c=++v,h=setTimeout(()=>{d.delete(c),i(Error("FORM_APP_REPLY_UNKNOWN"))},3e4);d.set(c,{resolve:o,reject:i,timer:h}),f({id:c,method:t,params:e})})}function _(t){if(t?.isError)throw Error("FORM_TOOL_REJECTED");if(t?.structuredContent?.status)return t.structuredContent;let e=t?.content?.find(o=>o.type==="text")?.text;if(typeof e!="string"||e.length>2e4)throw Error("FORM_RECEIPT_MISSING");return JSON.parse(e)}var A=()=>I.find(t=>t.checked)?.value||null;function p(){let t=A();r("modify").hidden=t!=="B",r("submit").disabled=!n||u||!t||t==="B"&&!r("comment").value.trim(),E()}function C(t){let e=t?.view;if(!e||e.template!=="chat-loop-review-card-v1"||!P.test(t.formId||"")||e.formId!==t.formId||!["GENERAL","TEST_ONLY","MANAGED"].includes(e.mode)||e.options?.length!==2||e.options[0]?.value!=="A"||e.options[1]?.value!=="B")throw Error("FORM_VIEW_INVALID");let o=e.mode==="GENERAL"||e.mode==="TEST_ONLY";n={...t,mode:e.mode},r("title").textContent=e.title,r("description").textContent=e.description,r("a-label").textContent=e.options[0].label,r("b-label").textContent=e.options[1].label,r("comment").placeholder=e.modifyField?.placeholder||"\u586B\u5199\u4FEE\u6539\u610F\u89C1",r("submit").textContent=e.submit?.label||"\u63D0\u4EA4",r("footer").textContent=e.footer||"",r("options").disabled=!o,r("comment").value="",I.forEach(i=>i.checked=!1),u=!o,s(o?"\u5DF2\u8FDE\u63A5 Form prepare\uFF1B\u8BF7\u9009\u62E9 A \u6216 B\u3002":"\u6B63\u5F0F\u5BA1\u6279\u9700\u8981\u771F\u5B9E\u7528\u6237\u6D88\u606F\u8EAB\u4EFD\uFF0C\u7EC4\u4EF6\u4E0D\u5F97\u4EE3\u7B7E\u3002",o?"ok":"error"),p()}function L(t){if(t.source!==window.parent)return;let e=t.data;if(!(!e||e.jsonrpc!=="2.0"||typeof e!="object")){if(Object.hasOwn(e,"id")&&!Object.hasOwn(e,"method")){let o=d.get(e.id);if(!o)return;d.delete(e.id),clearTimeout(o.timer),e.error?o.reject(Error("MCP_APP_HOST_REJECTED")):o.resolve(e.result);return}if(e.method==="ui/notifications/tool-result"){m=e.params;try{C(_(m))}catch{s("Form prepare \u56DE\u6267\u65E0\u6548\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error")}}e.method==="ui/resource-teardown"&&e.id!==void 0&&f({id:e.id,result:{}})}}var T=0,b=0;function E(){if(!l)return;let t=Math.ceil(document.documentElement.scrollHeight),e=Math.ceil(document.documentElement.clientWidth);t===T&&e===b||(T=t,b=e,R("ui/notifications/size-changed",{width:e,height:t}))}async function S(){if(window.parent===window){s("\u672A\u5728 ChatGPT MCP App iframe \u4E2D\u8FD0\u884C\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error");return}let t=++v,e=new Promise((o,i)=>{let c=setTimeout(()=>{d.delete(t),i(Error("FORM_APP_INIT_TIMEOUT"))},12e3);d.set(t,{resolve:o,reject:i,timer:c}),f({id:t,method:"ui/initialize",params:{appInfo:{name:"Chat Loop Review",version:"1.0.1"},appCapabilities:{},protocolVersion:"2026-01-26"}})});try{let o=await e;if(!o?.protocolVersion||!o.hostInfo)throw Error("FORM_APP_INIT_INVALID");l=!0,R("ui/notifications/initialized",{}),E(),m&&C(_(m)),typeof ResizeObserver=="function"&&new ResizeObserver(E).observe(document.documentElement)}catch{s("MCP App \u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u6838\u67E5 ChatGPT \u5BBF\u4E3B\u8FDE\u63A5\u3002","error")}}async function g(){if(!l||u||!n||!["GENERAL","TEST_ONLY"].includes(n.mode))return;let t=A(),e=r("comment").value.trim();if(!["A","B"].includes(t)||t==="B"&&!e)return;u=!0,p();let{formId:o,mode:i}=n,c=crypto.randomUUID(),h={mode:i,formId:o,choice:t,kind:n.kind,...t==="B"?{comment:e}:{},userTurn:"unverified-app-"+c,presentedAssistantRef:"app-form-"+o,writeRequestId:c,...i==="TEST_ONLY"?{projectId:n.projectId,chatRef:n.chatRef,documentId:n.documentId,version:n.version}:{}};s("\u6B63\u5728\u5411 Form submit \u63D0\u4EA4\u552F\u4E00\u8BF7\u6C42\u2026");let a;try{a=_(await O("tools/call",{name:"chat_loop_form__submit",arguments:h}))}catch{s("Submit \u7ED3\u679C\u672A\u77E5\uFF0C\u7981\u6B62\u91CD\u590D\u63D0\u4EA4\uFF1B\u8BF7\u67E5\u539F\u8BF7\u6C42\u56DE\u6267\u3002","error");return}if(a.status!=="FORM_SUBMISSION_OBSERVED_SOFT"||a.formId!==o||a.choice!==t||a.preparedFormIdVerified!==!0){s("Submit \u672A\u9A8C\u8BC1\u7ED1\u5B9A\uFF0C\u7528\u6237\u6D88\u606F\u672A\u53D1\u9001\u3002","error");return}let N=n.documentId?n.documentId+" v"+n.version:"\u81EA\u5B9A\u4E49\u8868\u5355",M="\u3010Chat Loop Form\uFF5C"+i+"\u3011formId="+o+"\uFF5C"+N+"\uFF5C"+(t==="A"?"A \u786E\u8BA4":"B \u4FEE\u6539\uFF1A"+e)+"\u3002\u7EC4\u4EF6\u8BF7\u6C42\u53D1\u9001\uFF0C\u7528\u6237\u6D88\u606F\u8EAB\u4EFD\u987B\u72EC\u7ACB\u6838\u5BF9\u3002"+(i==="TEST_ONLY"?"\u4E0D\u6784\u6210\u6B63\u5F0F\u5BA1\u6279\uFF0C\u4E0D Start/Continue/Handoff\u3002":"");s("Submit \u8F6F\u56DE\u6267\u6210\u529F\uFF0C\u6B63\u5728\u7533\u8BF7\u5355\u6B21\u7528\u6237\u6D88\u606F\u2026");try{let w=await O("ui/message",{role:"user",content:[{type:"text",text:M}]});s(w?.isError?"\u5BBF\u4E3B\u62D2\u7EDD\u6D88\u606F\uFF1B\u672A\u5B8C\u6210\u6B63\u5F0F\u5BA1\u6279\u3002":"\u5BBF\u4E3B\u63A5\u53D7\u6D88\u606F\u8BF7\u6C42\uFF1BuserMessageId \u4ECD\u9700\u72EC\u7ACB\u6838\u9A8C\u3002",w?.isError?"error":"ok")}catch{s("\u5BBF\u4E3B\u6D88\u606F\u72B6\u6001\u672A\u77E5\uFF0C\u7981\u6B62\u91CD\u590D\u53D1\u9001\u3002","error")}}window.addEventListener("message",L);I.forEach(t=>t.addEventListener("change",p));r("comment").addEventListener("input",p);r("submit").addEventListener("click",g);S();})();
43
+ <script>(()=>{var r=t=>document.getElementById(t),w=[...document.querySelectorAll('input[name="choice"]')],N=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/,T=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,u=new Map,P=0,s=!1,l=null,p=!1,_=null,d=null;function i(t,e="info"){r("status").textContent=t,r("status").dataset.state=e}function E(t){window.parent.postMessage({jsonrpc:"2.0",...t},"*")}function g(t,e={}){E({method:t,params:e})}function O(t,e){if(!s)throw Error("FORM_APP_NOT_INITIALIZED");return new Promise((o,n)=>{let c=++P,a=setTimeout(()=>{u.delete(c),n(Error("FORM_APP_REPLY_UNKNOWN"))},3e4);u.set(c,{resolve:o,reject:n,timer:a}),E({id:c,method:t,params:e})})}function b(t){if(t?.isError){let o=t.content?.find(n=>n.type==="text")?.text;throw Error(typeof o=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(o)?o:"FORM_TOOL_REJECTED")}if(t?.structuredContent?.status)return t.structuredContent;let e=t?.content?.find(o=>o.type==="text")?.text;if(typeof e!="string"||e.length>2e4)throw Error("FORM_RECEIPT_MISSING");return JSON.parse(e)}var M=()=>w.find(t=>t.checked)?.value||null;function m(){let t=M();r("options").disabled=!s,r("modify").hidden=t!=="B",r("submit").disabled=!s||!l||p||!t||t==="B"&&!r("comment").value.trim(),I()}function C(t){let e=t?.view;if(!e||e.template!=="chat-loop-review-card-v1"||typeof t.formId!="string"||!N.test(t.formId)||typeof t.traceRef!="string"||!T.test(t.traceRef)||e.formId!==t.formId||e.options?.length!==2||e.options[0]?.value!=="A"||e.options[1]?.value!=="B")throw Error("FORM_VIEW_INVALID");let o=l?.formId===t.formId&&l?.traceRef===t.traceRef&&p;l=t,r("title").textContent=e.title,r("description").textContent=e.description,r("a-label").textContent=e.options[0].label,r("b-label").textContent=e.options[1].label,r("comment").placeholder=e.modifyField?.placeholder||"\u586B\u5199\u4FEE\u6539\u610F\u89C1",r("submit").textContent=e.submit?.label||"\u63D0\u4EA4",r("footer").textContent=e.footer||"",r("options").disabled=!s,r("comment").value="",w.forEach(n=>n.checked=!1),p=o,i(d||(s?"\u8868\u5355\u5DF2\u51C6\u5907\uFF0C\u8BF7\u9009\u62E9 A \u6216 B\u3002":"\u8868\u5355\u5DF2\u51C6\u5907\uFF0C\u6B63\u5728\u7B49\u5F85\u5BBF\u4E3B\u80FD\u529B\u786E\u8BA4\u3002"),d?"error":s?"ok":"info"),m()}function v(t){if(t.source!==window.parent)return;let e=t.data;if(!(!e||e.jsonrpc!=="2.0"||typeof e!="object")){if(Object.hasOwn(e,"id")&&!Object.hasOwn(e,"method")){let o=u.get(e.id);if(!o)return;u.delete(e.id),clearTimeout(o.timer),e.error?o.reject(Error("MCP_APP_HOST_REJECTED")):o.resolve(e.result);return}if(e.method==="ui/notifications/tool-result"){_=e.params;try{C(b(_))}catch{i("Form prepare \u56DE\u6267\u65E0\u6548\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error")}}e.method==="ui/resource-teardown"&&e.id!==void 0&&E({id:e.id,result:{}})}}var R=0,A=0;function I(){if(!s)return;let t=Math.ceil(document.documentElement.scrollHeight),e=Math.ceil(document.documentElement.clientWidth);t===R&&e===A||(R=t,A=e,g("ui/notifications/size-changed",{width:e,height:t}))}async function x(){if(window.parent===window){i("\u672A\u5728 ChatGPT MCP App iframe \u4E2D\u8FD0\u884C\uFF0C\u7981\u6B62\u63D0\u4EA4\u3002","error");return}let t=++P,e=new Promise((o,n)=>{let c=setTimeout(()=>{u.delete(t),n(Error("FORM_APP_INIT_TIMEOUT"))},12e3);u.set(t,{resolve:o,reject:n,timer:c}),E({id:t,method:"ui/initialize",params:{appInfo:{name:"Chat Loop Review",version:"1.0.1"},appCapabilities:{},protocolVersion:"2026-01-26"}})});try{let o=await e;if(!o?.protocolVersion||!o.hostInfo||!o.hostCapabilities)throw Error("FORM_APP_INIT_INVALID");if(!o.hostCapabilities.serverTools||!o.hostCapabilities.message?.text){d="\u5F53\u524D\u5BBF\u4E3B\u7F3A\u5C11 serverTools \u6216 message.text \u80FD\u529B\uFF0C\u8868\u5355\u4E0D\u53EF\u63D0\u4EA4\u3002",i(d,"error"),m();return}s=!0,d=null,g("ui/notifications/initialized",{}),I(),_&&C(b(_)),typeof ResizeObserver=="function"&&new ResizeObserver(I).observe(document.documentElement)}catch{d="MCP App \u521D\u59CB\u5316\u5931\u8D25\uFF0C\u8BF7\u6838\u67E5\u5BBF\u4E3B\u8FDE\u63A5\u4E0E\u534F\u8BAE\u80FD\u529B\u3002",i(d,"error"),s=!1,m()}}async function F(){if(!s||p||!l)return;let t=M(),e=r("comment").value.trim();if(!["A","B"].includes(t)||t==="B"&&!e)return;p=!0,m();let{formId:o,traceRef:n}=l,c={formId:o,traceRef:n,choice:t,...t==="B"?{comment:e}:{}};i("\u6B63\u5728\u63D0\u4EA4\u8868\u5355\u2026");let a;try{a=b(await O("tools/call",{name:"chat_loop_form__submit",arguments:c}))}catch(f){let h=typeof f?.message=="string"&&/^[A-Z][A-Z0-9_]{1,95}$/.test(f.message)?f.message:"FORM_APP_REPLY_UNKNOWN";i(h==="FORM_APP_REPLY_UNKNOWN"||h==="FORM_SUBMISSION_CLAIM_UNKNOWN"?"Submit \u7ED3\u679C\u672A\u77E5\uFF0C\u5DF2\u9501\u5B9A\uFF0C\u7981\u6B62\u91CD\u590D\u63D0\u4EA4\uFF1B\u8BF7\u67E5\u539F\u8BF7\u6C42\u56DE\u6267\u3002":h==="FORM_ALREADY_SUBMITTED"?"\u8BE5\u8868\u5355\u5DF2\u63D0\u4EA4\u8FC7\uFF0C\u7981\u6B62\u91CD\u590D\u53D1\u9001\uFF1B\u8BF7\u6838\u67E5\u539F\u6D88\u606F\u3002":"Submit \u660E\u786E\u5931\u8D25\uFF08"+h+"\uFF09\uFF0C\u7528\u6237\u6D88\u606F\u672A\u53D1\u9001\u3002","error");return}if(a.status!=="FORM_SUBMITTED"||a.formId!==o||a.traceRef!==n||a.choice!==t){i("Submit \u8FD4\u56DE\u7684\u4FE1\u606F\u4E0E\u5F53\u524D\u8868\u5355\u4E0D\u5339\u914D\uFF0C\u7528\u6237\u6D88\u606F\u672A\u53D1\u9001\u3002","error");return}let y="\u3010Chat Loop Form\u3011formId="+o+"\uFF5C"+(t==="A"?"A \u9009\u62E9":"B \u9009\u62E9\uFF1A"+e)+"\u3002";i("\u5355\u6B21\u63D0\u4EA4\u5DF2\u9501\u5B9A\uFF0C\u6B63\u5728\u7533\u8BF7\u5F53\u524D Chat \u7528\u6237\u6D88\u606F\u2026");try{let f=await O("ui/message",{role:"user",content:[{type:"text",text:y}]});i(f?.isError?"\u5BBF\u4E3B\u672A\u63A5\u53D7\u8868\u5355\u7ED3\u679C\u6D88\u606F\u3002":"\u5BBF\u4E3B\u5DF2\u63A5\u53D7\u7528\u6237\u6D88\u606F\u8BF7\u6C42\uFF1B\u5E73\u53F0\u6D88\u606F\u8EAB\u4EFD\u4ECD\u9700\u72EC\u7ACB\u6838\u9A8C\u3002",f?.isError?"error":"ok")}catch{i("\u7528\u6237\u6D88\u606F\u53D1\u9001\u72B6\u6001\u672A\u77E5\uFF0C\u5DF2\u9501\u5B9A\uFF0C\u7981\u6B62\u91CD\u8BD5\uFF1B\u8BF7\u6838\u67E5\u539F\u6D88\u606F\u3002","error")}}window.addEventListener("message",v);w.forEach(t=>t.addEventListener("change",m));r("comment").addEventListener("input",m);r("submit").addEventListener("click",F);x();})();
44
44
  </script>
45
45
  </body>
46
46
  </html>