@josephyulei/summon-foundation 0.1.5 → 0.1.6

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
@@ -1,25 +1,27 @@
1
1
  # summon foundation
2
2
 
3
- 0.1.5 配合 Foundation 0.2.11。选中 Skill 后由程序接续精确确认;`--update --root <安装根> --version <固定版本>`、`--uninstall --root <安装根>` 组织维护步骤。`--resume <同次结果文件>` 仅恢复程序成功后的所选 Skill,不重装或重放批准。
3
+ 0.1.6 单页试用入口与 Foundation 0.2.12 起的运行引擎共同支持同一页面内的目录选择、程序和 Skill 独立确认;旧发行版本不具备本次单页修订。真实安装、新任务发现和主动告知仍需独立验收。
4
4
 
5
- 0.1.5 提供获取期间只读进度页。获取成功后同一页面关联运行程序返回的目录/确认页,仍由 Codex 内置浏览器打开;配合 Foundation 0.2.11 展示本次流程、当前目标和剩余动作。临时服务只随本次任务运行,不是守护进程,不执行未核验归档,也不替本人确认。原操作回执仍可独立只读查询,页断开不改写已核实终态。
5
+ 首次 URL 持续显示本次流程;确认仅转交本次受控子进程的当前计划,不新开manager页。--acquire仍只读获取;--resume仅在用户明确要求后恢复未完成Skill,不重放程序安装。
6
6
 
7
7
  Foundation 的薄获取入口,不包含完整运行包,没有 npm 安装生命周期脚本。
8
8
  只有明确执行才查询/获取;安装和 Skill 注册继续各自需要用户确认。
9
9
 
10
10
  可用性以 npm registry 的实际版本和公共 GitHub Release 为准;本目录或说明存在不是发布回执。只使用本项目已核验的包名,缺包时不换同名来源。
11
11
 
12
+ 确认 registry 中存在本版本及对应不可变 Release 后,在具备安装权限的新 Codex 对话粘贴:
13
+
12
14
  ```text
13
- npx --yes --package @josephyulei/summon-foundation@0.1.5 summon foundation
15
+ npx --yes --package @josephyulei/summon-foundation@0.1.6 summon foundation
14
16
  ```
15
17
 
