@josephyulei/summon-foundation 0.1.5 → 0.1.7

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,29 @@
1
1
  # summon foundation
2
2
 
3
- 0.1.5 配合 Foundation 0.2.11。选中 Skill 后由程序接续精确确认;`--update --root <安装根> --version <固定版本>`、`--uninstall --root <安装根>` 组织维护步骤。`--resume <同次结果文件>` 仅恢复程序成功后的所选 Skill,不重装或重放批准。
3
+ 本轮修订包含真实下载状态、专用入口环境和项目范围;以 registry 中本版本实际存在为执行前提。基础环境不能安全启动页面时,由 Codex 对话先披露并取得独立批准,再准备专用环境;页面启动后全程同页。具体方法见仓库 `docs/install-with-codex.md`,不能先运行 npx 来准备缺失的 Node。不修改共享 PATH;获取器专用环境及其回执按缓存保留,程序另用随包运行时。发行发现仅需 curl,获取还需 tar;已验证载荷的确认、恢复和卸载不依赖下载工具。
4
4
 
5
- 0.1.5 提供获取期间只读进度页。获取成功后同一页面关联运行程序返回的目录/确认页,仍由 Codex 内置浏览器打开;配合 Foundation 0.2.11 展示本次流程、当前目标和剩余动作。临时服务只随本次任务运行,不是守护进程,不执行未核验归档,也不替本人确认。原操作回执仍可独立只读查询,页断开不改写已核实终态。
5
+ 0.1.7 单页试用入口与 Foundation 0.2.12 起的运行引擎共同支持同一页面内的目录选择、程序和 Skill 独立确认;旧发行版本不具备本次单页修订。真实安装、新任务发现和主动告知仍需独立验收。
6
+
7
+ 首次 URL 持续显示本次流程;确认仅转交本次受控子进程的当前计划,不新开manager页。--acquire仍只读获取;--resume仅在用户明确要求后恢复未完成Skill,不重放程序安装。
6
8
 
7
9
  Foundation 的薄获取入口,不包含完整运行包,没有 npm 安装生命周期脚本。
8
10
  只有明确执行才查询/获取;安装和 Skill 注册继续各自需要用户确认。
9
11
 
10
12
  可用性以 npm registry 的实际版本和公共 GitHub Release 为准;本目录或说明存在不是发布回执。只使用本项目已核验的包名,缺包时不换同名来源。
11
13
 
14
+ 确认 registry 中存在本版本及对应不可变 Release 后,在具备安装权限的新 Codex 对话粘贴:
15
+
12
16
  ```text
13
- npx --yes --package @josephyulei/summon-foundation@0.1.5 summon foundation
17
+ npx --yes --package @josephyulei/summon-foundation@0.1.7 summon foundation
14
18
  ```
15
19
 
