@tomflow/chatloop-tools 0.9.24 → 0.9.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.mjs +13 -5
- package/lib/control.mjs +31 -0
- package/lib/release-owner-preflight.mjs +3 -3
- package/lib/release-upgrade.mjs +232 -0
- package/lib/release.mjs +8 -91
- package/lib/trace-gateway.mjs +6 -5
- package/lib/trace-observation.mjs +1 -1
- package/package.json +1 -1
- package/providers/form.mjs +27 -9
- package/ui/form/review-app.js +15 -1
- package/ui/form/review.html +1 -1
package/index.mjs
CHANGED
|
@@ -74,7 +74,7 @@ async function runtime(){
|
|
|
74
74
|
if(!runtimePromise)runtimePromise=(async()=>{
|
|
75
75
|
const [control,fixture,mcpChild,tunnelAdapter,adapters,tunnel,tunnelAuth,
|
|
76
76
|
contextAuth,contextRun,extensionContract,extensionCliContract,
|
|
77
|
-
extensionProxy,contextGateway,releasePreflight,release,
|
|
77
|
+
extensionProxy,contextGateway,releasePreflight,release,releaseUpgrade,
|
|
78
78
|
traceGateway,traceObservation,
|
|
79
79
|
terminalPolicy,gateway,supervisor]=await Promise.all([
|
|
80
80
|
import('./lib/control.mjs'),
|
|
@@ -92,6 +92,7 @@ async function runtime(){
|
|
|
92
92
|
import('./lib/context-gateway.mjs'),
|
|
93
93
|
import('./lib/release-owner-preflight.mjs'),
|
|
94
94
|
import('./lib/release.mjs'),
|
|
95
|
+
import('./lib/release-upgrade.mjs'),
|
|
95
96
|
import('./lib/trace-gateway.mjs'),
|
|
96
97
|
import('./lib/trace-observation.mjs'),
|
|
97
98
|
import('./lib/terminal-app-policy.mjs'),
|
|
@@ -153,9 +154,16 @@ async function runtime(){
|
|
|
153
154
|
acceptExtensionCliReceipt:extensionCliContract.acceptExtensionCliReceipt,
|
|
154
155
|
extensionTools:extensionContract.extensionTools,
|
|
155
156
|
readApiParent:apiAspect.current});
|
|
156
|
-
release.configureRelease({PACKAGE_VERSION:control.PACKAGE_VERSION
|
|
157
|
+
release.configureRelease({PACKAGE_VERSION:control.PACKAGE_VERSION});
|
|
158
|
+
releaseUpgrade.configureReleaseUpgrade({
|
|
159
|
+
...release.releaseUpgradeDependencies(),CONTRACT:control.CONTRACT,
|
|
160
|
+
lifecycleDeadlineMs:control.lifecycleDeadlineMs,
|
|
161
|
+
talkForUpgrade:control.talkForUpgrade,
|
|
157
162
|
activeDesktopCommands:releasePreflight.activeDesktopCommands,
|
|
158
|
-
awaitStopped:releasePreflight.awaitStopped
|
|
163
|
+
awaitStopped:releasePreflight.awaitStopped
|
|
164
|
+
});
|
|
165
|
+
const releaseApi=Object.freeze({...release,
|
|
166
|
+
upgradeRuntime:releaseUpgrade.upgradeRuntime});
|
|
159
167
|
const traceTalk=async request=>{
|
|
160
168
|
const result=await control.talk(request);
|
|
161
169
|
if(request?.action!=='__trace_health'||!result?.traceHealth)return result;
|
|
@@ -177,7 +185,7 @@ async function runtime(){
|
|
|
177
185
|
// One statically generated provider composition, shared by tools/list and
|
|
178
186
|
// tools/call. Adding an independent provider never edits this Gateway.
|
|
179
187
|
const coreToolRouter=createMcpToolRouter(providerDefinitions,{
|
|
180
|
-
control,release,terminal:terminalPolicy,context:contextGateway,
|
|
188
|
+
control,release:releaseApi,terminal:terminalPolicy,context:contextGateway,
|
|
181
189
|
form:{
|
|
182
190
|
observe:async payload=>{
|
|
183
191
|
const parent=apiAspect.current();
|
|
@@ -269,7 +277,7 @@ async function runtime(){
|
|
|
269
277
|
loadContextControlSecret:contextAuth.loadContextControlSecret,
|
|
270
278
|
handleContextControl:contextRun.handleContextControl
|
|
271
279
|
});
|
|
272
|
-
return Object.freeze({control,tunnel,tunnelAuth,release,gateway,supervisor});
|
|
280
|
+
return Object.freeze({control,tunnel,tunnelAuth,release:releaseApi,gateway,supervisor});
|
|
273
281
|
})();
|
|
274
282
|
return runtimePromise;
|
|
275
283
|
}
|
package/lib/control.mjs
CHANGED
|
@@ -97,6 +97,37 @@ export async function talk(request,timeout=12000){
|
|
|
97
97
|
verifyOwner(hello);
|
|
98
98
|
return send(request,timeout);
|
|
99
99
|
}
|
|
100
|
+
|
|
101
|
+
// Upgrade is the only lifecycle path allowed to speak to the currently active
|
|
102
|
+
// Supervisor across package versions. It still verifies the protocol, enabled
|
|
103
|
+
// tool registry and exact PID/nonce/version owner tuple from the private lock;
|
|
104
|
+
// it deliberately does not require the old Supervisor package version to
|
|
105
|
+
// equal the candidate CLI version.
|
|
106
|
+
export async function talkForUpgrade(request,timeout=12000){
|
|
107
|
+
const hello=await send({action:'__ping'},1200);
|
|
108
|
+
if(hello.contract!==CONTRACT||
|
|
109
|
+
hello.registrySignature!==registry().map(t=>t.id+':'+t.enabled).join('|')||
|
|
110
|
+
typeof hello.version!=='string')
|
|
111
|
+
throw Object.assign(new Error('Upgrade control contract mismatch'),{
|
|
112
|
+
code:'INCOMPATIBLE_VERSION'
|
|
113
|
+
});
|
|
114
|
+
const p=paths();
|
|
115
|
+
const d=lstatSync(p.dir),l=lstatSync(p.lock),s=lstatSync(p.socket);
|
|
116
|
+
if(!d.isDirectory()||d.isSymbolicLink()||(d.mode&0o077)||
|
|
117
|
+
!l.isFile()||l.isSymbolicLink()||(l.mode&0o077)||
|
|
118
|
+
!s.isSocket()||(s.mode&0o077)||
|
|
119
|
+
(process.getuid&&[d,l,s].some(f=>f.uid!==process.getuid())))
|
|
120
|
+
throw Object.assign(new Error('Untrusted upgrade IPC ownership'),{
|
|
121
|
+
code:'INSECURE_STATE_DIR'
|
|
122
|
+
});
|
|
123
|
+
const owner=JSON.parse(readFileSync(p.lock,'utf8'));
|
|
124
|
+
if(owner.pid!==hello.managerPid||owner.nonce!==hello.ownerNonce||
|
|
125
|
+
owner.version!==hello.version)
|
|
126
|
+
throw Object.assign(new Error('Upgrade owner lock and IPC mismatch'),{
|
|
127
|
+
code:'MANAGER_UNAVAILABLE'
|
|
128
|
+
});
|
|
129
|
+
return send(request,timeout);
|
|
130
|
+
}
|
|
100
131
|
export async function recoverStaleLock() {
|
|
101
132
|
const p=paths();
|
|
102
133
|
if (!existsSync(p.lock)) return;
|
|
@@ -31,10 +31,10 @@ export function activeDesktopCommands(oldStatus){
|
|
|
31
31
|
.map(x=>Number(x[0]));
|
|
32
32
|
}
|
|
33
33
|
export async function awaitStopped(entry,opts={}){
|
|
34
|
-
// A completed stop
|
|
35
|
-
const
|
|
34
|
+
// A completed stop requires both the lock and owned control socket to vanish.
|
|
35
|
+
const lock=opts.lockPath,socket=opts.socketPath;
|
|
36
36
|
for(let i=0;i<80;i++){
|
|
37
|
-
if(!existsSync(
|
|
37
|
+
if(!existsSync(lock)&&(!socket||!existsSync(socket)))return;
|
|
38
38
|
await delay(100);
|
|
39
39
|
}
|
|
40
40
|
throw Object.assign(Error('OWNER_STILL_RUNNING'),{code:'OWNER_STILL_RUNNING'});
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
// Supervisor cutover lifecycle. All package/runtime helpers arrive as
|
|
2
|
+
// explicit ports from the SDK composition root; this module owns no state.
|
|
3
|
+
import {randomUUID} from 'node:crypto';
|
|
4
|
+
import {existsSync,mkdirSync,openSync,closeSync,unlinkSync,lstatSync,readFileSync,writeFileSync} from 'node:fs';
|
|
5
|
+
import {join,dirname} from 'node:path';
|
|
6
|
+
let PACKAGE_VERSION,CONTRACT,lifecycleDeadlineMs,talkForUpgrade,
|
|
7
|
+
activeDesktopCommands,awaitStopped,checkedUpgradeBase,upgradeLayout,
|
|
8
|
+
run,cli,runtimeLaunchEnv,verifyPreparedRelease,atomicWrite,readJson,
|
|
9
|
+
quote,freshResult,name;
|
|
10
|
+
let connected=false;
|
|
11
|
+
export function configureReleaseUpgrade(ports){
|
|
12
|
+
if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
13
|
+
const required=['PACKAGE_VERSION','CONTRACT','lifecycleDeadlineMs',
|
|
14
|
+
'talkForUpgrade','activeDesktopCommands','awaitStopped','checkedUpgradeBase',
|
|
15
|
+
'upgradeLayout','run','cli','runtimeLaunchEnv','verifyPreparedRelease',
|
|
16
|
+
'atomicWrite','readJson','quote','freshResult','name'];
|
|
17
|
+
for(const key of required)
|
|
18
|
+
if(ports?.[key]===undefined)throw Error('TOOLS_PORT_MISSING:'+key);
|
|
19
|
+
({PACKAGE_VERSION,CONTRACT,lifecycleDeadlineMs,talkForUpgrade,
|
|
20
|
+
activeDesktopCommands,awaitStopped,checkedUpgradeBase,upgradeLayout,
|
|
21
|
+
run,cli,runtimeLaunchEnv,verifyPreparedRelease,atomicWrite,readJson,
|
|
22
|
+
quote,freshResult,name}=ports);
|
|
23
|
+
connected=true;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Preserve the exact pre-cutover runtime pointer and Tunnel profile before
|
|
27
|
+
// stopping the current owner. Backups are private and never logged verbatim.
|
|
28
|
+
function backupConfiguration(p){
|
|
29
|
+
const root=join(p.base,'backups');
|
|
30
|
+
mkdirSync(root,{recursive:true,mode:0o700});
|
|
31
|
+
const rootStat=lstatSync(root);
|
|
32
|
+
if(!rootStat.isDirectory()||rootStat.isSymbolicLink()||(rootStat.mode&0o077)
|
|
33
|
+
||(process.getuid&&rootStat.uid!==process.getuid()))
|
|
34
|
+
throw Object.assign(Error('UPGRADE_BACKUP_DIRECTORY_UNTRUSTED'),{
|
|
35
|
+
code:'UPGRADE_BACKUP_DIRECTORY_UNTRUSTED'});
|
|
36
|
+
const directory=join(root,'upgrade-'+p.version+'-'+randomUUID());
|
|
37
|
+
mkdirSync(directory,{mode:0o700});
|
|
38
|
+
const copied=[];
|
|
39
|
+
const copy=(source,target,required)=>{
|
|
40
|
+
if(!existsSync(source)){
|
|
41
|
+
if(required)throw Object.assign(Error('UPGRADE_BACKUP_SOURCE_MISSING'),{
|
|
42
|
+
code:'UPGRADE_BACKUP_SOURCE_MISSING'});
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const stat=lstatSync(source);
|
|
46
|
+
if(!stat.isFile()||stat.isSymbolicLink()
|
|
47
|
+
||(process.getuid&&stat.uid!==process.getuid()))
|
|
48
|
+
throw Object.assign(Error('UPGRADE_BACKUP_SOURCE_UNTRUSTED'),{
|
|
49
|
+
code:'UPGRADE_BACKUP_SOURCE_UNTRUSTED'});
|
|
50
|
+
writeFileSync(join(directory,target),readFileSync(source),
|
|
51
|
+
{mode:0o600,flag:'wx'});
|
|
52
|
+
copied.push(target);
|
|
53
|
+
};
|
|
54
|
+
copy(p.current,'runtime.json',false);
|
|
55
|
+
copy(p.profile,'tunnel-profile.yaml',true);
|
|
56
|
+
writeFileSync(join(directory,'backup.json'),JSON.stringify({
|
|
57
|
+
version:p.version,files:copied
|
|
58
|
+
},null,2)+'\n',{mode:0o600,flag:'wx'});
|
|
59
|
+
return directory;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export async function upgradeRuntime(options={}){
|
|
63
|
+
if(options.args?.length)return freshResult('FAILED',{code:'INVALID_ARGUMENT'});
|
|
64
|
+
const base=checkedUpgradeBase(options);
|
|
65
|
+
if(!base)return freshResult('BLOCKED',{code:'RUNTIME_HOME_MISMATCH'});
|
|
66
|
+
const p=upgradeLayout(base,options.version||PACKAGE_VERSION);
|
|
67
|
+
mkdirSync(p.base,{recursive:true,mode:0o700});
|
|
68
|
+
mkdirSync(p.releases,{recursive:true,mode:0o700});
|
|
69
|
+
let fd;
|
|
70
|
+
try{fd=openSync(p.lock,'wx',0o600);}
|
|
71
|
+
catch{return freshResult('BLOCKED',{code:'UPGRADE_IN_PROGRESS'});}
|
|
72
|
+
const runner=options.run||run;
|
|
73
|
+
let oldEntry,oldStatus,runtime,phase='preflight',oldWasStopped=false,verified=null,backupDir=null;
|
|
74
|
+
try{
|
|
75
|
+
if(!existsSync(p.profile))return freshResult('BLOCKED',{code:'PROFILE_NOT_FOUND'});
|
|
76
|
+
const profile=readJson(p.profile);
|
|
77
|
+
if(!profile?.mcp?.commands?.some(x=>x.channel==='main'))
|
|
78
|
+
return freshResult('BLOCKED',{code:'PROFILE_MCP_NOT_FOUND'});
|
|
79
|
+
runtime=existsSync(p.current)?readJson(p.current):null;
|
|
80
|
+
oldEntry=runtime?.entry||p.legacy;
|
|
81
|
+
const currentVersion=runtime?.version||
|
|
82
|
+
(existsSync(oldEntry)?readJson(join(dirname(dirname(oldEntry)),'package.json')).version:null);
|
|
83
|
+
const pendingTarget=runtime?.status==='STOPPED'&&
|
|
84
|
+
runtime.targetVersion===p.version&&runtime.targetEntry===p.entry;
|
|
85
|
+
if(!pendingTarget&&!existsSync(oldEntry))
|
|
86
|
+
return freshResult('BLOCKED',{code:'PREVIOUS_RUNTIME_NOT_FOUND'});
|
|
87
|
+
if(currentVersion===p.version&&runtime?.entry===p.entry&&runtime?.status==='ACTIVE'){
|
|
88
|
+
const active=await cli(p.entry,'status');
|
|
89
|
+
return active.status==='OK'?freshResult('OK',{outcome:'ALREADY_ACTIVE'}):
|
|
90
|
+
freshResult('BLOCKED',{code:'ACTIVE_RUNTIME_NOT_HEALTHY',activeStatus:active});
|
|
91
|
+
}
|
|
92
|
+
// Prepare a new immutable install without touching the running service.
|
|
93
|
+
phase='prepare';
|
|
94
|
+
if(options.requirePrepared&&!/^[a-f0-9]{64}$/.test(options.expectedArtifactSha256||''))
|
|
95
|
+
return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_PIN_REQUIRED'});
|
|
96
|
+
if(options.requirePrepared&&!existsSync(p.entry))
|
|
97
|
+
return freshResult('BLOCKED',{code:'PREPARED_RELEASE_NOT_FOUND'});
|
|
98
|
+
if(!existsSync(p.entry)){
|
|
99
|
+
await runner(process.platform==='win32'?'npm.cmd':'npm',
|
|
100
|
+
['install','--prefix',p.stage,'--save-exact','--ignore-scripts',name+'@'+p.version],
|
|
101
|
+
{env:process.env});
|
|
102
|
+
}
|
|
103
|
+
if(!existsSync(p.entry)||readJson(join(dirname(dirname(p.entry)),'package.json')).version!==p.version)
|
|
104
|
+
return freshResult('BLOCKED',{code:'STAGE_VERSION_MISMATCH'});
|
|
105
|
+
if(options.requirePrepared){
|
|
106
|
+
const evidence=verifyPreparedRelease(p.base,p.version);
|
|
107
|
+
if(!evidence.ok)return freshResult('BLOCKED',{code:evidence.code});
|
|
108
|
+
if(evidence.artifactSha256!==options.expectedArtifactSha256)
|
|
109
|
+
return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_PIN_MISMATCH'});
|
|
110
|
+
}
|
|
111
|
+
const ready=await cli(p.entry,'doctor');
|
|
112
|
+
if(ready.status!=='LOCAL_READY')return freshResult('BLOCKED',{code:'STAGE_DOCTOR_FAILED'});
|
|
113
|
+
if(options.requirePrepared){
|
|
114
|
+
const tunnel=await cli(p.entry,['tunnel','doctor']);
|
|
115
|
+
if(tunnel.status!=='BUNDLED_READY'||tunnel.verified!==true)
|
|
116
|
+
return freshResult('BLOCKED',{code:'STAGE_TUNNEL_NOT_READY'});
|
|
117
|
+
}
|
|
118
|
+
// Only the version-neutral, lock/nonce-verified control contract may stop
|
|
119
|
+
// the current Supervisor. Never execute the superseded runtime CLI.
|
|
120
|
+
const managerLockPath=join(p.base,'local-tools','manager.lock');
|
|
121
|
+
const controlSocketPath=join(p.base,'local-tools','control.sock');
|
|
122
|
+
if(pendingTarget){
|
|
123
|
+
// The candidate may have started before a prior readiness failure. Its
|
|
124
|
+
// own versioned status below decides whether to resume or remain blocked.
|
|
125
|
+
backupDir=runtime.backupDir||backupConfiguration(p);
|
|
126
|
+
oldWasStopped=true;
|
|
127
|
+
}else if(existsSync(managerLockPath)||existsSync(controlSocketPath)){
|
|
128
|
+
phase='check-owner';
|
|
129
|
+
const request=action=>({contract:CONTRACT,requestId:randomUUID(),
|
|
130
|
+
action,scope:'all',deadlineMs:lifecycleDeadlineMs(action)});
|
|
131
|
+
const control=options.talkForUpgrade||talkForUpgrade;
|
|
132
|
+
oldStatus=await control(request('status'),lifecycleDeadlineMs('status')+2000);
|
|
133
|
+
if(oldStatus.status!=='OK'||oldStatus.results?.some(r=>
|
|
134
|
+
r.after!=='RUNNING'&&r.after!=='STOPPED'&&r.after!=='DISABLED'))
|
|
135
|
+
return freshResult('BLOCKED',{code:'OWNER_NOT_QUIESCENT',
|
|
136
|
+
previousStatus:oldStatus.status,previousOwner:oldStatus});
|
|
137
|
+
const active=options.inspectActiveCommands?
|
|
138
|
+
options.inspectActiveCommands(oldStatus):activeDesktopCommands(oldStatus);
|
|
139
|
+
if(active.length)
|
|
140
|
+
return freshResult('BLOCKED',{code:'ACTIVE_TOOL_COMMANDS',activeCount:active.length});
|
|
141
|
+
phase='backup-config';
|
|
142
|
+
backupDir=backupConfiguration(p);
|
|
143
|
+
phase='stop-old';
|
|
144
|
+
const stopped=await control(request('stop'),lifecycleDeadlineMs('stop')+2000);
|
|
145
|
+
if(stopped.status!=='OK')
|
|
146
|
+
return freshResult('BLOCKED',{code:'STOP_UNCONFIRMED',stopReceipt:stopped,backupDir});
|
|
147
|
+
phase='verify-stopped';
|
|
148
|
+
await awaitStopped(oldEntry,{lockPath:managerLockPath,socketPath:controlSocketPath});
|
|
149
|
+
oldWasStopped=true;
|
|
150
|
+
}else{
|
|
151
|
+
// Absence of both lock and socket is a confirmed no-owner state.
|
|
152
|
+
phase='backup-config';
|
|
153
|
+
backupDir=backupConfiguration(p);
|
|
154
|
+
oldWasStopped=true;
|
|
155
|
+
}
|
|
156
|
+
if(oldWasStopped&&runtime){
|
|
157
|
+
runtime={...runtime,status:'STOPPED',targetVersion:p.version,
|
|
158
|
+
targetEntry:p.entry,...(backupDir?{backupDir}:{})};
|
|
159
|
+
atomicWrite(p.current,JSON.stringify(runtime,null,2)+'\n');
|
|
160
|
+
}
|
|
161
|
+
phase='configure-new';
|
|
162
|
+
const main=profile.mcp.commands.find(x=>x.channel==='main');
|
|
163
|
+
main.command=quote(process.execPath)+' '+quote(p.entry)+' mcp';
|
|
164
|
+
atomicWrite(p.profile,JSON.stringify(profile,null,2)+'\n');
|
|
165
|
+
phase='inspect-candidate';
|
|
166
|
+
const existing=await cli(p.entry,'status');
|
|
167
|
+
const enabled=existing.results?.filter(x=>x.enabled)||[];
|
|
168
|
+
const candidateRunning=existing.status==='OK'&&enabled.length>0&&
|
|
169
|
+
enabled.every(x=>x.after==='RUNNING');
|
|
170
|
+
const candidateStopped=existing.status==='OK'&&enabled.length>0&&
|
|
171
|
+
enabled.every(x=>x.after==='STOPPED');
|
|
172
|
+
if(candidateRunning)verified=existing;
|
|
173
|
+
else if(!candidateStopped)
|
|
174
|
+
throw Object.assign(Error('CANDIDATE_STATE_UNVERIFIED'),{
|
|
175
|
+
code:'CANDIDATE_STATE_UNVERIFIED',candidateStatus:existing
|
|
176
|
+
});
|
|
177
|
+
if(!verified){
|
|
178
|
+
phase='start-new';
|
|
179
|
+
const started=await cli(p.entry,'start',{
|
|
180
|
+
env:{...runtimeLaunchEnv(),CHAT_LOOP_SKIP_UPGRADE:'1'}
|
|
181
|
+
});
|
|
182
|
+
if(!['OK','STARTING'].includes(started.status))
|
|
183
|
+
throw Object.assign(Error('NEW_RUNTIME_UNHEALTHY'),{
|
|
184
|
+
code:'NEW_RUNTIME_UNHEALTHY',startupResult:started
|
|
185
|
+
});
|
|
186
|
+
// A successful start acknowledgement is not readiness. Wait for the
|
|
187
|
+
// candidate Supervisor and every enabled child to become observable.
|
|
188
|
+
phase='verify-new';
|
|
189
|
+
for(let attempt=0;attempt<30;attempt++){
|
|
190
|
+
const status=await cli(p.entry,'status');
|
|
191
|
+
const running=status.results?.filter(x=>x.enabled)||[];
|
|
192
|
+
if(status.status==='OK'&&running.length>0&&
|
|
193
|
+
running.every(x=>x.after==='RUNNING')){
|
|
194
|
+
verified=status;break;
|
|
195
|
+
}
|
|
196
|
+
await new Promise(resolve=>setTimeout(resolve,500));
|
|
197
|
+
}
|
|
198
|
+
if(!verified)
|
|
199
|
+
throw Object.assign(Error('NEW_RUNTIME_HEALTHCHECK_TIMEOUT'),{
|
|
200
|
+
code:'NEW_RUNTIME_HEALTHCHECK_TIMEOUT'
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
phase='verify-tunnel';
|
|
204
|
+
const tunnel=await cli(p.entry,['tunnel','doctor']);
|
|
205
|
+
if(tunnel.status!=='BUNDLED_READY'||tunnel.verified!==true)
|
|
206
|
+
throw Object.assign(Error('NEW_RUNTIME_TUNNEL_UNHEALTHY'),{
|
|
207
|
+
code:'NEW_RUNTIME_TUNNEL_UNHEALTHY'
|
|
208
|
+
});
|
|
209
|
+
phase='record-new';
|
|
210
|
+
atomicWrite(p.current,JSON.stringify({version:p.version,entry:p.entry,
|
|
211
|
+
status:'ACTIVE'},null,2)+'\n');
|
|
212
|
+
return freshResult('OK',{outcome:'ACTIVATED',managerPid:verified.managerPid,
|
|
213
|
+
healthyTools:verified.results.filter(x=>x.enabled).map(x=>x.toolId),backupDir});
|
|
214
|
+
}catch(e){
|
|
215
|
+
// Never restore or launch a superseded runtime after a failed cutover.
|
|
216
|
+
if(oldWasStopped&&runtime){
|
|
217
|
+
runtime={...runtime,status:'STOPPED',targetVersion:p.version,
|
|
218
|
+
targetEntry:p.entry,lastFailure:{phase,code:e.code||'UPGRADE_FAILED'}};
|
|
219
|
+
try{atomicWrite(p.current,JSON.stringify(runtime,null,2)+'\n');}
|
|
220
|
+
catch{return freshResult('BLOCKED',{code:e.code||'UPGRADE_FAILED',phase,
|
|
221
|
+
runtimePointer:'WRITE_FAILED'});}
|
|
222
|
+
}
|
|
223
|
+
return freshResult('BLOCKED',{code:e.code||'UPGRADE_FAILED',phase,
|
|
224
|
+
...(backupDir?{backupDir}:{}),
|
|
225
|
+
...(e.startupResult?{startupResult:e.startupResult}:{}),
|
|
226
|
+
...(e.candidateStatus?{candidateStatus:e.candidateStatus}:{}),
|
|
227
|
+
...(e.tunnelStatus?{tunnelStatus:e.tunnelStatus}:{})});
|
|
228
|
+
}finally{
|
|
229
|
+
if(fd!==undefined)closeSync(fd);
|
|
230
|
+
try{unlinkSync(p.lock);}catch{}
|
|
231
|
+
}
|
|
232
|
+
}
|
package/lib/release.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Owner-verified
|
|
1
|
+
// Owner-verified, version-neutral cutover; failed candidates never restart superseded runtimes.
|
|
2
2
|
import {spawn} from 'node:child_process';
|
|
3
3
|
import {randomUUID,createHash} from 'node:crypto';
|
|
4
4
|
import {existsSync,readFileSync,readdirSync,writeFileSync,openSync,closeSync,unlinkSync,mkdirSync,renameSync,lstatSync,rmSync} from 'node:fs';
|
|
@@ -6,13 +6,12 @@ import {homedir,userInfo} from 'node:os';
|
|
|
6
6
|
import {join,dirname,delimiter} from 'node:path';
|
|
7
7
|
// All internal dependencies are supplied as API contracts by index.mjs.
|
|
8
8
|
// Private modules never import or resolve another private implementation.
|
|
9
|
-
let PACKAGE_VERSION
|
|
9
|
+
let PACKAGE_VERSION;
|
|
10
10
|
let connected=false;
|
|
11
11
|
export function configureRelease(ports){
|
|
12
12
|
if(connected)throw Error('TOOLS_MODULE_ALREADY_COMPOSED');
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
({PACKAGE_VERSION, activeDesktopCommands, awaitStopped}=ports);
|
|
13
|
+
if(ports?.PACKAGE_VERSION===undefined)throw Error('TOOLS_PORT_MISSING:PACKAGE_VERSION');
|
|
14
|
+
({PACKAGE_VERSION}=ports);
|
|
16
15
|
connected=true;
|
|
17
16
|
}
|
|
18
17
|
|
|
@@ -302,90 +301,8 @@ export function verifyPreparedRelease(base,version=PACKAGE_VERSION){
|
|
|
302
301
|
}catch{return {ok:false,code:'PREPARED_RELEASE_UNTRUSTED'}}
|
|
303
302
|
}
|
|
304
303
|
|
|
305
|
-
export
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
const p=upgradeLayout(base,options.version||PACKAGE_VERSION);
|
|
310
|
-
mkdirSync(p.base,{recursive:true,mode:0o700});
|
|
311
|
-
mkdirSync(p.releases,{recursive:true,mode:0o700});
|
|
312
|
-
let fd;
|
|
313
|
-
try{fd=openSync(p.lock,'wx',0o600);}
|
|
314
|
-
catch{return freshResult('BLOCKED',{code:'UPGRADE_IN_PROGRESS'});}
|
|
315
|
-
const runner=options.run||run;
|
|
316
|
-
let oldEntry, oldStatus, phase='preflight';
|
|
317
|
-
try{
|
|
318
|
-
if(!existsSync(p.profile))return freshResult('BLOCKED',{code:'PROFILE_NOT_FOUND'});
|
|
319
|
-
const profile=readJson(p.profile);
|
|
320
|
-
if(!profile?.mcp?.commands?.some(x=>x.channel==='main'))
|
|
321
|
-
return freshResult('BLOCKED',{code:'PROFILE_MCP_NOT_FOUND'});
|
|
322
|
-
const runtime=existsSync(p.current)?readJson(p.current):null;
|
|
323
|
-
oldEntry=runtime?.entry||p.legacy;
|
|
324
|
-
if(!existsSync(oldEntry))return freshResult('BLOCKED',{code:'PREVIOUS_RUNTIME_NOT_FOUND'});
|
|
325
|
-
const currentVersion=readJson(join(dirname(dirname(oldEntry)),'package.json')).version;
|
|
326
|
-
if(currentVersion===p.version&&runtime?.entry===p.entry){
|
|
327
|
-
const active=await cli(p.entry,'status');
|
|
328
|
-
return active.status==='OK'?freshResult('OK',{outcome:'ALREADY_ACTIVE'}):
|
|
329
|
-
freshResult('BLOCKED',{code:'ACTIVE_RUNTIME_NOT_HEALTHY'});
|
|
330
|
-
}
|
|
331
|
-
// Prepare a new immutable install without touching the running service.
|
|
332
|
-
phase='prepare';
|
|
333
|
-
if(options.requirePrepared&&!/^[a-f0-9]{64}$/.test(options.expectedArtifactSha256||''))
|
|
334
|
-
return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_PIN_REQUIRED'});
|
|
335
|
-
if(options.requirePrepared&&!existsSync(p.entry))
|
|
336
|
-
return freshResult('BLOCKED',{code:'PREPARED_RELEASE_NOT_FOUND'});
|
|
337
|
-
if(!existsSync(p.entry)){
|
|
338
|
-
await runner(process.platform==='win32'?'npm.cmd':'npm',
|
|
339
|
-
['install','--prefix',p.stage,'--save-exact','--ignore-scripts',name+'@'+p.version],
|
|
340
|
-
{env:process.env});
|
|
341
|
-
}
|
|
342
|
-
if(!existsSync(p.entry)||readJson(join(dirname(dirname(p.entry)),'package.json')).version!==p.version)
|
|
343
|
-
return freshResult('BLOCKED',{code:'STAGE_VERSION_MISMATCH'});
|
|
344
|
-
if(options.requirePrepared){
|
|
345
|
-
const evidence=verifyPreparedRelease(p.base,p.version);
|
|
346
|
-
if(!evidence.ok)return freshResult('BLOCKED',{code:evidence.code});
|
|
347
|
-
if(evidence.artifactSha256!==options.expectedArtifactSha256)
|
|
348
|
-
return freshResult('BLOCKED',{code:'RELEASE_ARTIFACT_PIN_MISMATCH'});
|
|
349
|
-
}
|
|
350
|
-
const ready=await cli(p.entry,'doctor');
|
|
351
|
-
if(ready.status!=='LOCAL_READY')return freshResult('BLOCKED',{code:'STAGE_DOCTOR_FAILED'});
|
|
352
|
-
if(options.requirePrepared){
|
|
353
|
-
const tunnel=await cli(p.entry,['tunnel','doctor']);
|
|
354
|
-
if(tunnel.status!=='BUNDLED_READY'||tunnel.verified!==true)
|
|
355
|
-
return freshResult('BLOCKED',{code:'STAGE_TUNNEL_NOT_READY'});
|
|
356
|
-
}
|
|
357
|
-
// The staged Gateway is prepared independently; Tunnel binds only on activation.
|
|
358
|
-
phase='check-owner';
|
|
359
|
-
oldStatus=await cli(oldEntry,'status');
|
|
360
|
-
if(oldStatus.status!=='OK'||oldStatus.results?.some(r=>r.after!=='RUNNING'&&r.after!=='STOPPED'&&r.after!=='DISABLED'))
|
|
361
|
-
return freshResult('BLOCKED',{code:'OWNER_NOT_QUIESCENT',previousStatus:oldStatus.status});
|
|
362
|
-
const active=options.inspectActiveCommands?
|
|
363
|
-
options.inspectActiveCommands(oldStatus):activeDesktopCommands(oldStatus);
|
|
364
|
-
if(active.length)
|
|
365
|
-
return freshResult('BLOCKED',{code:'ACTIVE_TOOL_COMMANDS',activeCount:active.length});
|
|
366
|
-
phase='stop-old';
|
|
367
|
-
const oldStopped=await cli(oldEntry,'stop');
|
|
368
|
-
if(oldStopped.status!=='OK')return freshResult('BLOCKED',{code:'STOP_UNCONFIRMED'});
|
|
369
|
-
phase='verify-stopped';
|
|
370
|
-
await awaitStopped(oldEntry,{lockPath:join(p.base,'local-tools','manager.lock')});
|
|
371
|
-
phase='configure-new';
|
|
372
|
-
const main=profile.mcp.commands.find(x=>x.channel==='main');
|
|
373
|
-
main.command=quote(process.execPath)+' '+quote(p.entry)+' mcp';
|
|
374
|
-
atomicWrite(p.profile,JSON.stringify(profile,null,2)+'\n');
|
|
375
|
-
phase='start-new';
|
|
376
|
-
const started=await cli(p.entry,'start',{env:{...runtimeLaunchEnv(),CHAT_LOOP_SKIP_UPGRADE:'1'}});
|
|
377
|
-
if(!['OK','STARTING'].includes(started.status))
|
|
378
|
-
throw Object.assign(Error('NEW_RUNTIME_UNHEALTHY'),{code:'NEW_RUNTIME_UNHEALTHY'});
|
|
379
|
-
phase='record-new';
|
|
380
|
-
atomicWrite(p.current,JSON.stringify({version:p.version,entry:p.entry,
|
|
381
|
-
status:started.status==='OK'?'ACTIVE':'STARTING'},null,2)+'\n');
|
|
382
|
-
return freshResult(started.status,{outcome:started.status==='OK'?'ACTIVATED':'STARTING'});
|
|
383
|
-
}catch(e){
|
|
384
|
-
// Fail closed and retain the exact failure site. Never restart an unknown
|
|
385
|
-
// old/new owner or mutate another process as a "recovery" side effect.
|
|
386
|
-
return freshResult('BLOCKED',{code:e.code||'UPGRADE_FAILED',phase});
|
|
387
|
-
}finally{
|
|
388
|
-
if(fd!==undefined)closeSync(fd);
|
|
389
|
-
try{unlinkSync(p.lock);}catch{}
|
|
390
|
-
}
|
|
304
|
+
export function releaseUpgradeDependencies(){
|
|
305
|
+
return {PACKAGE_VERSION,checkedUpgradeBase,upgradeLayout,run,cli,
|
|
306
|
+
runtimeLaunchEnv,verifyPreparedRelease,atomicWrite,readJson,quote,
|
|
307
|
+
freshResult,name};
|
|
391
308
|
}
|
package/lib/trace-gateway.mjs
CHANGED
|
@@ -45,8 +45,8 @@ 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
46
|
const FORM_TRACE_REF=new RegExp(UUID);
|
|
47
47
|
const FORM_ID=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
48
|
-
const FORM_EVENT=/^form\.(?:prepared|submitted)\.(?:soft_observed|failed)$/;
|
|
49
|
-
const FORM_APIS=new Set(['mcp.chat_loop_form__prepare','mcp.chat_loop_form__submit']);
|
|
48
|
+
const FORM_EVENT=/^form\.(?:prepared|rendered|submitted)\.(?:soft_observed|failed)$/;
|
|
49
|
+
const FORM_APIS=new Set(['mcp.chat_loop_form__prepare','mcp.chat_loop_form__render','mcp.chat_loop_form__submit']);
|
|
50
50
|
export const traceStageTool={
|
|
51
51
|
name:'chat_loop_trace_stage',
|
|
52
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.',
|
|
@@ -108,9 +108,10 @@ async function diagnoseFormTrace(args){
|
|
|
108
108
|
const gaps=base.gaps.filter(gap=>gap!=='NO_MATCHING_EVENTS');
|
|
109
109
|
const parentKeys=new Map();
|
|
110
110
|
for(const event of formEvents){
|
|
111
|
-
const apiName=event.event
|
|
112
|
-
|
|
113
|
-
|
|
111
|
+
const apiName=event.event.startsWith('form.prepared.')
|
|
112
|
+
?'mcp.chat_loop_form__prepare'
|
|
113
|
+
:event.event.startsWith('form.rendered.')
|
|
114
|
+
?'mcp.chat_loop_form__render':'mcp.chat_loop_form__submit';
|
|
114
115
|
if(!event.parentSpanId){gaps.push('FORM_API_PARENT_MISSING');continue}
|
|
115
116
|
parentKeys.set(event.traceId+':'+event.parentSpanId,apiName);
|
|
116
117
|
}
|
|
@@ -16,7 +16,7 @@ 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
|
+
const form=/^form\.(prepared|rendered|submitted)\.(soft_observed|failed)$/.test(req?.event||'');
|
|
20
20
|
const contextGrant=process.env.CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS;
|
|
21
21
|
const contextAuthorized=process.env.CHAT_LOOP_CONTEXT_API_ENABLE==='1'
|
|
22
22
|
&&typeof contextGrant==='string'
|
package/package.json
CHANGED
package/providers/form.mjs
CHANGED
|
@@ -19,6 +19,7 @@ const REQUIRED_CARD=['title','description','options','submitLabel'];
|
|
|
19
19
|
const OPTION=['value','label'];
|
|
20
20
|
const TEXT_INPUT=['label','placeholder','showWhen','requiredWhen','maxLength','rows'];
|
|
21
21
|
const PREP=['formId','card'];
|
|
22
|
+
const RENDER=['formId','traceRef'];
|
|
22
23
|
const SUBMIT=['formId','traceRef','selection','input'];
|
|
23
24
|
const optionSchema={type:'object',additionalProperties:false,required:OPTION,
|
|
24
25
|
properties:{
|
|
@@ -65,6 +66,13 @@ const tools=[
|
|
|
65
66
|
input:{type:'string',maxLength:4000}
|
|
66
67
|
}},
|
|
67
68
|
annotations:{readOnlyHint:false},_meta:{ui:{visibility:['model','app']},
|
|
69
|
+
'openai/widgetAccessible':true}},
|
|
70
|
+
{name:'chat_loop_form__render',description:
|
|
71
|
+
'Internal Form App acknowledgement that the caller-defined form was rendered successfully. Records only formId/traceRef correlation; no business state is created.',
|
|
72
|
+
inputSchema:{type:'object',additionalProperties:false,required:RENDER,
|
|
73
|
+
properties:{formId:{type:'string',pattern:FORM_ID.source},
|
|
74
|
+
traceRef:{type:'string',pattern:UUID.source}}},
|
|
75
|
+
annotations:{readOnlyHint:false},_meta:{ui:{visibility:['app']},
|
|
68
76
|
'openai/widgetAccessible':true}}
|
|
69
77
|
];
|
|
70
78
|
function check(args,fields){
|
|
@@ -156,6 +164,13 @@ function validateSubmit(args){
|
|
|
156
164
|
||args.input!==undefined&&(typeof args.input!=='string'||args.input.length>4000))
|
|
157
165
|
throw fail('FORM_SUBMISSION_INVALID');
|
|
158
166
|
}
|
|
167
|
+
function rendered(args){
|
|
168
|
+
check(args,RENDER);
|
|
169
|
+
if(typeof args.formId!=='string'||!FORM_ID.test(args.formId)
|
|
170
|
+
||typeof args.traceRef!=='string'||!UUID.test(args.traceRef))
|
|
171
|
+
throw fail('FORM_RENDER_INVALID');
|
|
172
|
+
return {status:'FORM_RENDERED',formId:args.formId,traceRef:args.traceRef};
|
|
173
|
+
}
|
|
159
174
|
function submit(args){
|
|
160
175
|
validateSubmit(args);
|
|
161
176
|
return {status:'FORM_SUBMITTED',formId:args.formId,traceRef:args.traceRef,
|
|
@@ -182,21 +197,24 @@ export const provider=Object.freeze({
|
|
|
182
197
|
preferredDisplayMode:'inline'}}}]};
|
|
183
198
|
},
|
|
184
199
|
async call(name,args){
|
|
185
|
-
const isPrepare=name===tools[0].name
|
|
186
|
-
|
|
200
|
+
const isPrepare=name===tools[0].name;
|
|
201
|
+
const isSubmit=name===tools[1].name;
|
|
202
|
+
const isRender=name===tools[2].name;
|
|
203
|
+
if(!isPrepare&&!isSubmit&&!isRender)throw fail('UNKNOWN_TOOL');
|
|
187
204
|
const formId=typeof args?.formId==='string'?args.formId:null;
|
|
188
205
|
const traceRef=typeof args?.traceRef==='string'?args.traceRef:null;
|
|
189
206
|
try{
|
|
190
|
-
const result=isPrepare?prepare(args):submit(args);
|
|
207
|
+
const result=isPrepare?prepare(args):isRender?rendered(args):submit(args);
|
|
191
208
|
// Trace is soft and never delays or alters the returned Form data.
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
209
|
+
const event=isPrepare?'form.prepared.soft_observed':
|
|
210
|
+
isRender?'form.rendered.soft_observed':'form.submitted.soft_observed';
|
|
211
|
+
void observeForm(form,event,result.formId,result.traceRef);
|
|
195
212
|
return ok(result);
|
|
196
213
|
}catch(error){
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
214
|
+
const event=isPrepare?'form.prepared.failed':
|
|
215
|
+
isRender?'form.rendered.failed':'form.submitted.failed';
|
|
216
|
+
void observeForm(form,event,error.formId||formId,
|
|
217
|
+
error.traceRef||traceRef,error.code||'FORM_FAILED');
|
|
200
218
|
throw error;
|
|
201
219
|
}
|
|
202
220
|
}
|
package/ui/form/review-app.js
CHANGED
|
@@ -3,7 +3,7 @@ const $=id=>document.getElementById(id);
|
|
|
3
3
|
const idPattern=/^[A-Za-z0-9][A-Za-z0-9_-]{7,79}$/;
|
|
4
4
|
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;
|
|
5
5
|
const requests=new Map();
|
|
6
|
-
let seq=0,connected=false,prepared=null,locked=false,toolResult=null,hostFailure=null;
|
|
6
|
+
let seq=0,connected=false,prepared=null,locked=false,toolResult=null,hostFailure=null,renderReported=null;
|
|
7
7
|
function status(message,state='info'){
|
|
8
8
|
$('status').textContent=message;
|
|
9
9
|
$('status').dataset.state=state;
|
|
@@ -56,6 +56,19 @@ function update(){
|
|
|
56
56
|
||(visible&&inputRequired(option)&&!text);
|
|
57
57
|
resize();
|
|
58
58
|
}
|
|
59
|
+
function reportRendered(value){
|
|
60
|
+
if(!connected||!value)return;
|
|
61
|
+
const key=value.formId+':'+value.traceRef;
|
|
62
|
+
if(renderReported===key)return;
|
|
63
|
+
renderReported=key;
|
|
64
|
+
// Rendering is observed asynchronously; a Trace failure never blocks the UI.
|
|
65
|
+
void call('tools/call',{name:'chat_loop_form__render',arguments:{
|
|
66
|
+
formId:value.formId,traceRef:value.traceRef
|
|
67
|
+
}}).then(decode).then(receipt=>{
|
|
68
|
+
if(receipt.status!=='FORM_RENDERED'||receipt.formId!==value.formId
|
|
69
|
+
||receipt.traceRef!==value.traceRef)throw Error('FORM_RENDER_RECEIPT_INVALID');
|
|
70
|
+
}).catch(()=>{});
|
|
71
|
+
}
|
|
59
72
|
function render(value){
|
|
60
73
|
const view=value?.view,options=view?.options;
|
|
61
74
|
if(!view||view.template!=='chat-loop-form-v1'
|
|
@@ -104,6 +117,7 @@ function render(value){
|
|
|
104
117
|
'表单已准备,正在等待宿主能力确认。'),
|
|
105
118
|
hostFailure?'error':connected?'ok':'info');
|
|
106
119
|
update();
|
|
120
|
+
reportRendered(value);
|
|
107
121
|
}
|
|
108
122
|
function receive(event){
|
|
109
123
|
if(event.source!==window.parent)return;
|
package/ui/form/review.html
CHANGED
|
@@ -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),
|
|
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();})();
|
|
48
48
|
</script>
|
|
49
49
|
</body>
|
|
50
50
|
</html>
|