16
- 0.1.5 入口配合 Foundation 0.2.11 正式发行使用。默认命令实际查询、固定版本、披露缓存、下载并校验,然后保持运行等待安装页目录选择。选择目录后还要亲自确认精确安装计划;不会自动注册 Skill 或接入项目。实际获取仍须通过 registry 与 Release 校验,本文不替代发布证明。
18
+ 旧版退出推荐入口;支持边界见[现行支持策略](https://github.com/y15801172513-lang/foundation/blob/main/docs/install-platform-024.md#现行支持策略)。旧不可变版本不修改,不自动迁移或清除旧安装。
17
19
 
18
20
  Codex 需要打开返回的内置浏览器网址,并分段等待同次操作结果。npm 不能自行操控或唤醒 Codex,对话主动告知不是程序退出码保证;新对话接续仍待真人验收。系统浏览器只是明确告知后的备用,不自动打开。
19
21
 
20
- 0.1.3 的程序收尾:联网前建立同次操作记录,输出阶段、大文件实际字节/总量、尝试次数与最近进展;不能保存早期记录则不开始联网。大文件每次最多 10 分钟,连接 15 秒、低速 60 秒有界停止,仅暂时网络错误可重试一次。失败保留 curl 退出码和脱敏类别,校验失败与网络失败分开。`--status <返回的结果文件>` 只读恢复,不获取、安装或重试;中间记录不证明进程仍在运行。新运行版安装后程序核验稳定入口,启动唯一工作台至就绪便返回结果,不等常驻工作台退出;Codex 打开返回的实际网址并解释结果。旧 0.1.2 不含上述修复。工具返回 running 不是任务完成,运行中的 Codex 应继续观察原句柄;程序无法强制宿主不提前结束,新对话无追问反馈仍待验证。
22
+ 联网前建立操作记录,网络失败保留脱敏类别和退出码;--status只读恢复同次结果,不重试或重放。程序健康核验后结果留在本页,工作台由用户另行打开。工具yield不是任务完成,Codex须继续分段观察;HTML不能唤醒已结束任务。
21
23
 
22
- 显式 `--inspect` 才只查询,不下载运行文件。已有选择时可用 `--prepare --version <固定版本> --destination <绝对目录>`;`--acquire --version <固定版本>` 只准备更新输入,不执行更新。更新使用已安装稳定入口。旧运行版不支持页面选择时拒绝自动采用默认目录。没有 npm 时先从 GitHub 安装说明检查环境,不自动安装全局依赖。
24
+ 显式 --inspect 只查询发行。默认命令先在页面选择目录与Skill意向,再下载核验;最终精确计划仍需本人确认。--prepare传入的目录只是意向;--acquire只准备更新输入。更新/卸载仅使用支持单页的已安装稳定入口,不回退旧页面。
23
25
 
24
26
  需要 macOS arm64、Node.js 22.9+ 与 npm。无 TTY 不会卡在终端提问;目录选择在页面进行,关闭页面不算确认或取消。
25
27
  固定版本准备阶段匿名校验 GitHub 仓库身份、不可变 Release、签名证明、时间戳、源码提交和资产字节,随后使用随包运行时进入现有 Foundation 确认页面。
package/bin/summon.mjs CHANGED
@@ -8,9 +8,11 @@ import {acquireInWorker} from '../lib/acquisition-task.mjs';
8
8
  import {startProgressPage} from '../lib/progress-page.mjs';
9
9
  import {followSelectedSkill} from '../lib/skill-handoff.mjs';
10
10
  import {followMaintenance} from '../lib/maintenance-handoff.mjs';
11
+ import {installedClient} from '../lib/manager-step.mjs';
11
12
  import {resumeSkillHandoff} from '../lib/resume-handoff.mjs';
12
13
  import {parseSummonArgs} from '../lib/cli-options.mjs';
13
14
  import {createOperation,saveOperation,readOperation,runtimeObservation} from '../lib/operation-result.mjs';
15
+ import {createJourneyControl} from '../lib/journey-control.mjs';
14
16
 
15
17
  const help=`summon foundation [--version x.y.z] [--destination /absolute/folder]
16
18
  summon foundation --inspect [--version x.y.z]
@@ -48,24 +50,8 @@ function stageDirectory(){
48
50
  return fs.mkdtempSync(path.join(cache,'acquisition.'));
49
51
  }
50
52
  let operation=null,stage=null,progressPage=null;
53
+ const journeyControl=createJourneyControl(()=>operation,()=>progressPage?.publish());
51
54
  function updateOperation(patch){if(!operation)return;Object.assign(operation,patch,{updatedAt:new Date().toISOString()});const file=saveOperation(operation,stage);if(file)operation.resultFile=file;progressPage?.publish();console.log(JSON.stringify({status:'FOUNDATION_INSTALL_OPERATION',...operation,resultFile:file,recordSaved:!!file}));}
52
- async function openInstalledWorkbench(root,env){
53
- let child;
54
- try{
55
- plainPath(root);const launcher=path.join(root,'bin/foundation-kit');plainPath(launcher);
56
- const stdout=path.join(stage,'workbench.stdout.log'),stderr=path.join(stage,'workbench.stderr.log');
57
- const out=fs.openSync(stdout,'wx',0o600);let err;
58
- try{err=fs.openSync(stderr,'wx',0o600);child=spawn(launcher,['workbench','open','--root',root],{detached:true,stdio:['ignore',out,err],env});}finally{fs.closeSync(out);if(err!==undefined)fs.closeSync(err);}
59
- await new Promise((resolve,reject)=>{child.once('spawn',resolve);child.once('error',reject);});child.unref();
60
- for(let n=0;n<100;n++){
61
- if(child.exitCode!==null)throw Error('工作台进程提前退出');
62
- let ready;try{ready=JSON.parse(fs.readFileSync(stdout,'utf8'));}catch{}
63
- if(ready?.url){const url=new URL(ready.url);if(url.protocol!=='http:'||url.hostname!=='127.0.0.1'||url.username||url.password)throw Error('工作台网址无效');const response=await fetch(url,{signal:AbortSignal.timeout(5000),redirect:'error'});if(!response.ok)throw Error('工作台未就绪');return{state:'ready',url:url.href,pid:child.pid,requiredHostAction:'open-returned-loopback-url-in-codex-browser'};}
64
- await new Promise(r=>setTimeout(r,100));
65
- }
66
- throw Error('工作台启动超时');
67
- }catch{if(child&&child.exitCode===null)child.kill('SIGTERM');return{state:'not-ready',reason:'安装结果保留;工作台未能就绪,可从已安装入口重新打开'};}
68
- }
69
55
  try{
70
56
  const args=parseSummonArgs(process.argv.slice(2));
71
57
  if(args.help){console.log(help);process.exit(0);}
@@ -78,22 +64,31 @@ try{
78
64
  if(args.prepare||args.acquire||maintenance){operation=createOperation();stage=stageDirectory();updateOperation({});if(!saveOperation(operation,stage))fail('无法在已披露的获取目录保存操作记录;尚未联网或安装');}
79
65
  if(args.prepare)console.log('正在准备 Foundation 安装:将查询并固定本次正式版本,说明缓存位置后下载核验。未选目录会在安装页选择;之后仍需本人确认精确计划。请保持当前 Codex 任务等待并打开返回的内置浏览器网址;不会自动改用系统浏览器。');
80
66
  if(args.resume){
67
+ operation=readOperation(args.resume);stage=path.dirname(plainPath(args.resume));
68
+ progressPage=await startProgressPage(()=>operation,{control:journeyControl});
69
+ console.log(JSON.stringify({status:'FOUNDATION_SINGLE_PAGE',url:progressPage.url,operationId:operation.operationId}));
81
70
  const env={...process.env};for(const key of ['NODE_OPTIONS','NODE_PATH','NODE_V8_COVERAGE','NODE_REDIRECT_WARNINGS','NODE_COMPILE_CACHE','NODE_COMPILE_CACHE_PORTABLE','NODE_PRESERVE_SYMLINKS'])delete env[key];
82
- const result=await resumeSkillHandoff({file:args.resume,env,onChange:patch=>{if(!operation){operation=patch;stage=path.dirname(plainPath(args.resume));}updateOperation(patch);}});
71
+ const result=await resumeSkillHandoff({file:args.resume,env,journeyControl,onChange:updateOperation});
83
72
  updateOperation(result);process.exitCode=result.state==='completed'?0:1;
84
73
  }else if(maintenance){
85
74
  plainPath(args.root);
86
75
  const env={...process.env};for(const key of ['NODE_OPTIONS','NODE_PATH','NODE_V8_COVERAGE','NODE_REDIRECT_WARNINGS','NODE_COMPILE_CACHE','NODE_COMPILE_CACHE_PORTABLE','NODE_PRESERVE_SYMLINKS'])delete env[key];
87
- updateOperation({kind:args.update?'update':'uninstall',installationRoot:args.root});
88
- progressPage=await startProgressPage(()=>operation);updateOperation({progressUrl:progressPage.url});
76
+ const installed=installedClient(args.root,env),current=installed.call(['manager','inspect','--root',args.root]).installation?.current;
77
+ if(!current?.identity?.installId)fail('当前安装身份无法核实;尚未获取或执行维护');
78
+ const capability=spawnSync(installed.launcher,['--help'],{encoding:'utf8',env,timeout:15000});
79
+ if(capability.status!==0||!capability.stdout.includes('--journey-channel'))fail('当前安装不受新版单页流程支持。请另行确认卸载旧版并重新安装新版;本次不删除、不迁移、不回退旧页面');
80
+ updateOperation({kind:args.update?'update':'uninstall',installationRoot:args.root,currentVersion:current.version,installId:current.identity.installId});
81
+ progressPage=await startProgressPage(()=>operation,{control:journeyControl});updateOperation({progressUrl:progressPage.url});
82
+ console.log(JSON.stringify({status:'FOUNDATION_SINGLE_PAGE',url:progressPage.url,operationId:operation.operationId}));
89
83
  let candidate;
90
84
  if(args.update){
91
85
  const {context,receipt}=await acquireInWorker({version:args.version,stage,operationId:operation.operationId,onContext:context=>updateOperation({version:context.version,sourceCommit:context.sourceCommit}),onProgress:download=>updateOperation({download}),onPhase:phase=>updateOperation({phase})});
92
86
  const directory=plainPath(path.dirname(receipt.launcher)),manifest=JSON.parse(fs.readFileSync(plainPath(path.join(directory,'manifest.json'))));
93
87
  if(manifest.productVersion!==context.version)fail('获取版本与候选不一致');
94
88
  candidate={path:directory,manifestHash:manifest.candidateHash,version:manifest.productVersion,bytes:manifest.totalBytes,runtimeHash:manifest.files.find(f=>f.path===manifest.runtime.path)?.sha256};
89
+ updateOperation({phase:'acquired'});
95
90
  }
96
- updateOperation(await followMaintenance({operation,kind:operation.kind,candidate,env,onChange:updateOperation}));
91
+ updateOperation(await followMaintenance({operation,kind:operation.kind,candidate,env,onChange:updateOperation,journeyControl}));
97
92
  process.exitCode=operation.state==='completed'?0:1;
98
93
  await progressPage.close();progressPage=null;
99
94
  }else if(!args.prepare&&!args.acquire){
@@ -104,24 +99,30 @@ try{
104
99
  terminalBoundary:'普通终端无法创建或唤醒 Codex 对话;请在有相应权限的 Codex 任务发起安装。',
105
100
  acquisition:'尚未下载或验证运行归档。默认入口或 --prepare 执行匿名 GitHub 证明与完整性核验。'},null,2));
106
101
  }else{
107
- if(args.destination)plainPath(args.destination);console.log(`本次独占获取目录:${stage}`);
108
- progressPage=await startProgressPage(()=>operation);
102
+ console.log(`本次独占获取目录:${stage}`);
103
+ progressPage=await startProgressPage(()=>operation,args.acquire?{}:{control:journeyControl});
109
104
  updateOperation({progressUrl:progressPage.url});
110
- console.log(JSON.stringify({status:'FOUNDATION_ACQUISITION_PROGRESS_PAGE',url:progressPage.url,operationId:operation.operationId,next:'在 Codex 内置浏览器打开同次只读进度页,保持任务等待;不会自动打开系统浏览器。'}));
105
+ console.log(JSON.stringify({status:'FOUNDATION_ACQUISITION_PROGRESS_PAGE',url:progressPage.url,operationId:operation.operationId,next:'在 Codex 内置浏览器打开本次页面,所有所需确认在原页展开;保持任务等待,不自动打开系统浏览器。'}));
106
+ if(!args.acquire){
107
+ const metadata=inspectRelease(args.version);args.version=metadata.version;
108
+ updateOperation({phase:'choosing-intent',version:metadata.version,sourceCommit:metadata.sourceCommit,acquisitionRoot:stage,destinationIntent:args.destination||'',journeyContext:{id:operation.operationId,skillChoice:'undecided'}});
109
+ const choice=await journeyControl.waitChoice();
110
+ updateOperation({phase:'discovering',intentSelected:true,destinationIntent:choice.destination,journeyContext:{id:operation.operationId,skillChoice:choice.skillChoice}});
111
+ }
111
112
  const {context,receipt}=await acquireInWorker({version:args.version,stage,operationId:operation.operationId,onContext:context=>updateOperation({version:context.version,sourceCommit:context.sourceCommit}),onProgress:download=>updateOperation({download}),onPhase:phase=>updateOperation({phase})});console.log(JSON.stringify({status:'GITHUB_ACQUISITION_VERIFIED',...receipt,destinationIntent:args.destination}));
112
113
  updateOperation({phase:'acquired',version:context.version,sourceCommit:context.sourceCommit});
113
114
  if(args.acquire){updateOperation({state:'update-input-ready',terminal:true});console.log(JSON.stringify({status:'UPDATE_INPUT_READY_NOT_APPLIED',candidate:path.dirname(receipt.launcher),receipt:path.join(stage,'acquisition.json'),next:'使用当前健康安装的稳定入口生成独立更新计划;本人确认后才更新。获取回执不是删除授权。'}));await progressPage.close();progressPage=null;process.exit(0);}
114
115
  const env={...process.env};for(const key of ['NODE_OPTIONS','NODE_PATH','NODE_V8_COVERAGE','NODE_REDIRECT_WARNINGS','NODE_COMPILE_CACHE','NODE_COMPILE_CACHE_PORTABLE','NODE_PRESERVE_SYMLINKS'])delete env[key];
115
116
  const supported=spawnSync(receipt.launcher,['--help'],{encoding:'utf8',env,timeout:15000});
116
- if(!args.destination){
117
- if(supported.status!==0||!supported.stdout.includes('--choose-destination'))fail('本次发行尚不支持页面选择目录;未启动安装。请由当前对话取得目录后使用明确的 --destination,或等待新版发行,不静默采用默认位置');
118
- }
117
+ if(supported.status!==0||!supported.stdout.includes('--journey-channel'))fail('该发行不支持新版单页流程;未安装,不回退旧页面。请使用支持单页的新版发行');
119
118
  updateOperation({phase:'starting-confirmation-service',installationWrites:'unknown'});
120
- const child=spawn(receipt.launcher,['install',...(!args.destination&&supported.stdout?.includes('--journey-id')?['--journey-id',operation.operationId]:[]),...(args.destination?['--destination',args.destination]:['--choose-destination']),'--browser','codex'],{stdio:['inherit','pipe','inherit'],env});
119
+ const child=spawn(receipt.launcher,['install','--journey-id',operation.operationId,'--choose-destination','--journey-channel','--browser','codex'],{stdio:['inherit','pipe','inherit','ipc'],env});
120
+ journeyControl.attach(child);
121
121
  child.stdout.setEncoding('utf8');
122
122
  let pending='',json='';
123
123
  child.stdout.on('data',bytes=>{process.stdout.write(bytes);pending+=bytes.toString();if(pending.length>1_000_000){pending='';json='';return;}let end;while((end=pending.indexOf('\n'))>=0){const line=pending.slice(0,end);pending=pending.slice(end+1);if(!json&&!line.trim().startsWith('{'))continue;json+=line+'\n';if(json.length>1_000_000){json='';continue;}let e;try{e=JSON.parse(json)}catch{continue}json='';
124
124
  const observed=runtimeObservation(e);if(observed)updateOperation(observed);
125
+ journeyControl.observe(child,e).catch(error=>{updateOperation({state:'verification-required',terminal:true,next:error.message});child.kill('SIGTERM');});
125
126
  }});
126
127
  const interrupt=signal=>{child.kill(signal);};
127
128
  const int=()=>interrupt('SIGINT'),term=()=>interrupt('SIGTERM');
@@ -129,14 +130,10 @@ try{
129
130
  const ended=await new Promise((resolve,reject)=>{child.once('error',reject);child.once('close',(code,signal)=>resolve({code,signal}));}).finally(()=>{process.off('SIGINT',int);process.off('SIGTERM',term);});
130
131
  if(ended.signal||ended.code===null)fail(`确认服务未正常返回;结果待核实,保留 ${stage},不要自动重试安装`);
131
132
  if(operation.state==='awaiting-skill'){
132
- try{updateOperation(await followSelectedSkill({operation,env,onChange:updateOperation}));}
133
+ try{updateOperation(await followSelectedSkill({operation,env,onChange:updateOperation,journeyControl}));}
133
134
  catch(error){updateOperation({state:'partial',phase:'finished',terminal:true,skillRegistered:false,handoffFailure:{code:error.code||'SKILL_HANDOFF_REQUIRES_VERIFICATION',command:error.command||null,exitCode:error.exitCode??null},next:'程序已安装,Skill 接续未完成;保留当前计划与结果,仅核实未完成步骤,不重装程序或重放确认。'});}
134
135
  }
135
136
  if(!operation.terminal)updateOperation({state:'verification-required',terminal:true,childExitCode:ended.code,next:'服务退出不等于成功或取消;只读核验原 session 与 installed 状态,不自动重试'});
136
- if(operation.state==='completed'&&operation.installationRoot){
137
- const workbench=await openInstalledWorkbench(operation.installationRoot,env);
138
- updateOperation({phase:'finished',workbench,next:workbench.state==='ready'?(operation.skillRegistered?'打开已安装工作台;Skill 文件已注册,新对话识别与项目接入另验':'打开已安装工作台;本次未注册 Skill,项目接入另行确认'):'安装已完成,但工作台未就绪;保留安装结果并只读检查'});
139
- }
140
137
  process.exitCode=operation.state==='partial'?1:ended.code;
141
138
  }
142
- }catch(e){const message=String(e.message).replace(/https?:\/\/\S+/g,'[已脱敏网址]').replace(/(?:github_pat_|ghp_|npm_)[A-Za-z0-9_]+/g,'[已脱敏凭据]');updateOperation({state:operation?.programState==='completed'?'partial':operation&&operation.installationWrites!=='none'?'verification-required':'failed',terminal:true,...(operation?.programState==='completed'?{failedPhase:operation.phase,phase:'finished'}:{}),errorCode:['ACQUISITION_TRANSPORT_FAILED','ACQUISITION_VALIDATION_FAILED'].includes(e.code)?e.code:'INSTALL_ENTRY_FAILED',diagnostic:e.diagnostic||null,next:message+'。先核验旧工具进程已结束及同次结果;保留材料,不自动重试或重放安装确认'});console.error(`错误:${message}`);process.exitCode=1;}finally{if(progressPage)await progressPage.close();}
139
+ }catch(e){const message=String(e.message).replace(/https?:\/\/\S+/g,'[已脱敏网址]').replace(/(?:github_pat_|ghp_|npm_)[A-Za-z0-9_]+/g,'[已脱敏凭据]');updateOperation({state:e.code==='ENTRY_CHOICE_CANCELLED'?'cancelled-no-install':e.code==='ENTRY_CHOICE_EXPIRED'?'expired-no-install':operation?.programState==='completed'?'partial':operation&&operation.installationWrites!=='none'?'verification-required':'failed',terminal:true,...(operation?.programState==='completed'?{failedPhase:operation.phase,phase:'finished'}:{}),errorCode:['ACQUISITION_TRANSPORT_FAILED','ACQUISITION_VALIDATION_FAILED','ENTRY_CHOICE_CANCELLED','ENTRY_CHOICE_EXPIRED'].includes(e.code)?e.code:'INSTALL_ENTRY_FAILED',diagnostic:e.diagnostic||null,next:message+'。先核验旧工具进程已结束及同次结果;保留材料,不自动重试或重放安装确认'});console.error(`错误:${message}`);process.exitCode=1;}finally{if(progressPage)await progressPage.close();}
@@ -0,0 +1,68 @@
1
+ import crypto from 'node:crypto';
2
+
3
+ // Only the exact child created by this invocation may supply an active view.
4
+ // Browser input cannot name a URL, route, transport token or future plan.
5
+ export function createJourneyControl(readRecord, changed) {
6
+ const children=new Map();let active=null,origin=null,choice=null,resolveChoice,rejectChoice,choiceTimer,viewRevision=0;
7
+ const headers=owner=>({origin,'content-type':'application/json','x-foundation-journey':owner.token,'x-foundation-operation':readRecord().operationId});
8
+ const request=async(owner,route,body)=>{
9
+ if(owner.child.exitCode!==null||owner.child.signalCode)throw Error('确认服务已退出,结果待核实');
10
+ const response=await fetch(owner.url+route,{method:body?'POST':'GET',headers:headers(owner),...(body?{body:JSON.stringify(body)}:{}),redirect:'error',signal:AbortSignal.timeout(120000)});
11
+ return {status:response.status,body:await response.json()};
12
+ };
13
+ return {
14
+ setOrigin(value){if(origin)throw Error('单页来源不能重绑定');origin=value;},
15
+ attach(child){
16
+ const owner={child,token:crypto.randomBytes(32).toString('hex'),url:null};children.set(child,owner);
17
+ child.on('message',message=>{if(message?.type==='foundation-journey-ready-v1')child.send({type:'foundation-journey-bind-v1',origin,operationId:readRecord().operationId,token:owner.token});});
18
+ child.once('close',()=>{children.delete(child);if(active?.owner===owner){active=null;changed();}});
19
+ },
20
+ async observe(child,event){
21
+ if(event.status==='FOUNDATION_OPERATION_STATE'&&active?.view?.session?.sessionId===event.sessionId){active.view.session.state=event.state;changed();return;}
22
+ if(!['AWAITING_FOUNDATION_DIRECTORY_SELECTION','AWAITING_FOUNDATION_UI_CONFIRMATION'].includes(event.status))return;
23
+ const owner=children.get(child);if(!owner)throw Error('未绑定的确认进程');
24
+ const revision=++viewRevision;
25
+ const url=new URL(event.url);if(url.protocol!=='http:'||url.hostname!=='127.0.0.1'||url.pathname!=='/'||url.search||url.hash||url.username||url.password)throw Error('确认服务地址无效');
26
+ owner.url=url.href;
27
+ const selection=event.status==='AWAITING_FOUNDATION_DIRECTORY_SELECTION';
28
+ const result=await request(owner,selection?'__foundation/install/view':'__foundation/manager/view');
29
+ if(children.get(child)!==owner||revision!==viewRevision)return;
30
+ if(result.status!==200||result.body.operationId!==readRecord().operationId)throw Error('当前引擎不支持单页确认;旧版本需要另行重新安装,不降级到旧页面');
31
+ if(!selection&&result.body.session.sessionId!==event.sessionId)throw Error('确认会话不匹配');
32
+ active={owner,type:selection?'selection':'manager',view:result.body};changed();
33
+ if(selection&&choice){
34
+ const selected=await request(owner,'__foundation/install/selection',{nonce:result.body.nonce,action:'select',destination:choice.destination,skillChoice:choice.skillChoice});
35
+ if(selected.status!==200){active.error=selected.body.message;choice=null;changed();}
36
+ }
37
+ },
38
+ view(){return active?{type:active.type,...active.view,error:active.error||null}:null;},
39
+ waitChoice({timeoutMs=600000}={}){return new Promise((resolve,reject)=>{
40
+ if(resolveChoice)throw Error('目录选择已在等待');
41
+ resolveChoice=resolve;rejectChoice=reject;
42
+ choiceTimer=setTimeout(()=>{resolveChoice=null;rejectChoice=null;reject(Object.assign(Error('目录选择已到期,尚未下载或安装;重新发起需要新的选择'),{code:'ENTRY_CHOICE_EXPIRED'}));changed();},timeoutMs);
43
+ changed();
44
+ });},
45
+ async submit(body){
46
+ if(body.operationId!==readRecord().operationId)throw Error('流程身份不匹配');
47
+ if(body.action==='cancel-intent'&&rejectChoice){
48
+ clearTimeout(choiceTimer);const reject=rejectChoice;resolveChoice=null;rejectChoice=null;
49
+ reject(Object.assign(Error('已取消目录选择,尚未下载或安装'),{code:'ENTRY_CHOICE_CANCELLED'}));changed();return {status:200,body:{state:'cancelled-no-install'}};
50
+ }
51
+ if(body.action==='choose'&&resolveChoice){
52
+ if(typeof body.destination!=='string'||!body.destination.trim()||!['selected','skipped'].includes(body.skillChoice))throw Error('请选择完整目录和 Skill 意向');
53
+ choice={destination:body.destination,skillChoice:body.skillChoice};const resolve=resolveChoice;clearTimeout(choiceTimer);resolveChoice=null;rejectChoice=null;resolve(choice);changed();return {status:200,body:{state:'intent-selected'}};
54
+ }
55
+ if(!active)throw Error('当前没有可确认的计划;请等待或查询结果');
56
+ const a=active;
57
+ if(a.type==='selection'){
58
+ if(!['select','cancel'].includes(body.action))throw Error('目录操作无效');
59
+ const result=await request(a.owner,'__foundation/install/selection',{nonce:a.view.nonce,action:body.action,destination:body.destination,skillChoice:body.skillChoice});
60
+ if(result.status!==200)a.error=result.body.message;changed();return result;
61
+ }
62
+ const s=a.view.session;
63
+ if(body.sessionId!==s.sessionId||body.planHash!==s.planHash||body.managerNonce!==a.view.managerNonce||!['cancel-no-change',a.view.action].includes(body.action))throw Error('当前计划已变化或请求无效');
64
+ const result=await request(a.owner,'__foundation/manager/confirm',{operationId:body.operationId,sessionId:s.sessionId,planHash:s.planHash,managerNonce:body.managerNonce,action:body.action});
65
+ if(active===a&&result.body.state)a.view.session={...s,...result.body};changed();return result;
66
+ }
67
+ };
68
+ }
@@ -17,17 +17,17 @@ export function matchesUninstallResult(receipt,payload,installId) {
17
17
  }
18
18
 
19
19
  // Only coordinates the installed exact-plan API. Every mutation waits for its
20
- // own manager confirmation. Even the first update uses the OLD stable launcher.
21
- export async function followMaintenance({operation,kind,candidate,env,onChange}) {
20
+ // own manager confirmation, executed by the current owned stable launcher.
21
+ export async function followMaintenance({operation,kind,candidate,env,onChange,journeyControl=null}) {
22
22
  if(!['update','uninstall'].includes(kind))throw Error('维护类型无效');
23
- const client=installedClient(operation.installationRoot,env),{root,call}=client;
23
+ const client=installedClient(operation.installationRoot,env,journeyControl),{root,call}=client;
24
24
  const before=call(['manager','inspect','--root',root]),current=before.installation?.current;
25
25
  if(!current?.identity?.installId||before.bridge?.currentVersion!==current.version)throw Error('当前安装无法核实');
26
26
  if(kind==='update'&&(!candidate||candidate.version===current.version))throw Error('目标版本无效或已经安装;不重复更新或解除 Skill');
27
27
  const manifest=plainPath(path.join(root,current.appPath,'artifacts/skills/ai-product-foundation-kit/capability.json'));
28
28
  if(!manifest.startsWith(root+path.sep))throw Error('当前材料路径越界');
29
- // On 0.2.10 inspect has no codexSkill field. File presence only requests an
30
- // ownership-checked plan; the old engine validates its signed receipt/files.
29
+ // File presence only requests an ownership-checked plan; the running engine
30
+ // validates its receipt and files. It does not authorize removal.
31
31
  const registration=plainPath(path.join(root,'state/codex-skill-registration.json'));
32
32
  const hadSkill=fs.existsSync(registration);
33
33
  let previousPlanRef=null;
@@ -72,6 +72,6 @@ const event=await observePlan(client,requested,observation=>onChange({phase:obse
72
72
  }
73
73
  const after=call(['manager','inspect','--root',root]).installation?.current;
74
74
  if(after?.identity?.installId!==current.identity.installId||after.version!==candidate.version||after.candidateHash!==candidate.manifestHash||payload.stableLauncherHealth!=='passed')throw Error('更新后的稳定入口身份或健康待核实');
75
- if(hadSkill)return followSelectedSkill({operation:{...operation,kind:'update',installationRoot:root,programState:'completed',sessionId:null,previousPlanRef,journeyContext:{id:operation.operationId,skillChoice:'selected'}},env,onChange});
75
+ if(hadSkill)return followSelectedSkill({operation:{...operation,kind:'update',installationRoot:root,programState:'completed',sessionId:null,previousPlanRef,journeyContext:{id:operation.operationId,skillChoice:'selected'}},env,onChange,journeyControl});
76
76
  return {state:'completed',terminal:true,phase:'finished',skillRegistered:false,next:'更新及稳定入口健康核验完成;未新增 Skill,项目与用户数据按计划保留。'};
77
77
  }
@@ -3,7 +3,7 @@ import path from 'node:path';
3
3
  import {plainPath} from './acquire.mjs';
4
4
 
5
5
  // A client of the existing installed manager, never a confirmation authority.
6
- export function installedClient(root,env) {
6
+ export function installedClient(root,env,journeyControl=null) {
7
7
  root=plainPath(root);
8
8
  const launcher=plainPath(path.join(root,'bin/foundation-kit'));
9
9
  const call=args=>{
@@ -11,22 +11,19 @@ export function installedClient(root,env) {
11
11
  if(r.status!==0){const e=Error('已安装入口检查失败;保留已核实结果,不自动重放');e.code='INSTALLED_COMMAND_FAILED';e.command=args.slice(0,2);e.exitCode=r.status;throw e;}
12
12
  return JSON.parse(r.stdout);
13
13
  };
14
- return {root,launcher,call,env};
14
+ return {root,launcher,call,env,journeyControl};
15
15
  }
16
16
 
17
17
  export async function observePlan(client,requested,onChange) {
18
18
  if(!/^foundation-plan-[a-f0-9]{64}$/.test(requested.planRef))throw Error('计划标识无效');
19
- const child=spawn(client.launcher,['manager','open-manager','--plan-ref',requested.planRef],{env:client.env,stdio:['ignore','pipe','pipe']});
19
+ const child=spawn(client.launcher,['manager','open-manager','--plan-ref',requested.planRef,...(client.journeyControl?['--journey-channel']:[])],{env:client.env,stdio:['ignore','pipe','pipe',...(client.journeyControl?['ipc']:[])]});
20
+ client.journeyControl?.attach(child);
20
21
  let pending='',json='',finished=false;
21
22
  return new Promise((resolve,reject)=>{
22
23
  const stop=()=>child.kill('SIGTERM');
23
24
  const finish=(error,value)=>{if(finished)return;finished=true;clearTimeout(timer);process.off('SIGINT',stop);process.off('SIGTERM',stop);
24
- if(error||value?.responseFinished===true)child.kill('SIGTERM');
25
- else { // Older managers report results before HTTP flush. Leave their
26
- // existing bounded page lifetime intact rather than aborting the reply.
27
- child.stdout.destroy();child.stderr.destroy();child.unref();
28
- onChange({state:value.state,temporaryManager:{pid:child.pid,expiresAt:requested.expiresAt,reason:'old-manager-response-flush-unavailable'}});
29
- }
25
+ if(!error&&value?.responseFinished!==true)error=Error('当前引擎未核实确认响应结束;保留结果,不降级到旧页面');
26
+ child.kill('SIGTERM');
30
27
  error?reject(error):resolve(value);
31
28
  };
32
29
  const timer=setTimeout(()=>finish(Error('确认等待到期;保留同次计划记录')),Math.max(1,Math.min(16*60*1000,requested.expiresAt-Date.now()+1000)));
@@ -44,6 +41,7 @@ export async function observePlan(client,requested,onChange) {
44
41
  if(!json&&!line.trim().startsWith('{'))continue;
45
42
  json+=line+'\n';let event;try{event=JSON.parse(json);}catch{continue;}json='';
46
43
  if(event.planRef!==requested.planRef)continue;
44
+ client.journeyControl?.observe(child,event).catch(error=>finish(error));
47
45
  if(event.status==='AWAITING_FOUNDATION_UI_CONFIRMATION'){
48
46
  const url=new URL(event.url);if(url.protocol!=='http:'||url.hostname!=='127.0.0.1'||url.username||url.password)return finish(Error('确认网址无效'));
49
47
  onChange({state:'pending',confirmationUrl:url.href,sessionId:event.sessionId});
@@ -1,6 +1,7 @@
1
1
  import http from 'node:http';
2
2
  import crypto from 'node:crypto';
3
3
  import {journeyView} from './journey-view.mjs';
4
+ import {singlePageDocument} from './single-page-view.mjs';
4
5
 
5
6
  export function downloadText(download) {
6
7
  if(!download||!Number.isFinite(download.downloadedBytes)||download.downloadedBytes<0)return '';
@@ -39,19 +40,32 @@ export function acquisitionProgress(record) {
39
40
 
40
41
  // A bounded, read-only loopback view over the existing in-memory operation.
41
42
  // No POST, launch endpoint, confirmation authority or downloaded executable.
42
- export async function startProgressPage(readRecord) {
43
+ export async function startProgressPage(readRecord, {control = null} = {}) {
43
44
  const token=crypto.randomBytes(24).toString('hex'),base=`/${token}`,clients=new Set();
44
45
  const html=`<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>Foundation 获取与安装进度</title><style>body{font:16px/1.6 system-ui;max-width:760px;margin:24px auto;padding:0 20px;color:#18181b;background:#fafafa;overflow-wrap:anywhere}section{background:white;border:1px solid #e4e4e7;border-radius:12px;padding:16px;margin:16px 0}h1{font-size:24px}h2{font-size:18px}a{display:inline-block;padding:12px;border:1px solid #71717a;border-radius:8px;color:inherit}pre{white-space:pre-wrap}a:focus-visible,summary:focus-visible{outline:3px solid #2563eb}[hidden]{display:none}.steps{display:flex;flex-wrap:wrap;gap:8px}.steps p{margin:0;background:#f4f4f5;padding:6px 10px;border-radius:6px;font-size:13px}header{font-size:14px;font-weight:600}#continue{background:#18181b;color:white;font-weight:600;text-decoration:none}#target{overflow-wrap:anywhere}@media(max-width:480px){body{padding:0 16px}.steps p{flex:1 1 110px}}</style><body><header>Foundation</header><h1>正在准备 Foundation</h1><section role="status" aria-live="polite"><h2 id="phase">正在读取同次操作</h2><div id="journey-steps" class="steps"></div><p id="journey-summary"></p><p id="version"></p><p id="download"></p><p id="target"></p><p id="program"></p><p id="skill"></p><p id="project"></p><p id="next"></p><a id="continue" hidden>继续到目录选择 / 本人确认页</a><p id="connection"></p></section><p>此页面只读,不批准安装;程序、对话能力与项目分别确认。未知长度不显示百分比。临时服务结束后,可从原对话读取保留的操作结果。</p><details><summary>操作与恢复详情</summary><pre id="raw"></pre></details><script>const downloadText=${downloadText.toString()};let last=null;function show(p){last=p;document.querySelector('h1').textContent=p.journey.title;document.getElementById('journey-summary').textContent=p.journey.summary;const steps=document.getElementById('journey-steps');steps.replaceChildren();for(const step of p.journey.steps){const line=document.createElement('p');line.textContent=step.title+':'+step.label;steps.append(line);}for(const key of ['phase','program','skill','project','next'])document.getElementById(key).textContent=p[key]||'';document.getElementById('download').textContent=downloadText(p.download);document.getElementById('version').textContent=p.version?'版本:'+p.version:'';document.getElementById('target').textContent=p.installationRoot?'程序目录:'+p.installationRoot:'';const link=document.getElementById('continue');link.hidden=!p.nextUrl;link.textContent=p.nextLabel;if(p.nextUrl)link.href=p.nextUrl;document.getElementById('raw').textContent=JSON.stringify(p,null,2);}const events=new EventSource(location.pathname+'/events');events.onmessage=e=>show(JSON.parse(e.data));events.onerror=()=>{events.close();document.getElementById('connection').textContent=last&&last.terminal?'临时进度服务已结束,上方保留最后收到的结果。':'连接已中断,当前状态待核实;不自动重试安装。'};window.addEventListener('pagehide',()=>events.close(),{once:true});</script></body></html>`;
45
46
  let origin;
47
+ let terminalObserved=false,terminalRead=null;
46
48
  const current=()=>JSON.stringify(acquisitionProgress(readRecord()));
47
- const server=http.createServer((req,res)=>{
48
- if(req.method!=='GET'||req.headers.host!==origin||req.headers.origin&&req.headers.origin!==`http://${origin}`){res.writeHead(403).end();return;}
49
+ const server=http.createServer(async(req,res)=>{
50
+ if(req.headers.host!==origin||req.headers.origin&&req.headers.origin!==`http://${origin}`){res.writeHead(403).end();return;}
51
+ if(control&&req.method==='GET'&&req.url===base+'/state'){const record=readRecord();if(record.terminal)res.once('finish',()=>{terminalObserved=true;terminalRead?.();});res.writeHead(200,{'content-type':'application/json','cache-control':'no-store'}).end(JSON.stringify({record,progress:acquisitionProgress(record),view:control.view()}));return;}
52
+ if(control&&req.method==='POST'&&req.url===base+'/action'){
53
+ if(req.headers.origin!==`http://${origin}`||req.headers['content-type']!=='application/json'){res.writeHead(403).end();return;}
54
+ try{let body='',size=0;for await(const chunk of req){size+=chunk.length;if(size>16384)throw Error('请求过大');body+=chunk;}const input=JSON.parse(body);if(input.csrf!==token)throw Error('页面确认身份不符');const result=await control.submit(input);res.writeHead(result.status,{'content-type':'application/json','cache-control':'no-store'}).end(JSON.stringify(result.body));}catch(error){res.writeHead(409,{'content-type':'application/json','cache-control':'no-store'}).end(JSON.stringify({message:error.message}));}return;
55
+ }
56
+ if(req.method!=='GET'){res.writeHead(403).end();return;}
49
57
  const headers={'cache-control':'no-store','x-content-type-options':'nosniff','content-security-policy':"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'"};
50
- if(req.url===base){res.writeHead(200,{...headers,'content-type':'text/html; charset=utf-8'}).end(html);}
58
+ if(req.url===base){res.writeHead(200,{...headers,'content-type':'text/html; charset=utf-8'}).end(control?singlePageDocument(token):html);}
51
59
  else if(req.url===base+'/events'){res.writeHead(200,{...headers,'content-type':'text/event-stream'});res.write(`data: ${current()}\n\n`);clients.add(res);req.on('close',()=>clients.delete(res));}
52
60
  else{res.writeHead(404).end();}
53
61
  });
54
62
  await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
55
63
  origin=`127.0.0.1:${server.address().port}`;
56
- return {url:`http://${origin}${base}`,publish(){for(const res of clients)res.write(`data: ${current()}\n\n`);},close(){for(const res of clients)res.end();clients.clear();return new Promise(resolve=>server.close(resolve));}};
64
+ control?.setOrigin(`http://${origin}`);
65
+ return {url:`http://${origin}${base}`,publish(){for(const res of clients)res.write(`data: ${current()}\n\n`);},async close(){
66
+ // Allow the same page to receive the terminal snapshot before this bounded
67
+ // service exits. No polling or page acknowledgement authorizes a mutation.
68
+ if(control&&readRecord().terminal&&!terminalObserved)await new Promise(resolve=>{const timer=setTimeout(resolve,15000);terminalRead=()=>{clearTimeout(timer);resolve();};});
69
+ for(const res of clients)res.end();clients.clear();return new Promise(resolve=>server.close(resolve));
70
+ }};
57
71
  }
@@ -3,7 +3,7 @@ import {installedClient} from './manager-step.mjs';
3
3
  import {followSelectedSkill} from './skill-handoff.mjs';
4
4
 
5
5
  // Explicit user-requested recovery, never an automatic replay of approval.
6
- export async function resumeSkillHandoff({file,env,onChange}) {
6
+ export async function resumeSkillHandoff({file,env,onChange,journeyControl=null}) {
7
7
  const previous=readOperation(file);
8
8
  if(previous.pid&&previous.pid!==process.pid){
9
9
  try{process.kill(previous.pid,0);throw Error('原进程仍存在,先在原任务查询;不并发恢复');}
@@ -20,5 +20,5 @@ export async function resumeSkillHandoff({file,env,onChange}) {
20
20
  }
21
21
  const operation={...previous,pid:process.pid,state:'awaiting-skill',terminal:false};
22
22
  onChange(operation);
23
- return followSelectedSkill({operation,env,onChange});
23
+ return followSelectedSkill({operation,env,onChange,journeyControl});
24
24
  }
@@ -0,0 +1,4 @@
1
+ // Product-area CSS transplanted from the approved 040 reference.
2
+ // Source SHA-256: e9949cc0d67e979b0297ca654eda1f163f2178b3338d4c4cf3ea9363e3cd8644
3
+ // Demo-only selectors remain inert; there are no demo controls in production.
4
+ export const singlePageStyle = "#foundation-flow-demo{--fp-bg:light-dark(#fff,#191b20);--fp-soft:light-dark(#f7f8fa,#23262c);--fp-text:light-dark(#20252d,#eff1f5);--fp-muted:light-dark(#606a78,#adb5c3);--fp-line:light-dark(#e5e8ee,#383d46);--fp-accent:light-dark(#315ee8,#98b3ff);--fp-active:light-dark(#f3f6ff,#232f48);--fp-good:light-dark(#23784c,#8ddcb1);--fp-error:light-dark(#b33434,#ffadad);font-family:Inter,-apple-system,BlinkMacSystemFont,\"Segoe UI\",sans-serif;color:var(--fp-text);font-size:14px;line-height:1.6;color-scheme:light dark}\n#foundation-flow-demo *{box-sizing:border-box}#foundation-flow-demo [hidden]{display:none!important}#foundation-flow-demo button,#foundation-flow-demo input,#foundation-flow-demo select{font:inherit;color:inherit}#foundation-flow-demo button,#foundation-flow-demo select{cursor:pointer}#foundation-flow-demo button{border:1px solid var(--fp-line);background:var(--fp-bg);border-radius:7px;padding:9px 15px;min-height:42px}#foundation-flow-demo button:disabled{opacity:.55;cursor:default}#foundation-flow-demo .demo-tools{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-bottom:14px;color:var(--fp-muted);font-size:12px}#foundation-flow-demo .demo-tools label{margin-left:auto;display:flex;align-items:center;gap:8px}#foundation-flow-demo select{padding:7px;border:1px solid var(--fp-line);border-radius:6px;background:var(--fp-bg)}#foundation-flow-demo .product{background:var(--fp-bg);border:1px solid var(--fp-line);border-radius:14px;overflow:hidden}#foundation-flow-demo .brand{display:flex;align-items:center;gap:9px;padding:18px 26px;border-bottom:1px solid var(--fp-line);font-weight:500}#foundation-flow-demo .brand-mark{display:grid;place-items:center;width:26px;height:26px;border-radius:6px;background:var(--fp-text);color:var(--fp-bg)}#foundation-flow-demo .private-label{margin-left:auto;font-size:12px;color:var(--fp-muted);font-weight:400}#foundation-flow-demo .overview{padding:24px 26px 20px}#foundation-flow-demo h1{font-size:25px;font-weight:500;line-height:1.3;margin:5px 0 8px}#foundation-flow-demo p{margin:6px 0}#foundation-flow-demo .eyebrow{color:var(--fp-accent);font-size:12px;font-weight:500}#foundation-flow-demo #flow-description{color:var(--fp-muted)}#foundation-flow-demo .metadata{display:flex;flex-direction:column;gap:4px;margin:15px 0;color:var(--fp-muted);font-size:12px;overflow-wrap:anywhere}#foundation-flow-demo .progress-label{display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;font-size:12px;margin-bottom:8px}#foundation-flow-demo #flow-status{color:var(--fp-accent)}#foundation-flow-demo .track{height:5px;background:var(--fp-soft);border-radius:4px;overflow:hidden}#foundation-flow-demo #flow-bar{height:100%;background:var(--fp-accent);width:0;transition:width .2s}#foundation-flow-demo .steps{list-style:none;padding:0 26px;margin:0}#foundation-flow-demo .step{border-top:1px solid var(--fp-line);padding:15px 0}#foundation-flow-demo .step.current{background:var(--fp-active);border:1px solid var(--fp-line);border-radius:10px;padding:16px;margin:4px -16px 8px}#foundation-flow-demo .step-top{display:flex;align-items:center;gap:12px}#foundation-flow-demo .step-number{flex:none;border:1px solid var(--fp-line);border-radius:50%;width:25px;height:25px;display:grid;place-items:center;font-size:12px;color:var(--fp-muted)}#foundation-flow-demo .done .step-number{color:var(--fp-good);border-color:transparent;background:var(--fp-soft)}#foundation-flow-demo .current .step-number{background:var(--fp-accent);color:var(--fp-bg);border-color:transparent}#foundation-flow-demo .step-title{font-weight:500;flex:1}#foundation-flow-demo .step-state{font-size:12px;color:var(--fp-muted)}#foundation-flow-demo .done .step-state{color:var(--fp-good)}#foundation-flow-demo .step-body{margin:12px 0 0 37px;color:var(--fp-muted)}#foundation-flow-demo .field{display:block;margin:13px 0 5px;color:var(--fp-text)}#foundation-flow-demo input[type=text]{width:100%;min-width:0;font-size:16px;background:var(--fp-bg);border:1px solid var(--fp-line);border-radius:7px;padding:10px}#foundation-flow-demo .check{display:flex;align-items:flex-start;gap:9px;margin:14px 0;color:var(--fp-text)}#foundation-flow-demo .check input{margin-top:6px;accent-color:var(--fp-accent)}#foundation-flow-demo .hint{font-size:12px;color:var(--fp-muted);overflow-wrap:anywhere}#foundation-flow-demo .actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:17px}#foundation-flow-demo .primary{background:var(--fp-accent);border-color:var(--fp-accent);color:var(--fp-bg);font-weight:500}#foundation-flow-demo .danger{background:var(--fp-error);border-color:var(--fp-error);color:var(--fp-bg)}#foundation-flow-demo .error{color:var(--fp-error);font-size:13px;margin-top:6px}#foundation-flow-demo .facts{border-left:2px solid var(--fp-line);padding-left:12px;margin:12px 0;overflow-wrap:anywhere}#foundation-flow-demo .result{margin:14px 26px 24px;padding:18px;background:var(--fp-soft);border-radius:10px}#foundation-flow-demo .result h2{font-size:18px;font-weight:500;margin:0 0 8px}#foundation-flow-demo footer{padding:17px 26px;border-top:1px solid var(--fp-line);color:var(--fp-muted);font-size:12px}#foundation-flow-demo summary{cursor:pointer}#foundation-flow-demo .completed-detail{margin-left:37px;font-size:12px;color:var(--fp-muted)}\n@media(max-width:480px){#foundation-flow-demo .overview,#foundation-flow-demo .brand,#foundation-flow-demo footer{padding-left:17px;padding-right:17px}#foundation-flow-demo .steps{padding:0 17px}#foundation-flow-demo .step.current{margin-left:-8px;margin-right:-8px;padding:12px 8px}#foundation-flow-demo .step-body{margin-left:0}#foundation-flow-demo .step-top{gap:8px}#foundation-flow-demo .step-state{max-width:82px;text-align:right}#foundation-flow-demo .demo-tools label{margin-left:0}#foundation-flow-demo .result{margin:14px 17px}#foundation-flow-demo h1{font-size:23px}}\n@media(prefers-reduced-motion:reduce){#foundation-flow-demo #flow-bar{transition:none}}";
@@ -0,0 +1,56 @@
1
+ import {singlePageStyle} from './single-page-style.mjs';
2
+
3
+ // The approved product DOM/CSS; the client consumes facts, not demo timers.
4
+ export function singlePageDocument(csrf) {
5
+ return `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Foundation 安装与维护</title><style>body{margin:0}${singlePageStyle}</style><body><div id="foundation-flow-demo" aria-label="Foundation 安装与维护"><main class="product"><header class="brand"><span class="brand-mark">F</span><span>Foundation</span><span class="private-label">安装与维护</span></header><section class="overview"><div class="eyebrow" id="flow-eyebrow">正在核实</div><h1 id="flow-title">Foundation</h1><p id="flow-description"></p><div class="metadata"><span id="flow-version"></span><span id="flow-destination"></span></div><div class="progress-label"><span id="flow-count"></span><span id="flow-status" role="status" aria-live="polite"></span></div><div class="track" role="progressbar" aria-label="已完成步骤" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div id="flow-bar"></div></div></section><ol id="flow-steps" class="steps"></ol><section id="flow-result" class="result" hidden aria-live="polite"></section><footer><p id="connection" role="status"></p><details><summary>技术详情</summary><pre id="raw" style="white-space:pre-wrap;overflow-wrap:anywhere"></pre></details></footer></main></div><script>(${singlePageClient.toString()})(${JSON.stringify(csrf)});</script></body></html>`;
6
+ }
7
+
8
+ function singlePageClient(csrf) {
9
+ const q=s=>document.querySelector(s),esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
10
+ let last=null,busy=false,revision=null,stopped=false;
11
+ const verbs={install:'安装',update:'更新',uninstall:'卸载'};
12
+ function cleanupText(session){const c=session?.hostCleanup;if(!c)return '';return '<div class="facts"><p>更新成功并通过健康检查后,清理本次下载的归档和展开候选。</p><p>清理位置:'+esc(c.root)+'</p><p>范围:'+esc(c.files?.length??'待核实')+' 个文件;'+(Number.isFinite(c.bytes)?(c.bytes/1048576).toFixed(2)+' MiB':'大小待核实')+'</p><p>保留获取回执、验证材料、回退版本、项目和未知或已修改文件;仍在使用的材料不会强删。</p></div>';}
13
+ function show(p){
14
+ last=p;const r=p.record,v=p.view,kind=r.kind||'install',verb=verbs[kind],choice=r.phase==='choosing-intent';
15
+ const titles={select:'选择安装位置',acquire:kind==='update'?'下载并检查新版':'下载并检查文件',program:verb+' Foundation',material:'准备安装 Skill',register:kind==='update'?'更新 Codex 中的 Skill':'将 Skill 安装到 Codex',remove:'移除 Codex 中的 Skill',health:'检查'+verb+'结果','optional-skill':'Foundation Skill'};
16
+ const stateLabels={failed:'本步失败',cancelled:'已取消',expired:'已过期','verification-required':'结果待核实',running:'正在执行',executing:'正在执行',consumed:'正在执行',undecided:'可选,待选择'};
17
+ const order=kind==='uninstall'?['remove','program']:['select','acquire','program','material','register','optional-skill','health'];
18
+ const steps=p.progress.journey.steps.map(s=>({...s})).sort((a,b)=>order.indexOf(a.key)-order.indexOf(b.key));
19
+ if(choice)for(const s of steps)s.state=s.key==='select'?'pending':'planned';
20
+ if(r.intentSelected){const s=steps.find(s=>s.key==='select');if(s)s.state='completed';}
21
+ let active=choice?'select':v?.type==='selection'?'select':v?.session?.capabilityId?(v.session.operation==='install'?'material':v.session.operation==='uninstall'?'remove':'register'):v?.session?'program':steps.find(s=>!['completed','skipped','retained'].includes(s.state))?.key;
22
+ // The final result check must not look finished while a chosen Skill step
23
+ // still awaits confirmation. Program health remains visible in its receipt.
24
+ const health=steps.find(s=>s.key==='health');
25
+ if(health?.state==='completed'&&!r.terminal)health.state='planned';
26
+ if(r.terminal)active=null;
27
+ const executing=['executing','consumed'].includes(v?.session?.state)||['executing','skill-executing'].includes(r.phase);
28
+ const count=steps.filter(s=>['completed','skipped','retained'].includes(s.state)).length;
29
+ q('#flow-title').textContent=r.terminal?(r.state==='completed'?'Foundation '+verb+'完成':'本次'+verb+'未全部完成'):verb+' Foundation';
30
+ q('#flow-eyebrow').textContent=r.terminal?'本次结果':executing?'正在执行':busy?'正在提交请求':v||choice?'等待你的操作':'正在进行';
31
+ q('#flow-description').textContent=kind==='install'?'安装程序和 Skill,让 Codex 可以使用 Foundation。':kind==='update'?'更新程序和已有 Skill,保留你的项目与制作资料。':'移除 Foundation 和它的 Skill,保留你的项目与制作资料。';
32
+ q('#flow-version').textContent='版本:'+(p.progress.version||'待核实');q('#flow-destination').textContent='程序位置:'+(r.installationRoot||r.destinationIntent||'等待选择');
33
+ q('#flow-count').textContent='已处理 '+count+' / '+steps.length+' 步';q('#flow-status').textContent=executing?'正在执行当前步骤':busy?'正在提交请求':r.terminal?(r.state==='completed'?'本次流程已完成':'查看未完成项'):('当前:'+(titles[active]||p.progress.phase));
34
+ const percent=steps.length?count/steps.length*100:0;q('#flow-bar').style.width=percent+'%';q('.track').setAttribute('aria-valuenow',String(Math.round(percent)));
35
+ const key=JSON.stringify([active,v?.session?.sessionId,v?.session?.state,v?.selectionId,r.terminal,steps.map(s=>s.state),v?.error]);
36
+ if(key!==revision&&!busy){
37
+ revision=key;
38
+ q('#flow-steps').innerHTML=steps.map((s,i)=>{
39
+ const done=['completed','retained'].includes(s.state),skip=s.state==='skipped',current=s.key===active;
40
+ let body='';
41
+ if(current&&(choice||v?.type==='selection'))body='<form id="current-form"><label class="field" for="install-path">安装到哪里?</label><input id="install-path" name="destination" type="text" value="'+esc(r.destinationIntent||v?.suggestion||'')+'" spellcheck="false" required><p class="hint">请输入完整路径,可以包含成对引号。不会覆盖已有内容,最终目录仍由程序检查。</p><label class="check"><input id="include-skill" name="includeSkill" type="checkbox" '+(r.journeyContext?.skillChoice==='skipped'?'':'checked')+'><span>同时安装 Foundation Skill<br><span class="hint">让 Codex 能识别 Foundation 指令,并按 Foundation 规范工作。</span></span></label><p class="hint">获取缓存:'+esc(r.acquisitionRoot||'以当前任务已披露位置为准')+'。选择不是安装批准。</p><div id="step-error" class="error" role="alert">'+esc(v?.error||'')+'</div><div class="actions"><button class="primary" name="action" value="'+(choice?'choose':'select')+'">使用这个位置</button><button name="action" value="'+(choice?'cancel-intent':'cancel')+'" formnovalidate>取消本步</button></div></form>';
42
+ else if(current&&v?.session){const f=v.feedback;body='<p>'+esc(f.detail)+'</p><div class="facts">'+f.namedTargets.map(t=>'<p>'+esc(t.label)+':'+esc(t.path||'待核实')+'</p>').join('')+'<p>保留:'+esc(f.preserves.join(';'))+'</p><p>'+esc(f.notDone)+'</p>'+cleanupText(v.session)+((v.session.deletes||[]).length?'<details open><summary>删除范围</summary>'+v.session.deletes.map(x=>'<p>'+esc(x==='foundation-installation:full'?'本安装中经所有权核验的程序、运行时和状态文件;未知或用户修改的文件保留。':typeof x==='string'?x:JSON.stringify(x))+'</p>').join('')+'</details>':'')+'</div><p class="hint">每次确认只针对当前计划,不批准后续步骤。Skill 文件就位不等于新对话已识别。</p><form id="current-form"><div id="step-error" class="error" role="alert"></div><div class="actions">'+(v.session.state==='pending'?'<button class="'+(kind==='uninstall'?'danger':'primary')+'" name="action" value="'+esc(v.action)+'">确认'+esc(titles[s.key])+'</button><button name="action" value="cancel-no-change">取消本步</button>':'<p>本步已开始或结束,不能重复确认。</p>')+'</div></form>';}
43
+ else if(current)body='<p role="status">'+esc(p.progress.phase)+'</p><p class="hint">下一步会在本页展开,不需要查找其他网址。</p>';
44
+ return '<li class="step '+(current?'current':done||skip?'done':'later')+'"><div class="step-top"><span class="step-number">'+(skip?'−':done?'✓':i+1)+'</span><span class="step-title">'+esc(titles[s.key]||s.title)+'</span><span class="step-state">'+esc(skip?'已跳过':done?'已完成':stateLabels[s.state]||(current?(choice?'等待选择':p.progress.phase):r.terminal?'本次未执行':'等待前序步骤'))+'</span></div>'+(current?'<div class="step-body">'+body+'</div>':done||skip?'<details class="completed-detail"><summary>查看结果</summary><p>'+esc(skip?'本次未执行此步骤。':s.evidence?JSON.stringify(s.evidence):'结果来自本次操作记录')+'</p></details>':'')+'</li>';
45
+ }).join('');
46
+ }
47
+ if(busy&&executing){const live=q('.current .step-state');if(live)live.textContent='正在执行';}
48
+ q('#flow-result').hidden=!r.terminal;
49
+ if(r.terminal)q('#flow-result').innerHTML='<h2>'+esc(r.state==='completed'?verb+'完成':'部分完成 / 待核实')+'</h2><p>'+esc(p.progress.program)+'</p><p>Skill:'+esc(p.progress.skill)+'</p><p>项目:'+esc(p.progress.project)+'</p><p class="hint">下一步:'+esc(p.progress.next)+'</p>';
50
+ const safe=JSON.parse(JSON.stringify(p));if(safe.view){delete safe.view.managerNonce;delete safe.view.nonce;}q('#raw').textContent=JSON.stringify(safe,null,2);
51
+ }
52
+ document.addEventListener('submit',async e=>{if(e.target.id!=='current-form')return;e.preventDefault();if(busy||!last)return;busy=true;const form=e.target;form.querySelectorAll('button').forEach(b=>b.disabled=true);q('#flow-status').textContent='正在提交请求';const action=e.submitter.value,v=last.view;const body={csrf,operationId:last.record.operationId,action,...(['choose','select'].includes(action)?{destination:form.elements.destination.value,skillChoice:form.elements.includeSkill.checked?'selected':'skipped'}:{managerNonce:v?.managerNonce,sessionId:v?.session?.sessionId,planHash:v?.session?.planHash})};
53
+ try{const response=await fetch(location.pathname+'/action',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});const result=await response.json();if(!response.ok){q('#step-error').textContent=result.message||result.code||'本步未完成,请核实';busy=false;form.querySelectorAll('button').forEach(b=>b.disabled=false);return;}busy=false;revision=null;await refresh();}catch{q('#connection').textContent='请求结果待核实,不自动重试。已收到的结果保留;刷新查询同次流程。';}});
54
+ async function refresh(){try{const response=await fetch(location.pathname+'/state');if(!response.ok)throw Error();show(await response.json());q('#connection').textContent='';}catch{q('#connection').textContent=last?.record?.terminal?'结果服务已结束,上方保留最后核实结果。可在对话中按本次操作记录再次查询。':'连接已中断,保留最后核实结果;不自动重试操作。';}}
55
+ async function poll(){if(stopped)return;await refresh();if(!stopped)setTimeout(poll,750);}poll();window.addEventListener('pagehide',()=>{stopped=true},{once:true});
56
+ }
@@ -6,9 +6,9 @@ import {plainPath} from './acquire.mjs';
6
6
  // Coordinates existing exact-plan APIs. It never sends a confirmation request.
7
7
  // The installed launcher resolves current on every call; downloaded code is not
8
8
  // reused as installed authority. onChange is observation, not authorization.
9
- export async function followSelectedSkill({operation,env,onChange}) {
9
+ export async function followSelectedSkill({operation,env,onChange,journeyControl=null}) {
10
10
  if(operation.programState!=='completed'||operation.journeyContext?.skillChoice!=='selected')throw Error('Skill 接续需要已完成程序和明确所选意向');
11
- const client=installedClient(operation.installationRoot,env),{root,call}=client;
11
+ const client=installedClient(operation.installationRoot,env,journeyControl),{root,call}=client;
12
12
  const initial=call(['manager','inspect','--root',root]);
13
13
  const identity=initial.installation?.current;
14
14
  if(!identity?.identity?.installId||initial.bridge?.currentVersion!==identity.version)throw Error('当前安装身份无法核实,停止 Skill 接续');
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@josephyulei/summon-foundation",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@josephyulei/summon-foundation",
9
- "version": "0.1.5",
9
+ "version": "0.1.6",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@sigstore/bundle": "4.0.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@josephyulei/summon-foundation",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "Prepare a verified Foundation release for an explicitly confirmed Codex installation",
5
5
  "type": "module",
6
6
  "bin": {"summon": "bin/summon.mjs"},