16
- 0.1.5 入口配合 Foundation 0.2.11 正式发行使用。默认命令实际查询、固定版本、披露缓存、下载并校验,然后保持运行等待安装页目录选择。选择目录后还要亲自确认精确安装计划;不会自动注册 Skill 或接入项目。实际获取仍须通过 registry 与 Release 校验,本文不替代发布证明。
20
+ 旧版退出推荐入口;支持边界见[现行支持策略](https://github.com/y15801172513-lang/foundation/blob/main/docs/install-platform-024.md#现行支持策略)。旧不可变版本不修改,不自动迁移或清除旧安装。
17
21
 
18
22
  Codex 需要打开返回的内置浏览器网址,并分段等待同次操作结果。npm 不能自行操控或唤醒 Codex,对话主动告知不是程序退出码保证;新对话接续仍待真人验收。系统浏览器只是明确告知后的备用,不自动打开。
19
23
 
20
- 0.1.3 的程序收尾:联网前建立同次操作记录,输出阶段、大文件实际字节/总量、尝试次数与最近进展;不能保存早期记录则不开始联网。大文件每次最多 10 分钟,连接 15 秒、低速 60 秒有界停止,仅暂时网络错误可重试一次。失败保留 curl 退出码和脱敏类别,校验失败与网络失败分开。`--status <返回的结果文件>` 只读恢复,不获取、安装或重试;中间记录不证明进程仍在运行。新运行版安装后程序核验稳定入口,启动唯一工作台至就绪便返回结果,不等常驻工作台退出;Codex 打开返回的实际网址并解释结果。旧 0.1.2 不含上述修复。工具返回 running 不是任务完成,运行中的 Codex 应继续观察原句柄;程序无法强制宿主不提前结束,新对话无追问反馈仍待验证。
24
+ 联网前建立操作记录,网络失败保留脱敏类别和退出码;--status只读恢复同次结果,不重试或重放。程序健康核验后结果留在本页,工作台由用户另行打开。工具yield不是任务完成,Codex须继续分段观察;HTML不能唤醒已结束任务。
21
25
 
22
- 显式 `--inspect` 才只查询,不下载运行文件。已有选择时可用 `--prepare --version <固定版本> --destination <绝对目录>`;`--acquire --version <固定版本>` 只准备更新输入,不执行更新。更新使用已安装稳定入口。旧运行版不支持页面选择时拒绝自动采用默认目录。没有 npm 时先从 GitHub 安装说明检查环境,不自动安装全局依赖。
26
+ 显式 --inspect 只查询发行。默认命令先在页面选择目录与Skill意向,再下载核验;最终精确计划仍需本人确认。--prepare传入的目录只是意向;--acquire只准备更新输入。更新/卸载仅使用支持单页的已安装稳定入口,不回退旧页面。
23
27
 
24
28
  需要 macOS arm64、Node.js 22.9+ 与 npm。无 TTY 不会卡在终端提问;目录选择在页面进行,关闭页面不算确认或取消。
25
29
  固定版本准备阶段匿名校验 GitHub 仓库身份、不可变 Release、签名证明、时间戳、源码提交和资产字节,随后使用随包运行时进入现有 Foundation 确认页面。
@@ -0,0 +1,51 @@
1
+ #!/bin/sh
2
+ # C6: bootstrap the npm entry, not Foundation itself. No Node/npm is needed
3
+ # to inspect this plan. Keep pins aligned with official-node-runtime.mjs.
4
+ set -eu
5
+ umask 077
6
+ fail(){ printf '错误:%s\n' "$1" >&2; exit 1; }
7
+ version=24.14.1
8
+ archive_hash=25495ff85bd89e2d8a24d88566d7e2f827c6b0d3d872b2cebf75371f93fcb1fe
9
+ node_hash=35d4bc736bbe4161f0c074aa140ddb74586e46969bc2ad63d32c838bec4463ff
10
+ license_hash=4573185d56580da2b890ba34a85a409257640f1c5632eade4300137266194d18
11
+ url=https://nodejs.org/dist/v24.14.1/node-v24.14.1-darwin-arm64.tar.gz
12
+ prefix=node-v24.14.1-darwin-arm64
13
+ mode=${1:-}; destination=${2:-}; approval=${3:-}
14
+ [ "$#" -ge 2 ] && [ "$#" -le 3 ] || fail '用法:sh prepare-environment.sh --inspect /绝对独立目录;本人批准后以 --prepare 同一路径 精确计划摘要执行'
15
+ case "$mode" in --inspect|--prepare) ;; *) fail '仅支持查看计划或按批准准备环境' ;; esac
16
+ case "$destination" in /*) ;; *) fail '环境位置必须是绝对路径' ;; esac
17
+ case "$destination" in *'
18
+ '*|*'/../'*|*'/./'*|*/|'/') fail '环境位置必须是规范化独立目录' ;; esac
19
+ [ "$(/usr/bin/uname -s)" = Darwin ] && [ "$(/usr/bin/uname -m)" = arm64 ] || fail '此设备暂不支持;不会通过准备环境绕过平台限制'
20
+ for tool in /usr/bin/curl /usr/bin/tar /usr/bin/shasum /usr/bin/stat /bin/mkdir /bin/chmod; do [ -x "$tool" ] || fail "缺少可信系统工具:$tool"; done
21
+ parent=${destination%/*}; [ -n "$parent" ] || fail '不能写系统根目录'
22
+ [ -d "$parent" ] && [ -w "$parent" ] && [ -x "$parent" ] || fail '父目录不存在或无权限;不会代建系统目录'
23
+ [ "$(CDPATH= cd -- "$parent" && pwd -P)" = "$parent" ] || fail '父目录含链接或非规范路径'
24
+ cursor=$parent
25
+ while [ "$cursor" != / ]; do [ ! -L "$cursor" ] || fail '拒绝符号链接祖先'; cursor=${cursor%/*}; [ -n "$cursor" ] || cursor=/; done
26
+ [ ! -e "$destination" ] && [ ! -L "$destination" ] || fail '目标已经存在;保留已有或失败材料,请核验后选择新的独立目录'
27
+ parent_identity=$(/usr/bin/stat -f '%d:%i:%u:%Lp' "$parent")
28
+ plan=$(printf 'foundation-entry-environment-v1\n%s\n%s\n%s\n%s\n%s\nno-shared-settings\n' "$version" "$destination" "$parent_identity" "$url" "$archive_hash" | /usr/bin/shasum -a 256)
29
+ plan=${plan%% *}
30
+ printf '基础环境计划:Node.js %s(含 npm),仅用于启动获取器\n来源:%s\n位置:%s\n影响:不修改现有 Node、Shell、PATH 或系统设置;不安装 Foundation、不注册 Skill\n保留:失败材料和环境回执;不自动清理\n计划摘要:%s\n' "$version" "$url" "$destination" "$plan"
31
+ [ "$mode" = --prepare ] || exit 0
32
+ [ -n "$approval" ] && [ "$approval" = "$plan" ] || fail '缺少匹配的本人批准计划摘要;没有准备环境'
33
+ # The invoking Codex task must obtain human approval for the displayed plan.
34
+ # This argument binds that request; it is not evidence of a UI confirmation.
35
+ [ "$(CDPATH= cd -- "$parent" && pwd -P)" = "$parent" ] && [ "$(/usr/bin/stat -f '%d:%i:%u:%Lp' "$parent")" = "$parent_identity" ] || fail '父目录在批准后变化;没有准备环境'
36
+ /bin/mkdir -m 700 -- "$destination" || fail '创建独占环境目录失败'
37
+ printf 'state=preparing\nplan=%s\nsource=%s\narchive_sha256=%s\nshared_settings_changed=false\n' "$plan" "$url" "$archive_hash" > "$destination/environment-result.txt"
38
+ trap 'printf "state=failed-or-interrupted\n" >> "$destination/environment-result.txt"' EXIT
39
+ /usr/bin/curl -q --fail --silent --show-error --location --max-redirs 3 --proto '=https' --proto-redir '=https' --connect-timeout 15 --max-time 600 --max-filesize 134217728 -o "$destination/node.tar.gz" "$url" || fail '官方环境下载失败;保留材料,不执行'
40
+ observed=$(/usr/bin/shasum -a 256 "$destination/node.tar.gz"); [ "${observed%% *}" = "$archive_hash" ] || fail '官方环境归档摘要不匹配'
41
+ /usr/bin/tar -xzpf "$destination/node.tar.gz" --no-same-owner --no-acls --no-fflags --no-mac-metadata --no-xattrs -C "$destination" || fail '已验证归档解包失败'
42
+ node="$destination/$prefix/bin/node"
43
+ [ -f "$node" ] && [ ! -L "$node" ] && [ -x "$node" ] || fail '缺少绑定运行时'
44
+ observed=$(/usr/bin/shasum -a 256 "$node"); [ "${observed%% *}" = "$node_hash" ] || fail '运行时字节不符'
45
+ observed=$(/usr/bin/shasum -a 256 "$destination/$prefix/LICENSE"); [ "${observed%% *}" = "$license_hash" ] || fail '许可字节不符'
46
+ unset NODE_OPTIONS NODE_PATH NODE_V8_COVERAGE NODE_REDIRECT_WARNINGS NODE_COMPILE_CACHE NODE_COMPILE_CACHE_PORTABLE NODE_PRESERVE_SYMLINKS
47
+ [ "$("$node" --version)" = "v$version" ] || fail '环境准备后版本复检失败'
48
+ [ -f "$destination/$prefix/lib/node_modules/npm/bin/npm-cli.js" ] || fail '官方环境缺少 npm 入口'
49
+ printf 'state=prepared-and-rechecked\nnode_version=%s\nnode_sha256=%s\nnode=%s\nnpm_cli=%s\n' "$version" "$node_hash" "$node" "$destination/$prefix/lib/node_modules/npm/bin/npm-cli.js" >> "$destination/environment-result.txt"
50
+ trap - EXIT
51
+ printf '基础环境已准备并复检。由当前任务以此 Node 和 npm 入口启动已固定版本的 Foundation 单页;不要更改全局 PATH。\n回执:%s/environment-result.txt\n' "$destination"
package/bin/summon.mjs CHANGED
@@ -8,9 +8,12 @@ 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';
16
+ import {inspectEntryEnvironment} from '../lib/environment-check.mjs';
14
17
 
15
18
  const help=`summon foundation [--version x.y.z] [--destination /absolute/folder]
16
19
  summon foundation --inspect [--version x.y.z]
@@ -48,55 +51,55 @@ function stageDirectory(){
48
51
  return fs.mkdtempSync(path.join(cache,'acquisition.'));
49
52
  }
50
53
  let operation=null,stage=null,progressPage=null;
54
+ const journeyControl=createJourneyControl(()=>operation,patch=>patch?updateOperation(patch):progressPage?.publish());
51
55
  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
56
  try{
70
57
  const args=parseSummonArgs(process.argv.slice(2));
71
58
  if(args.help){console.log(help);process.exit(0);}
72
59
  if(args.status){console.log(JSON.stringify(readOperation(args.status),null,2));process.exit(0);}
73
- const [major,minor]=process.versions.node.split('.').map(Number);
74
- if(major<22||(major===22&&minor<9))fail('获取入口需要 Node.js 22.9 或以上;尚未安装,不自动安装依赖');
75
- if(process.platform!=='darwin'||process.arch!=='arm64')fail('当前仅支持 macOS arm64;尚未安装');
60
+ const initialEnvironment=inspectEntryEnvironment({purpose:args.uninstall?'uninstall':args.resume?'resume':args.inspect?'discover':'acquire'});
61
+ if(!initialEnvironment.supported||!initialEnvironment.compatible){
62
+ operation=createOperation();updateOperation({phase:'checking-environment',environment:initialEnvironment});
63
+ fail(!initialEnvironment.supported?'当前仅支持 macOS arm64;尚未安装':'获取入口需要 Node.js 22.9 或以上;当前入口不能安全承诺同页准备,请按安装说明在对话中先确认独立基础环境,不自动安装依赖');
64
+ }
76
65
  const maintenance=args.update||args.uninstall;
77
66
  if(args.prepare||args.acquire||maintenance||args.resume)sourceGuard();
78
- if(args.prepare||args.acquire||maintenance){operation=createOperation();stage=stageDirectory();updateOperation({});if(!saveOperation(operation,stage))fail('无法在已披露的获取目录保存操作记录;尚未联网或安装');}
67
+ if(args.prepare||args.acquire||maintenance){operation=createOperation();Object.assign(operation,{phase:'checking-environment',environment:initialEnvironment});stage=stageDirectory();updateOperation({});if(!saveOperation(operation,stage))fail('无法在已披露的获取目录保存操作记录;尚未联网或安装');}
79
68
  if(args.prepare)console.log('正在准备 Foundation 安装:将查询并固定本次正式版本,说明缓存位置后下载核验。未选目录会在安装页选择;之后仍需本人确认精确计划。请保持当前 Codex 任务等待并打开返回的内置浏览器网址;不会自动改用系统浏览器。');
80
69
  if(args.resume){
70
+ operation=readOperation(args.resume);stage=path.dirname(plainPath(args.resume));
71
+ updateOperation({environment:initialEnvironment});
72
+ if(initialEnvironment.state!=='ready')fail('恢复所需环境无法核实;保留已有安装和操作记录');
73
+ progressPage=await startProgressPage(()=>operation,{control:journeyControl});
74
+ console.log(JSON.stringify({status:'FOUNDATION_SINGLE_PAGE',url:progressPage.url,operationId:operation.operationId}));
81
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];
82
- const result=await resumeSkillHandoff({file:args.resume,env,onChange:patch=>{if(!operation){operation=patch;stage=path.dirname(plainPath(args.resume));}updateOperation(patch);}});
76
+ const result=await resumeSkillHandoff({file:args.resume,env,journeyControl,onChange:updateOperation});
83
77
  updateOperation(result);process.exitCode=result.state==='completed'?0:1;
84
78
  }else if(maintenance){
85
79
  plainPath(args.root);
86
80
  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});
81
+ const installed=installedClient(args.root,env),current=installed.call(['manager','inspect','--root',args.root]).installation?.current;
82
+ if(!current?.identity?.installId)fail('当前安装身份无法核实;尚未获取或执行维护');
83
+ const capability=spawnSync(installed.launcher,['--help'],{encoding:'utf8',env,timeout:15000});
84
+ if(capability.status!==0||!capability.stdout.includes('--journey-channel'))fail('当前安装不受新版单页流程支持。请另行确认卸载旧版并重新安装新版;本次不删除、不迁移、不回退旧页面');
85
+ const environment=inspectEntryEnvironment({purpose:args.update?'acquire':'uninstall'});
86
+ updateOperation({kind:args.update?'update':'uninstall',installationRoot:args.root,currentVersion:current.version,installId:current.identity.installId,environment,usageScope:current.usageScope||{kind:'user',project:null}});
87
+ progressPage=await startProgressPage(()=>operation,{control:journeyControl});updateOperation({progressUrl:progressPage.url});
88
+ console.log(JSON.stringify({status:'FOUNDATION_SINGLE_PAGE',url:progressPage.url,operationId:operation.operationId}));
89
+ if(environment.state!=='ready')fail('环境复检未通过:'+environment.state+';缺少 '+environment.missing.join('、')+';保留当前安装,不修改系统工具');
89
90
  let candidate;
90
91
  if(args.update){
91
- 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
+ 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,...(phase==='fetching-and-verifying-runtime'?{download:null}:{})})});
92
93
  const directory=plainPath(path.dirname(receipt.launcher)),manifest=JSON.parse(fs.readFileSync(plainPath(path.join(directory,'manifest.json'))));
93
94
  if(manifest.productVersion!==context.version)fail('获取版本与候选不一致');
94
95
  candidate={path:directory,manifestHash:manifest.candidateHash,version:manifest.productVersion,bytes:manifest.totalBytes,runtimeHash:manifest.files.find(f=>f.path===manifest.runtime.path)?.sha256};
96
+ updateOperation({phase:'acquired'});
95
97
  }
96
- updateOperation(await followMaintenance({operation,kind:operation.kind,candidate,env,onChange:updateOperation}));
98
+ updateOperation(await followMaintenance({operation,kind:operation.kind,candidate,env,onChange:updateOperation,journeyControl}));
97
99
  process.exitCode=operation.state==='completed'?0:1;
98
100
  await progressPage.close();progressPage=null;
99
101
  }else if(!args.prepare&&!args.acquire){
102
+ if(initialEnvironment.state!=='ready'){operation=createOperation();updateOperation({phase:'checking-environment',environment:initialEnvironment});fail('发行查询所需环境无法核实;尚未联网');}
100
103
  const context=inspectRelease(args.version);
101
104
  const guide=`https://github.com/${context.repository.full_name}/blob/${context.documentationCommit}/docs/install-with-codex.md`;
102
105
  console.log(JSON.stringify({schemaVersion:'1.0.0',status:'RELEASE_DISCOVERED_NOT_ACQUIRED',product:'Foundation',version:context.version,sourceCommit:context.sourceCommit,documentationCommit:context.documentationCommit,repository:context.repository.full_name,guide,installationPerformed:false,skillRegistered:false,
@@ -104,24 +107,32 @@ try{
104
107
  terminalBoundary:'普通终端无法创建或唤醒 Codex 对话;请在有相应权限的 Codex 任务发起安装。',
105
108
  acquisition:'尚未下载或验证运行归档。默认入口或 --prepare 执行匿名 GitHub 证明与完整性核验。'},null,2));
106
109
  }else{
107
- if(args.destination)plainPath(args.destination);console.log(`本次独占获取目录:${stage}`);
108
- progressPage=await startProgressPage(()=>operation);
110
+ console.log(`本次独占获取目录:${stage}`);
111
+ progressPage=await startProgressPage(()=>operation,args.acquire?{}:{control:journeyControl});
109
112
  updateOperation({progressUrl:progressPage.url});
110
- console.log(JSON.stringify({status:'FOUNDATION_ACQUISITION_PROGRESS_PAGE',url:progressPage.url,operationId:operation.operationId,next:'在 Codex 内置浏览器打开同次只读进度页,保持任务等待;不会自动打开系统浏览器。'}));
111
- 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}));
113
+ console.log(JSON.stringify({status:'FOUNDATION_ACQUISITION_PROGRESS_PAGE',url:progressPage.url,operationId:operation.operationId,next:'在 Codex 内置浏览器打开本次页面,所有所需确认在原页展开;保持任务等待,不自动打开系统浏览器。'}));
114
+ const environment=inspectEntryEnvironment({purpose:'acquire'});updateOperation({phase:'checking-environment',environment});
115
+ if(environment.state!=='ready')fail('获取环境检查未通过:'+environment.state+';缺少 '+environment.missing.join('、')+';不会以安装 Node 替代缺失的系统工具');
116
+ if(!args.acquire){
117
+ const metadata=inspectRelease(args.version);args.version=metadata.version;
118
+ updateOperation({phase:'choosing-intent',environment,version:metadata.version,sourceCommit:metadata.sourceCommit,acquisitionRoot:stage,destinationIntent:args.destination||'',journeyContext:{id:operation.operationId,skillChoice:'undecided'}});
119
+ const choice=await journeyControl.waitChoice();
120
+ updateOperation({phase:'discovering',intentSelected:true,destinationIntent:choice.destination,scopeIntent:{kind:choice.scopeKind,projectRoot:choice.projectRoot},destinationCheck:choice.destinationCheck,journeyContext:{id:operation.operationId,skillChoice:choice.skillChoice}});
121
+ }
122
+ 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,...(phase==='fetching-and-verifying-runtime'?{download:null}:{})})});console.log(JSON.stringify({status:'GITHUB_ACQUISITION_VERIFIED',...receipt,destinationIntent:args.destination}));
112
123
  updateOperation({phase:'acquired',version:context.version,sourceCommit:context.sourceCommit});
113
124
  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
125
  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
126
  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
- }
127
+ if(supported.status!==0||!supported.stdout.includes('--journey-channel'))fail('该发行不支持新版单页流程;未安装,不回退旧页面。请使用支持单页的新版发行');
119
128
  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});
129
+ const child=spawn(receipt.launcher,['install','--journey-id',operation.operationId,'--choose-destination','--journey-channel','--browser','codex'],{stdio:['inherit','pipe','inherit','ipc'],env});
130
+ journeyControl.attach(child);
121
131
  child.stdout.setEncoding('utf8');
122
132
  let pending='',json='';
123
133
  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
134
  const observed=runtimeObservation(e);if(observed)updateOperation(observed);
135
+ journeyControl.observe(child,e).catch(error=>{updateOperation({state:'verification-required',terminal:true,next:error.message});child.kill('SIGTERM');});
125
136
  }});
126
137
  const interrupt=signal=>{child.kill(signal);};
127
138
  const int=()=>interrupt('SIGINT'),term=()=>interrupt('SIGTERM');
@@ -129,14 +140,10 @@ try{
129
140
  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
141
  if(ended.signal||ended.code===null)fail(`确认服务未正常返回;结果待核实,保留 ${stage},不要自动重试安装`);
131
142
  if(operation.state==='awaiting-skill'){
132
- try{updateOperation(await followSelectedSkill({operation,env,onChange:updateOperation}));}
143
+ try{updateOperation(await followSelectedSkill({operation,env,onChange:updateOperation,journeyControl}));}
133
144
  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
145
  }
135
146
  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
147
  process.exitCode=operation.state==='partial'?1:ended.code;
141
148
  }
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();}
149
+ }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();}
package/lib/acquire.mjs CHANGED
@@ -91,9 +91,10 @@ async function trustRoot(stage) {
91
91
  await updater.refresh();const info=await updater.getTargetInfo('trusted_root.json');if(!info)fail('GitHub 信任目标缺失');
92
92
  return json(fs.readFileSync(await updater.downloadTarget(info)));
93
93
  }
94
- async function verifiedAsset(context,asset,stage,trust,onProgress) {
94
+ async function verifiedAsset(context,asset,stage,trust,onProgress=()=>{},onDownloaded=()=>{}) {
95
95
  if(!asset||!Number.isSafeInteger(asset.size)||asset.size<=0||asset.size>250_000_000||!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(asset.name)||!/^sha256:[a-f0-9]{64}$/.test(asset.digest)||asset.browser_download_url!==`https://github.com/${policy.repository}/releases/download/${context.release.tag_name}/${asset.name}`)fail('资产元数据无效');
96
- const bytes=asset.size>10_000_000?await downloadLarge(asset.browser_download_url,asset.size,onProgress):download(asset.browser_download_url,asset.size+1);
96
+ const bytes=asset.size>10_000_000?await downloadLarge(asset.browser_download_url,asset.size,p=>onProgress({...p,asset:asset.name})):download(asset.browser_download_url,asset.size+1);
97
+ onDownloaded();
97
98
  if(bytes.length!==asset.size||`sha256:${hash(bytes)}`!==asset.digest)fail('下载长度或摘要不匹配');
98
99
  const proofs=api(`attestations/${asset.digest}?predicate_type=release&per_page=100`).attestations;
99
100
  if(!Array.isArray(proofs)||proofs.length>=100)fail('证明列表不完整或分页待核实');
@@ -152,7 +153,7 @@ export async function acquireRelease(context,stage,{onPhase=()=>{},onProgress=()
152
153
  if(release.repositoryId!==policy.repositoryId||release.sourceCommit!==context.sourceCommit||!/^[a-f0-9]{64}$/.test(release.candidateHash)||release.url!==`https://github.com/${policy.repository}/releases/download/${context.release.tag_name}/${assetName}`||!/^\d+\.\d+\.\d+$/.test(release.runtime?.version)||release.runtime.url!==`https://nodejs.org/dist/v${release.runtime.version}/node-v${release.runtime.version}-darwin-arm64.tar.gz`)fail('清单不能更换仓库、提交或官方运行时来源');
153
154
  const assets=context.release.assets.filter(x=>x.name===assetName&&x.size===release.bytes&&x.digest===`sha256:${release.sha256}`);if(assets.length!==1)fail('归档身份不匹配');
154
155
  onPhase('fetching-and-verifying-runtime');
155
- const archive=await verifiedAsset(context,assets[0],stage,trust,onProgress);
156
+ const archive=await verifiedAsset(context,assets[0],stage,trust,onProgress,()=>onPhase('verifying-runtime'));
156
157
  onPhase('extracting-and-validating');
157
158
  const listing=spawnSync('/usr/bin/tar',['-tzf',archive.file],{encoding:'utf8',maxBuffer:10_000_000});
158
159
  const types=spawnSync('/usr/bin/tar',['-tvzf',archive.file],{encoding:'utf8',maxBuffer:10_000_000});
@@ -7,7 +7,7 @@ export function acquireInWorker({version,stage,operationId,onContext=()=>{},onPh
7
7
  const interrupt=()=>{failure=Object.assign(Error('获取任务被中断;保留本次材料'),{code:'ACQUISITION_INTERRUPTED'});void worker.terminate();};
8
8
  process.once('SIGINT',interrupt);process.once('SIGTERM',interrupt);
9
9
  worker.on('message',event=>{
10
- if(event.type==='context'){context=event.context;onContext(context);}
10
+ if(event.type==='context'){context=event.context;onContext(context);worker.postMessage({type:'context-recorded'});}
11
11
  else if(event.type==='phase')onPhase(event.phase);
12
12
  else if(event.type==='progress')onProgress(event.download);
13
13
  else if(event.type==='complete')receipt=event.receipt;
@@ -5,7 +5,14 @@ import {inspectRelease, acquireRelease} from './acquire.mjs';
5
5
 
6
6
  try {
7
7
  const context = inspectRelease(workerData.version);
8
+ // The parent persists context atomically in the stage. Finish that write
9
+ // before checking that the stage contains only this operation's record.
10
+ const recorded = new Promise(resolve=>parentPort.once('message',message=>{
11
+ if(message.type!=='context-recorded')throw Error('获取上下文确认无效');
12
+ resolve();
13
+ }));
8
14
  parentPort.postMessage({type:'context',context});
15
+ await recorded;
9
16
  const receipt = await acquireRelease(context, workerData.stage, {
10
17
  operationId:workerData.operationId,
11
18
  onPhase:phase=>parentPort.postMessage({type:'phase',phase}),
@@ -0,0 +1,56 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import {spawnSync} from 'node:child_process';
4
+ import crypto from 'node:crypto';
5
+ import {plainPath} from './acquire.mjs';
6
+
7
+ export function classifyEntryEnvironment({platform,arch,nodeVersion,tools}){
8
+ const [major,minor]=String(nodeVersion||'').split('.').map(Number);
9
+ const supported=platform==='darwin'&&arch==='arm64';
10
+ const compatible=Number.isInteger(major)&&Number.isInteger(minor)&&(major>22||major===22&&minor>=9);
11
+ const missing=tools.filter(x=>!x.available).map(x=>x.path);
12
+ return{platform,arch,nodeVersion,supported,compatible,tools,state:!supported?'unsupported':!compatible?'environment-required':missing.length?'blocked':'ready',missing,sharedSettingsChanged:false};
13
+ }
14
+ export function inspectEntryEnvironment({purpose='acquire'}={}){
15
+ // Hash/proof verification uses Node crypto. System shasum belongs only to the
16
+ // no-Node preparation script, not an npm action or installed confirmation.
17
+ const requirements={discover:['/usr/bin/curl'],acquire:['/usr/bin/curl','/usr/bin/tar'],confirm:[],uninstall:[],resume:[]};
18
+ if(!Object.hasOwn(requirements,purpose))throw Error('未知环境检查动作');
19
+ const tools=requirements[purpose].map(file=>{let available=false;try{fs.accessSync(file,fs.constants.X_OK);available=fs.statSync(file).isFile();}catch{}return{path:file,available};});
20
+ const result={...classifyEntryEnvironment({platform:process.platform,arch:process.arch,nodeVersion:process.versions.node,tools}),purpose,entryRuntime:process.execPath,checkedAt:new Date().toISOString(),programRuntime:'随程序携带,不替换现有 Node'};
21
+ const receipt=path.resolve(path.dirname(process.execPath),'../..','environment-result.txt');
22
+ try{if(fs.existsSync(receipt)){
23
+ plainPath(receipt);const stat=fs.lstatSync(receipt);if(!stat.isFile()||stat.size>65536)throw Error('基础环境回执异常,保留并核实');
24
+ const fields=Object.fromEntries(fs.readFileSync(receipt,'utf8').trim().split('\n').map(line=>{const i=line.indexOf('=');return[line.slice(0,i),line.slice(i+1)];}));
25
+ const hash=crypto.createHash('sha256').update(fs.readFileSync(process.execPath)).digest('hex');
26
+ if(fields.state!=='prepared-and-rechecked'||fields.node!==process.execPath||fields.node_sha256!==hash||fields.node_version!==process.versions.node)throw Error('基础环境回执与当前运行文件不一致,不继续');
27
+ result.preparation={receipt,plan:fields.plan,state:fields.state,humanApproval:'由启动任务核验,本记录不是人类批准证明',retention:'获取器专用环境保留为缓存,不自动清理;不属于程序安装根'};
28
+ }}catch{result.state='blocked';result.preparation={receipt,state:'verification-required',reason:'基础环境回执与当前运行文件无法核实;保留材料,不继续'};}
29
+ return result;
30
+ }
31
+ export function inspectEntryDestination(input){
32
+ let destination=String(input||'').trim();
33
+ if((destination.startsWith('"')&&destination.endsWith('"'))||(destination.startsWith("'")&&destination.endsWith("'")))destination=destination.slice(1,-1);
34
+ plainPath(destination);
35
+ if(fs.existsSync(destination)&&(!fs.lstatSync(destination).isDirectory()||fs.readdirSync(destination).length))throw Error('安装目录已有内容或不是目录;请选择独立空目录,不覆盖已有文件');
36
+ const parent=path.dirname(destination);plainPath(parent);if(!fs.existsSync(parent)||!fs.lstatSync(parent).isDirectory())throw Error('安装目录的父目录必须存在');
37
+ fs.accessSync(parent,fs.constants.W_OK|fs.constants.X_OK);
38
+ const disk=fs.statfsSync(parent),availableBytes=Number(disk.bavail)*Number(disk.bsize);
39
+ if(!Number.isFinite(availableBytes)||availableBytes<=0)throw Error('无法确认可用空间;尚未下载或安装');
40
+ return{destination,parent,availableBytes,checkedAt:new Date().toISOString(),authority:'intent-only; runtime rechecks exact bytes and plan'};
41
+ }
42
+
43
+ // Intent preflight only. The installed engine repeats identity checks and seals
44
+ // the actual scope in the independently confirmed lifecycle plan.
45
+ export function inspectScopeIntent(kind, input, destination){
46
+ if(kind==='user')return {kind,projectRoot:null};
47
+ if(kind!=='project'||typeof input!=='string')throw Error('请选择有效的使用范围');
48
+ let projectRoot=input.trim();
49
+ if((projectRoot.startsWith('"')&&projectRoot.endsWith('"'))||(projectRoot.startsWith("'")&&projectRoot.endsWith("'")))projectRoot=projectRoot.slice(1,-1);
50
+ plainPath(projectRoot);
51
+ if(!fs.lstatSync(projectRoot).isDirectory())throw Error('项目根不是已有目录');
52
+ const git=spawnSync('/usr/bin/git',['-C',projectRoot,'rev-parse','--show-toplevel'],{encoding:'utf8',env:{PATH:'/usr/bin:/bin',GIT_OPTIONAL_LOCKS:'0'},timeout:10000});
53
+ if(git.status!==0||git.stdout.trim()!==projectRoot)throw Error('仅当前项目模式需要明确的 Git 仓库根;不会自动创建仓库');
54
+ if(destination===projectRoot||destination.startsWith(projectRoot+path.sep)||projectRoot.startsWith(destination+path.sep))throw Error('程序目录不能与业务项目互相包含;请选择独立目录');
55
+ return {kind,projectRoot};
56
+ }
@@ -0,0 +1,83 @@
1
+ import crypto from 'node:crypto';
2
+ import {inspectEntryDestination,inspectScopeIntent,inspectEntryEnvironment} from './environment-check.mjs';
3
+
4
+ // Legacy engines already mean user scope. Do not send new keys to their strict
5
+ // selection parser; project scope must remain explicit and may never downgrade.
6
+ const scopeFields=value=>value.scopeKind==='project'?{scopeKind:'project',projectRoot:value.projectRoot}:{};
7
+
8
+ // Only the exact child created by this invocation may supply an active view.
9
+ // Browser input cannot name a URL, route, transport token or future plan.
10
+ export function createJourneyControl(readRecord, changed) {
11
+ const children=new Map();let active=null,origin=null,choice=null,resolveChoice,rejectChoice,choiceTimer,viewRevision=0;
12
+ const headers=owner=>({origin,'content-type':'application/json','x-foundation-journey':owner.token,'x-foundation-operation':readRecord().operationId});
13
+ const request=async(owner,route,body)=>{
14
+ if(owner.child.exitCode!==null||owner.child.signalCode)throw Error('确认服务已退出,结果待核实');
15
+ 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)});
16
+ return {status:response.status,body:await response.json()};
17
+ };
18
+ return {
19
+ setOrigin(value){if(origin)throw Error('单页来源不能重绑定');origin=value;},
20
+ attach(child){
21
+ const owner={child,token:crypto.randomBytes(32).toString('hex'),url:null};children.set(child,owner);
22
+ 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});});
23
+ child.once('close',()=>{children.delete(child);if(active?.owner===owner){active=null;changed();}});
24
+ },
25
+ async observe(child,event){
26
+ if(event.status==='FOUNDATION_OPERATION_STATE'&&active?.view?.session?.sessionId===event.sessionId){active.view.session.state=event.state;changed();return;}
27
+ if(!['AWAITING_FOUNDATION_DIRECTORY_SELECTION','AWAITING_FOUNDATION_UI_CONFIRMATION'].includes(event.status))return;
28
+ const owner=children.get(child);if(!owner)throw Error('未绑定的确认进程');
29
+ const revision=++viewRevision;
30
+ 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('确认服务地址无效');
31
+ owner.url=url.href;
32
+ const selection=event.status==='AWAITING_FOUNDATION_DIRECTORY_SELECTION';
33
+ const result=await request(owner,selection?'__foundation/install/view':'__foundation/manager/view');
34
+ if(children.get(child)!==owner||revision!==viewRevision)return;
35
+ if(result.status!==200||result.body.operationId!==readRecord().operationId)throw Error('当前引擎不支持单页确认;旧版本需要另行重新安装,不降级到旧页面');
36
+ if(!selection&&result.body.session.sessionId!==event.sessionId)throw Error('确认会话不匹配');
37
+ active={owner,type:selection?'selection':'manager',view:result.body};changed();
38
+ if(selection&&choice){
39
+ const selected=await request(owner,'__foundation/install/selection',{nonce:result.body.nonce,action:'select',destination:choice.destination,skillChoice:choice.skillChoice,...scopeFields(choice)});
40
+ if(selected.status!==200){active.error=selected.body.message;choice=null;changed();}
41
+ }
42
+ },
43
+ view(){return active?{type:active.type,...active.view,error:active.error||null}:null;},
44
+ waitChoice({timeoutMs=600000}={}){return new Promise((resolve,reject)=>{
45
+ if(resolveChoice)throw Error('目录选择已在等待');
46
+ resolveChoice=resolve;rejectChoice=reject;
47
+ choiceTimer=setTimeout(()=>{resolveChoice=null;rejectChoice=null;reject(Object.assign(Error('目录选择已到期,尚未下载或安装;重新发起需要新的选择'),{code:'ENTRY_CHOICE_EXPIRED'}));changed();},timeoutMs);
48
+ changed();
49
+ });},
50
+ async submit(body){
51
+ if(body.operationId!==readRecord().operationId)throw Error('流程身份不匹配');
52
+ if(body.action==='cancel-intent'&&rejectChoice){
53
+ clearTimeout(choiceTimer);const reject=rejectChoice;resolveChoice=null;rejectChoice=null;
54
+ reject(Object.assign(Error('已取消目录选择,尚未下载或安装'),{code:'ENTRY_CHOICE_CANCELLED'}));changed();return {status:200,body:{state:'cancelled-no-install'}};
55
+ }
56
+ if(body.action==='choose'&&resolveChoice){
57
+ if(typeof body.destination!=='string'||!body.destination.trim()||!['selected','skipped'].includes(body.skillChoice))throw Error('请选择完整目录和 Skill 意向');
58
+ const destinationCheck=inspectEntryDestination(body.destination);
59
+ const scopeKind=body.scopeKind||'user';if(!['user','project'].includes(scopeKind)||scopeKind==='project'&&(!body.projectRoot||typeof body.projectRoot!=='string'))throw Error('请选择使用范围和完整项目根路径');
60
+ const scope=inspectScopeIntent(scopeKind,body.projectRoot,destinationCheck.destination);
61
+ choice={destination:destinationCheck.destination,skillChoice:body.skillChoice,scopeKind,projectRoot:scope.projectRoot,destinationCheck};const resolve=resolveChoice;clearTimeout(choiceTimer);resolveChoice=null;rejectChoice=null;resolve(choice);changed();return {status:200,body:{state:'intent-selected'}};
62
+ }
63
+ if(!active)throw Error('当前没有可确认的计划;请等待或查询结果');
64
+ const a=active;
65
+ if(a.type==='selection'){
66
+ if(!['select','cancel'].includes(body.action))throw Error('目录操作无效');
67
+ const result=await request(a.owner,'__foundation/install/selection',body.action==='cancel'?{nonce:a.view.nonce,action:'cancel'}:{nonce:a.view.nonce,action:body.action,destination:body.destination,skillChoice:body.skillChoice,...scopeFields(body)});
68
+ if(result.status!==200)a.error=result.body.message;changed();return result;
69
+ }
70
+ const s=a.view.session;
71
+ 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('当前计划已变化或请求无效');
72
+ if(body.action!=='cancel-no-change'){
73
+ const environment=inspectEntryEnvironment({purpose:'confirm'});
74
+ // Keep the failed snapshot with this operation even if no mutation is
75
+ // forwarded; acquisition-only tools must not gate a verified plan.
76
+ Object.assign(readRecord(),{environment});changed({environment});
77
+ if(environment.state!=='ready')throw Error('执行前环境复检未通过;没有提交确认,请核实当前工具环境');
78
+ }
79
+ const result=await request(a.owner,'__foundation/manager/confirm',{operationId:body.operationId,sessionId:s.sessionId,planHash:s.planHash,managerNonce:body.managerNonce,action:body.action});
80
+ if(active===a&&result.body.state)a.view.session={...s,...result.body};changed();return result;
81
+ }
82
+ };
83
+ }
@@ -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,16 +1,32 @@
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
- export function downloadText(download) {
6
+ export function downloadText(download, compact = false) {
6
7
  if(!download||!Number.isFinite(download.downloadedBytes)||download.downloadedBytes<0)return '';
7
8
  const amount=n=>(n/1048576).toFixed(2)+' MiB';
8
9
  const known=Number.isFinite(download.totalBytes)&&download.totalBytes>0;
9
- return '已接收 '+amount(download.downloadedBytes)+(known?' / '+amount(download.totalBytes)+(download.downloadedBytes<=download.totalBytes?' · '+Math.floor(download.downloadedBytes/download.totalBytes*100)+'%':'(长度待核实)'):'(总量未知)');
10
+ const valid=known&&download.downloadedBytes<=download.totalBytes;
11
+ const percent=valid&&download.downloadedBytes>0?Math.floor(download.downloadedBytes/download.totalBytes*100):null;
12
+ if(compact)return (percent===null?'已下载 ':'下载 '+percent+'% · ')+amount(download.downloadedBytes)+(known?' / '+amount(download.totalBytes)+(valid?'':'(长度待核实)'):'');
13
+ return '已接收 '+amount(download.downloadedBytes)+(known?' / '+amount(download.totalBytes)+(valid?(percent===null?'':' · '+percent+'%'):'(长度待核实)'):'(总量未知)');
14
+ }
15
+
16
+ export function downloadStatus(record) {
17
+ if(record.kind==='uninstall')return '';
18
+ if(record.terminal)return record.state==='failed'?'下载检查失败':'本次获取已结束';
19
+ if(record.phase==='fetching-and-verifying-runtime'){
20
+ const d=record.download,prefix=Number.isSafeInteger(d?.attempt)&&d.attempt>1?'重试 '+d.attempt+' · ':'';
21
+ if(d?.downloadedBytes===0)return prefix+'等待下载';
22
+ if(Number.isFinite(d?.totalBytes)&&d.totalBytes>0&&d.downloadedBytes===d.totalBytes)return '正在检查文件';
23
+ return prefix+(downloadText(d,true)||'等待下载');
24
+ }
25
+ return ({discovering:'正在查询版本','verifying-trust':'正在检查来源','fetching-and-verifying-catalog':'正在检查清单','verifying-runtime':'正在检查文件','extracting-and-validating':'正在展开检查','acquired':'检查完成'})[record.phase]||'';
10
26
  }
11
27
 
12
28
  export function acquisitionProgress(record) {
13
- const phases={discovering:'查询正式发行','verifying-trust':'核验发行来源','fetching-and-verifying-catalog':'获取并核验发行清单','fetching-and-verifying-runtime':'下载并核验运行文件','extracting-and-validating':'展开并检查文件','acquired':'获取验证完成','starting-confirmation-service':'准备目录选择与确认页','selecting-directory':'等待你选择目录','awaiting-confirmation':'等待你确认安装',executing:'正在安装','runtime-ended':'读取安装结果',finished:'安装结果已返回'};
29
+ const phases={discovering:'查询正式发行','verifying-trust':'核验发行来源','fetching-and-verifying-catalog':'获取并核验发行清单','fetching-and-verifying-runtime':'正在下载运行文件','verifying-runtime':'正在检查文件摘要与发行证明','extracting-and-validating':'展开并检查文件','acquired':'获取验证完成','starting-confirmation-service':'准备目录选择与确认页','selecting-directory':'等待你选择目录','awaiting-confirmation':'等待你确认安装',executing:'正在安装','runtime-ended':'读取安装结果',finished:'安装结果已返回'};
14
30
  const terminal=record.terminal;
15
31
  const acquired=['acquired','starting-confirmation-service','selecting-directory','directory-selection-ended','awaiting-confirmation','executing','runtime-ended','finished'].includes(record.phase);
16
32
  const observations={acquire:{state:acquired?'completed':terminal?'failed':'running',evidence:record.resultFile}};
@@ -34,24 +50,37 @@ export function acquisitionProgress(record) {
34
50
  const verb=kind==='uninstall'?'卸载':kind==='update'?'更新':'安装';
35
51
  Object.assign(phases,{'awaiting-confirmation':'等待你确认'+verb,executing:'正在'+verb,'runtime-ended':'读取'+verb+'结果',finished:verb+'结果已返回'});
36
52
  if(record.terminal&&record.state==='partial'&&record.programState==='completed'&&kind==='update')journey.title='程序已更新,Skill 尚未更新';
37
- return {journey,operationId:record.operationId,title:journey.title,phase:({'skill-confirmation':'等待你确认 Codex 操作','skill-executing':'正在处理 Codex 对话能力'})[record.phase]||phases[record.phase]||'正在核实本次操作',state:record.state,version:record.currentVersion&&kind==='update'?record.currentVersion+' → '+record.version:record.version||record.currentVersion||null,download:record.download||null,program:record.programState==='completed'?'程序'+verb+'已完成;'+(kind==='uninstall'?'结果由独立回执保留':record.runtimeHealth==='passed'?'稳定入口健康已核验':'健康待核实'):record.installationWrites==='none'?'尚未执行程序操作':'程序结果以同次记录为准',skill:kind==='uninstall'?(observations.remove?.state==='completed'?'已解除已归属 Codex 注册;修改和未知文件按计划保留':'本次没有已核实的注册移除结果'):record.skillRegistered===true?'Skill 文件与归属已核验;新对话识别另验':record.journeyContext?.skillChoice==='skipped'?'本次不接入 Codex':record.journeyContext?.skillChoice==='selected'?'已选择接入 Codex;仅在分别确认后执行':'Codex 接入可选,尚未选择',project:'未自动接入项目',installationRoot:record.installationRoot||null,skillDestination:record.skillDestination||null,next:record.next||(record.terminal&&record.state==='completed'&&record.journeyContext?.skillChoice==='skipped'?'本次已跳过 Codex 接入;程序操作已完成,项目另行确认。':journey.summary),nextUrl:record.terminal?(kind!=='uninstall'&&record.workbench?.state==='ready'?record.workbench.url:null):record.confirmationUrl||null,nextLabel:record.terminal?'打开已安装工作台':record.phase?.startsWith('skill-')?'查看 Codex 精确确认':kind==='install'?'继续到目录选择 / 本人确认页':'查看'+verb+'确认',resultFile:record.resultFile||null,terminal,diagnostic:record.diagnostic||null};
53
+ return {journey,operationId:record.operationId,title:journey.title,phase:({'skill-confirmation':'等待你确认 Codex 操作','skill-executing':'正在处理 Codex 对话能力'})[record.phase]||phases[record.phase]||'正在核实本次操作',state:record.state,version:record.currentVersion&&kind==='update'?record.currentVersion+' → '+record.version:record.version||record.currentVersion||null,download:record.download||null,downloadStatus:downloadStatus(record),program:record.programState==='completed'?'程序'+verb+'已完成;'+(kind==='uninstall'?'结果由独立回执保留':record.runtimeHealth==='passed'?'稳定入口健康已核验':'健康待核实'):record.installationWrites==='none'?'尚未执行程序操作':'程序结果以同次记录为准',skill:kind==='uninstall'?(observations.remove?.state==='completed'?'已解除已归属 Codex 注册;修改和未知文件按计划保留':'本次没有已核实的注册移除结果'):record.skillRegistered===true?'Skill 文件与归属已核验;新对话识别另验':record.journeyContext?.skillChoice==='skipped'?'本次不接入 Codex':record.journeyContext?.skillChoice==='selected'?'已选择接入 Codex;仅在分别确认后执行':'Codex 接入可选,尚未选择',project:'未自动接入项目',installationRoot:record.installationRoot||null,skillDestination:record.skillDestination||null,next:record.next||(record.terminal&&record.state==='completed'&&record.journeyContext?.skillChoice==='skipped'?'本次已跳过 Codex 接入;程序操作已完成,项目另行确认。':journey.summary),nextUrl:record.terminal?(kind!=='uninstall'&&record.workbench?.state==='ready'?record.workbench.url:null):record.confirmationUrl||null,nextLabel:record.terminal?'打开已安装工作台':record.phase?.startsWith('skill-')?'查看 Codex 精确确认':kind==='install'?'继续到目录选择 / 本人确认页':'查看'+verb+'确认',resultFile:record.resultFile||null,terminal,diagnostic:record.diagnostic||null};
38
54
  }
39
55
 
40
56
  // A bounded, read-only loopback view over the existing in-memory operation.
41
57
  // No POST, launch endpoint, confirmation authority or downloaded executable.
42
- export async function startProgressPage(readRecord) {
58
+ export async function startProgressPage(readRecord, {control = null} = {}) {
43
59
  const token=crypto.randomBytes(24).toString('hex'),base=`/${token}`,clients=new Set();
44
60
  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
61
  let origin;
62
+ let terminalObserved=false,terminalRead=null;
46
63
  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;}
64
+ const server=http.createServer(async(req,res)=>{
65
+ if(req.headers.host!==origin||req.headers.origin&&req.headers.origin!==`http://${origin}`){res.writeHead(403).end();return;}
66
+ 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;}
67
+ if(control&&req.method==='POST'&&req.url===base+'/action'){
68
+ if(req.headers.origin!==`http://${origin}`||req.headers['content-type']!=='application/json'){res.writeHead(403).end();return;}
69
+ 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;
70
+ }
71
+ if(req.method!=='GET'){res.writeHead(403).end();return;}
49
72
  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);}
73
+ if(req.url===base){res.writeHead(200,{...headers,'content-type':'text/html; charset=utf-8'}).end(control?singlePageDocument(token):html);}
51
74
  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
75
  else{res.writeHead(404).end();}
53
76
  });
54
77
  await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});
55
78
  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));}};
79
+ control?.setOrigin(`http://${origin}`);
80
+ return {url:`http://${origin}${base}`,publish(){for(const res of clients)res.write(`data: ${current()}\n\n`);},async close(){
81
+ // Allow the same page to receive the terminal snapshot before this bounded
82
+ // service exits. No polling or page acknowledgement authorizes a mutation.
83
+ if(control&&readRecord().terminal&&!terminalObserved)await new Promise(resolve=>{const timer=setTimeout(resolve,15000);terminalRead=()=>{clearTimeout(timer);resolve();};});
84
+ for(const res of clients)res.end();clients.clear();return new Promise(resolve=>server.close(resolve));
85
+ }};
57
86
  }
@@ -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,5 @@
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
+ // C5: download metadata wraps within the existing right-hand status slot.
5
+ 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;min-width:0;overflow-wrap:anywhere}#foundation-flow-demo .step-state{font-size:12px;color:var(--fp-muted);max-width:48%;text-align:right;overflow-wrap:anywhere}#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,67 @@
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.environment)steps.unshift({key:'environment',title:'检查使用环境',state:r.environment.state==='ready'?'completed':'failed',evidence:(r.environment.preparation?'对话准备的基础环境已复检;':'复用现有入口环境;')+r.environment.platform+' '+r.environment.arch+';入口 Node '+r.environment.nodeVersion+';程序使用随包运行时,不修改共享设置'+(r.environment.preparation?'。独立环境回执:'+r.environment.preparation.receipt+';缓存不自动清理':'')});
21
+ if(r.intentSelected){const s=steps.find(s=>s.key==='select');if(s)s.state='completed';}
22
+ 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;
23
+ // The final result check must not look finished while a chosen Skill step
24
+ // still awaits confirmation. Program health remains visible in its receipt.
25
+ const health=steps.find(s=>s.key==='health');
26
+ if(health?.state==='completed'&&!r.terminal)health.state='planned';
27
+ if(r.terminal)active=null;
28
+ const executing=['executing','consumed'].includes(v?.session?.state)||['executing','skill-executing'].includes(r.phase);
29
+ const count=steps.filter(s=>['completed','skipped','retained'].includes(s.state)).length;
30
+ q('#flow-title').textContent=r.terminal?(r.state==='completed'?'Foundation '+verb+'完成':'本次'+verb+'未全部完成'):verb+' Foundation';
31
+ q('#flow-eyebrow').textContent=r.terminal?'本次结果':executing?'正在执行':busy?'正在提交请求':v||choice?'等待你的操作':'正在进行';
32
+ q('#flow-description').textContent=kind==='install'?'安装程序和 Skill,让 Codex 可以使用 Foundation。':kind==='update'?'更新程序和已有 Skill,保留你的项目与制作资料。':'移除 Foundation 和它的 Skill,保留你的项目与制作资料。';
33
+ q('#flow-version').textContent='版本:'+(p.progress.version||'待核实');q('#flow-destination').textContent='程序位置:'+(r.installationRoot||r.destinationIntent||'等待选择');
34
+ q('#flow-count').textContent='已处理 '+count+' / '+steps.length+' 步';q('#flow-status').textContent=executing?'正在执行当前步骤':busy?'正在提交请求':r.terminal?(r.state==='completed'?'本次流程已完成':'查看未完成项'):('当前:'+(titles[active]||p.progress.phase));
35
+ const percent=steps.length?count/steps.length*100:0;q('#flow-bar').style.width=percent+'%';q('.track').setAttribute('aria-valuenow',String(Math.round(percent)));
36
+ const key=JSON.stringify([active,v?.session?.sessionId,v?.session?.state,v?.selectionId,r.terminal,steps.map(s=>s.state),v?.error]);
37
+ if(key!==revision&&!busy){
38
+ revision=key;
39
+ q('#flow-steps').innerHTML=steps.map((s,i)=>{
40
+ const done=['completed','retained'].includes(s.state),skip=s.state==='skipped',current=s.key===active;
41
+ let body='';
42
+ 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>';
43
+ 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>';}
44
+ else if(current)body='<p role="status" '+(s.key==='acquire'?'data-acquisition-phase':'')+'>'+esc(p.progress.phase)+'</p><p class="hint">下一步会在本页展开,不需要查找其他网址。</p>'+(s.key==='acquire'?'<p class="error" data-download-connection role="status"></p>':'');
45
+ else if(s.key==='acquire'&&s.state==='failed')body='<p class="error">'+esc(p.progress.next)+'</p>';
46
+ if(current&&(choice||v?.type==='selection'))body=body.replace('<form id="current-form">','<form id="current-form"><label class="field" for="scope-kind">在哪里使用?</label><select id="scope-kind" name="scopeKind"><option value="user" '+(r.scopeIntent?.kind!=='project'?'selected':'')+'>当前用户使用(推荐)</option><option value="project" '+(r.scopeIntent?.kind==='project'?'selected':'')+'>仅当前项目使用</option></select><p class="hint">当前用户:多个项目共用,Skill 为用户级,不是所有系统账户。项目模式:绑定具体仓库,Skill 仅放入该项目;已有用户级 Skill 不会消失,同名冲突会停止注册。</p><label class="field" for="project-root">项目根路径(仅项目模式需要)</label><input id="project-root" type="text" name="projectRoot" value="'+esc(r.scopeIntent?.projectRoot||'')+'" spellcheck="false"><p class="hint">程序仍使用与业务项目不重叠的独立目录,通过真实项目身份限定使用,不修改业务依赖或 AGENTS。</p>');
47
+ return '<li data-step="'+esc(s.key)+'" 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>'+(body?'<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>';
48
+ }).join('');
49
+ }
50
+ if(busy&&executing){const live=q('.current .step-state');if(live)live.textContent='正在执行';}
51
+ // Byte/phase updates must not rebuild the form or depend on its revision key.
52
+ const downloadRow=q('[data-step="acquire"]');
53
+ if(downloadRow&&(active==='acquire'||r.terminal&&steps.find(s=>s.key==='acquire')?.state==='failed')){
54
+ downloadRow.querySelector('.step-state').textContent=p.progress.downloadStatus||p.progress.phase;
55
+ const phase=downloadRow.querySelector('[data-acquisition-phase]');if(phase)phase.textContent=p.progress.downloadStatus==='正在检查文件'?'正在检查文件':p.progress.phase;
56
+ const connection=downloadRow.querySelector('[data-download-connection]');if(connection)connection.textContent='';
57
+ }
58
+ q('#flow-result').hidden=!r.terminal;
59
+ 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>';
60
+ 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);
61
+ }
62
+ 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})};
63
+ if(['choose','select'].includes(action)){body.scopeKind=form.elements.scopeKind.value;body.projectRoot=body.scopeKind==='project'?form.elements.projectRoot.value:null;}
64
+ 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='请求结果待核实,不自动重试。已收到的结果保留;刷新查询同次流程。';}});
65
+ 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?'结果服务已结束,上方保留最后核实结果。可在对话中按本次操作记录再次查询。':'连接已中断,保留最后核实结果;不自动重试操作。';const note=q('.current [data-download-connection]');if(note){note.textContent='连接中断,进度待核实;保留上次收到的数值。';q('.current .step-state').textContent=(last.progress.downloadStatus||last.progress.phase)+' · 待核实';}}}
66
+ async function poll(){if(stopped)return;await refresh();if(!stopped)setTimeout(poll,750);}poll();window.addEventListener('pagehide',()=>{stopped=true},{once:true});
67
+ }
@@ -6,14 +6,15 @@ 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 接续');
15
15
  if(operation.installId&&operation.installId!==identity.identity.installId)throw Error('恢复记录属于另一安装,停止接续');
16
- onChange({installId:identity.identity.installId,installedCandidateHash:identity.candidateHash});
16
+ onChange({installId:identity.identity.installId,installedCandidateHash:identity.candidateHash,usageScope:identity.usageScope||{kind:'user',project:null}});
17
+ const discoveryNext=identity.usageScope?.kind==='project'?'请在绑定项目 '+identity.usageScope.project.path+' 内新开 Codex 对话验证识别;不会供其他项目使用。':'新开 Codex 对话验证识别。';
17
18
  const manifestFile=plainPath(path.join(root,identity.appPath,'artifacts/skills/ai-product-foundation-kit/capability.json'));
18
19
  if(!manifestFile.startsWith(root+path.sep))throw Error('Skill 材料必须属于当前安装');
19
20
  if(initial.codexSkill?.state==='files-installed-host-discovery-unverified'){
@@ -49,5 +50,5 @@ const event=await observePlan(client,requested,observation=>onChange({phase:obse
49
50
  }
50
51
  const verified=checkIdentity().codexSkill;
51
52
  if(verified?.state!=='files-installed-host-discovery-unverified')throw Error('Skill 注册文件与归属未通过核验;程序成功保留');
52
- return {state:'completed',phase:'finished',terminal:true,skillRegistered:true,skillDestination:verified.destination,skillSteps:steps,hostDiscoveryVerified:false,next:'程序与所选 Skill 文件已就位;新开 Codex 对话验证识别,项目接入另行确认。'};
53
+ return {state:'completed',phase:'finished',terminal:true,skillRegistered:true,skillDestination:verified.destination,skillSteps:steps,hostDiscoveryVerified:false,next:'程序与所选 Skill 文件已就位;'+discoveryNext+' 项目接入另行确认。'};
53
54
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@josephyulei/summon-foundation",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
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.7",
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.7",
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"},