@promptframe/creation 0.3.0 → 0.3.1

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.
@@ -36,13 +36,17 @@
36
36
 
37
37
  当前源码按平台握手结果提供标准 resources/prompts 读取。项目公开指引复用平台已验证的创作基线;资源 URI 由平台解析,每次读取重新检查账号和项目权限。带版本的引用遇到正文版本变化会提示重新列取,不静默替换内容。桥保留标准正文和元数据,按序列化 UTF-8 计算单块400000字节、整次2000000字节上限;超限不会重执行业务。后续正常读取观察到版本变化时发送对应目录通知,不启动后台轮询。未声明这些能力的平台仍可通过原工具入口读取入门说明。源码能力、公开包和宿主实际支持分别核实。
38
38
 
39
- 当前源码在新会话启动时读取平台初始化中的 `experimental.promptframe.creation` 兼容声明。在接收宿主工具调用前,按真实版本检查 `minBridge`,从官方 npm registry 获取固定的 `recommendedBridge`;`--bridge-version X.Y.Z` 可锁定一个兼容版本。下载只允许公开的 `@promptframe/creation` 固定版本,核 SHA-512 integrity、包身份及自包含运行文件后,再原子放入私有缓存。缓存按完整文件摘要复核,同版本不能更换完整性摘要,准备过程不运行安装脚本或注册宿主。新进程继承同一凭据路径和冻结的宿主会话身份,活动桥不被替换。
39
+ 当前源码在新会话启动时读取平台初始化中的 `experimental.promptframe.creation` 兼容声明。在接收宿主工具调用前,按真实版本检查 `minBridge`,从官方 npm registry 获取固定的 `recommendedBridge`;`--bridge-version X.Y.Z` 可锁定一个兼容版本。下载只允许公开的 `@promptframe/creation` 固定版本,核 SHA-512 integrity、包身份及自包含运行文件后,再原子放入私有缓存。缓存按完整文件摘要复核,同版本不能更换完整性摘要,准备过程不运行安装脚本或注册宿主。新进程继承同一凭据路径和宿主种类,活动桥不被替换。宿主 hook 随插件安装,不由运行文件选择器更新。
40
40
 
41
41
  获取或校验失败时,只有当前程序已经达到已知最低版本才可继续;显式锁定失败不会另选版本。平台缺少兼容声明时提示先更新平台。缓存位于安全凭据目录下的 `runtime-cache`,不会自动删除旧版本或清除不明准备锁。新运行进程启动后的错误不会触发第二次桥启动。
42
42
 
43
43
  外部宿主可在初始化声明 `experimental.promptframe.contentTypes`,桥只转发已知种类,未声明时使用明确的文字降级。媒体能力来自宿主声明,不从模型或宿主名称推断;真实桌面是否展示图片、音频和资源仍需分别验证。源码、公开包及实际宿主加载分别核实。
44
44
 
45
- `bridge --host codex`使用宿主提供的threadId;`bridge --host claude-code`使用启动环境中的`CLAUDE_CODE_SESSION_ID`。未指定host时,`CLAUDECODE=1`选择Claude Code,其余选择Codex。Claude会话ID缺失时,本进程使用临时UUID;下次启动不能据此保留原编辑身份。无效会话ID会报错,不从调用参数接受替代值。公开发行与两种桌面宿主的实际加载分别核实。
45
+ `bridge --host codex`使用宿主提供的threadId。Claude通过同步SessionStart/PreToolUse hook取得当前session_id;每个调用的单次本机凭证绑定工具、参数和当前代次,桥在转发前移除,模型提供的身份字段不能代替它。`/clear`或fork更新身份,resume保留同一UUID,compact不切换控制者。启动环境仅用于识别宿主种类,缺少可信身份时不随机生成或退回旧值:独立读取仍按平台目录与ACL执行,受控和权威操作明确拒绝。
46
+
47
+ Linux/WSL原生CLI关联沿实际进程祖先、boot/birth、UID和原生可执行文件核验,不假定直接父进程。私有状态使用0700目录、0600无symlink文件与原子fsync写入;旧hook写入和旧代次响应不能回写当前控制缓存。正常SessionEnd清理本进程命名空间;异常残留不能供另一个进程认领。MCP+Skill备用安装只管理自身的精确hook项,保留其它设置,编辑冲突和未知写回执先读取原状态。
48
+
49
+ PreToolUse hook不替用户批准工具。Claude的auto模式可能先审核hook补入的输入;同一个尚未使用的精确凭证可在该审核重试时保留,实际调用后不可重放。包发行、hook安装、桌面实际会话与模型收图分别验证。
46
50
 
47
51
  源码经 GitHub Actions 打包发行到 npm;插件目录记录包名/版本或源码位置。安装后,Codex 加载本地副本并按配置启动 Node 桥;桥通过 stdio 接收调用,读取独立安全配置,再通过 HTTPS MCP 连接所选平台。GitHub、npm 与目录索引负责获取版本,不进入正常工具调用链。Token 不进入源码、插件包或命令参数。
48
52
 
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": "creation-install-guidance/v1",
3
3
  "package": "@promptframe/creation",
4
- "version": "0.3.0",
4
+ "version": "0.3.1",
5
5
  "hosts": [
6
6
  {
7
7
  "kind": "codex",
@@ -18,8 +18,8 @@
18
18
  {
19
19
  "kind": "claude-code",
20
20
  "name": "Claude Code",
21
- "minimumBridge": "0.3.0",
22
- "requirements": "Node.js 20+ 与 Claude Code 2.0.12+,或桌面版提供的同机远程入口",
21
+ "minimumBridge": "0.3.1",
22
+ "requirements": "Node.js 20+ 与 Claude Code 2.1.295+;受控会话身份使用 Linux/WSL 原生 CLI 或桌面版的同机远程入口",
23
23
  "commandArgs": [
24
24
  "connect",
25
25
  "--host",
@@ -1,12 +1,12 @@
1
1
  # 安装、连接与升级
2
2
 
3
- 需要 Node.js 20+,支持插件命令的 Codex0.160.0+ 或 Claude Code2.0.12+,以及可以访问 Studio 的网络。原生 Windows ACL 尚未验证;Linux、WSL、macOS 使用用户目录和私有文件权限,不需要 sudo。
3
+ 需要 Node.js 20+,支持插件命令的 Codex0.160.0+ 或 Claude Code2.1.295+,以及可以访问 Studio 的网络。原生 Windows ACL 尚未验证;Linux、WSL、macOS 使用用户目录和私有文件权限,不需要 sudo。
4
4
 
5
5
  从 Studio 的“连接与授权”复制当前环境的指引。在本机终端执行:
6
6
 
7
7
  <!-- creation-install-command -->
8
8
  ```bash
9
- npx --yes @promptframe/creation@0.3.0 connect --endpoint <Studio提供的API地址>
9
+ npx --yes @promptframe/creation@0.3.1 connect --endpoint <Studio提供的API地址>
10
10
  ```
11
11
  <!-- /creation-install-command -->
12
12
 
@@ -26,7 +26,7 @@ npx --yes @promptframe/creation@0.3.0 connect --endpoint <Studio提供的API地
26
26
 
27
27
  <!-- creation-install-command -->
28
28
  ```bash
29
- npx --yes @promptframe/creation@0.3.0 connect --host claude-code --endpoint <Studio提供的API地址>
29
+ npx --yes @promptframe/creation@0.3.1 connect --host claude-code --endpoint <Studio提供的API地址>
30
30
  ```
31
31
  <!-- /creation-install-command -->
32
32
 
@@ -46,7 +46,7 @@ CLI 优先使用 PATH 中的 Claude;桌面版远程连接 WSL 时,也识别
46
46
 
47
47
  <!-- creation-install-command -->
48
48
  ```bash
49
- npx --yes @promptframe/creation@0.3.0 connect --profile work-account --endpoint <另一环境API地址>
49
+ npx --yes @promptframe/creation@0.3.1 connect --profile work-account --endpoint <另一环境API地址>
50
50
  ```
51
51
  <!-- /creation-install-command -->
52
52
 
@@ -0,0 +1,7 @@
1
+ # 0.3.1
2
+
3
+ 修复Claude Code在`/clear`后继续使用启动时会话身份的问题。插件通过当前宿主hook为每次调用绑定身份,清空或分叉后使用新会话,恢复保留原UUID,压缩不会切换控制者。缺少可信身份时仍可独立读取,编辑和执行会返回明确错误。
4
+
5
+ Claude Code需要2.1.295或更新版本;当前受控身份关联使用Linux/WSL原生CLI,包括桌面版提供的同机远程入口。安装后在新会话中加载插件和hook;已有凭据继续使用。平台需提供相容的工具分类与只读入口。模型收图和实际创作仍需在该宿主内检查。
6
+
7
+ Codex继续使用原宿主threadId。既有版本和标签保持不变。
@@ -0,0 +1,11 @@
1
+ export function claudeHostHooks({pluginName='promptframe-creation',serverName,configFile,nodeCommand='node',runtimeRoot='${CLAUDE_PLUGIN_ROOT}'}={}){
2
+ const escaped=pluginName.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
3
+ const command={type:'command',command:nodeCommand,args:[runtimeRoot+'/bin/promptframe-creation.mjs',
4
+ 'claude-host-hook',...(configFile?['--config',configFile]:[])],timeout:5};
5
+ return{
6
+ SessionStart:[{matcher:'startup|resume|fork|clear|compact',hooks:[{...command}]}],
7
+ PreToolUse:[{matcher:serverName?'^mcp__'+serverName.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')+'__.*':'^mcp__plugin_'+escaped+'_.*',
8
+ hooks:[{...command,onFailure:'block'}]}],
9
+ SessionEnd:[{hooks:[{...command}]}],
10
+ };
11
+ }
@@ -0,0 +1,66 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {open,rm} from 'node:fs/promises';
3
+ import {constants} from 'node:fs';
4
+ import path from 'node:path';
5
+ import {homedir} from 'node:os';
6
+ import {installationFiles} from './user-installation.mjs';
7
+ import {claudeConfigRoot} from './claude-local-state.mjs';
8
+ import {claudeHostHooks} from './claude-hook-definition.mjs';
9
+ import {CreationClientError} from './credentials.mjs';
10
+ const {privateDirectory,privateRead,atomicJSON,acquire}=installationFiles;
11
+ const digest=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
12
+ const fail=()=>{throw new CreationClientError('installation.claude_hooks_require_review');};
13
+ async function settings(file){
14
+ let handle;try{
15
+ handle=await open(file,constants.O_RDONLY|constants.O_NOFOLLOW);const info=await handle.stat();
16
+ if(!info.isFile()||info.uid!==process.getuid?.()||info.size>512*1024)fail();
17
+ const value=JSON.parse(await handle.readFile('utf8'));
18
+ if(!value||typeof value!=='object'||Array.isArray(value)||value.hooks!==undefined&&(!value.hooks||typeof value.hooks!=='object'||Array.isArray(value.hooks)))fail();
19
+ return value;
20
+ }catch(e){if(e.code==='ENOENT')return{};throw e;}finally{await handle?.close();}
21
+ }
22
+ const contains=(value,entries)=>Object.entries(entries).every(([event,wanted])=>Array.isArray(value.hooks?.[event])
23
+ &&wanted.every(entry=>value.hooks[event].filter(actual=>digest(actual)===digest(entry)).length===1));
24
+ export async function verifyClaudeFallbackHooks(record,env){
25
+ if(!record?.settingsFile||record.settingsFile!==path.join(claudeConfigRoot(env),'settings.json')||!record.entries)fail();
26
+ if(!contains(await settings(record.settingsFile),record.entries))fail();
27
+ return true;
28
+ }
29
+ /** The existing installer owns only these exact hook entries. Preserve all
30
+ * unrelated settings; edited/missing owned entries and unknown ACKs are read,
31
+ * never overwritten or followed by a second configuration write. */
32
+ export async function registerClaudeFallbackHooks({record,root,env,nodeCommand,signal}){
33
+ const directory=claudeConfigRoot(env),file=path.join(directory,'settings.json');
34
+ const guard=path.resolve(env.XDG_DATA_HOME??path.join(homedir(),'.local/share'),'promptframe-creation',
35
+ 'claude-hook-writer-'+digest(directory));
36
+ await privateDirectory(guard);const release=await acquire(guard,signal);
37
+ const markerFile=path.join(root,'hooks-current.json'),pendingFile=path.join(root,'hooks-pending.json');
38
+ try{
39
+ await privateDirectory(directory);
40
+ const entries=claudeHostHooks({serverName:record.serverName,configFile:record.configFile,nodeCommand,runtimeRoot:record.versionRoot});
41
+ const expected={contractVersion:'creation-claude-hooks/v1',settingsFile:file,profile:record.profile,entries};
42
+ const pending=await privateRead(pendingFile),previous=await privateRead(markerFile),before=await settings(file);
43
+ if(pending){
44
+ if(digest(pending)!==digest(expected)||!contains(before,entries))throw new CreationClientError('installation.registration_unconfirmed_keep_existing');
45
+ await atomicJSON(markerFile,expected);await rm(pendingFile);return expected;
46
+ }
47
+ if(previous){
48
+ if(previous.contractVersion!==expected.contractVersion||previous.profile!==record.profile||previous.settingsFile!==file)fail();
49
+ await verifyClaudeFallbackHooks(previous,env);
50
+ if(digest(previous)===digest(expected))return previous;
51
+ }
52
+ const next={...before,hooks:{...before.hooks}};
53
+ for(const [event,wanted]of Object.entries(entries)){
54
+ const actual=next.hooks[event]??[];if(!Array.isArray(actual))fail();
55
+ const owned=new Set((previous?.entries[event]??[]).map(digest));
56
+ // A matching destination without our ownership record is not adopted.
57
+ if(wanted.some(entry=>actual.some(value=>digest(value)===digest(entry))&&!owned.has(digest(entry))))fail();
58
+ next.hooks[event]=[...actual.filter(entry=>!owned.has(digest(entry))),...wanted];
59
+ }
60
+ signal?.throwIfAborted();await atomicJSON(pendingFile,expected);
61
+ if(digest(await settings(file))!==digest(before))fail();
62
+ await atomicJSON(file,next);
63
+ if(!contains(await settings(file),entries))throw new CreationClientError('installation.registration_unconfirmed_keep_existing');
64
+ await atomicJSON(markerFile,expected);await rm(pendingFile);return expected;
65
+ }finally{await release();}
66
+ }
@@ -0,0 +1,48 @@
1
+ import {readFile,readlink,stat} from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import {homedir} from 'node:os';
4
+ import {createHash} from 'node:crypto';
5
+
6
+ const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
7
+ const bounded=async file=>{const value=await readFile(file);if(value.length>65536)throw Error('host_process_invalid');return value;};
8
+ export async function processBirth(pid){
9
+ const data=(await bounded(`/proc/${pid}/stat`)).toString(),end=data.lastIndexOf(')'),fields=data.slice(end+2).split(' ');
10
+ if(end<0||fields.length<20||!/^\d+$/.test(fields[19]))throw Error('host_process_invalid');
11
+ const info=await stat(`/proc/${pid}`),exe=await stat(`/proc/${pid}/exe`),name=await readlink(`/proc/${pid}/exe`);
12
+ return{pid,ppid:Number(fields[1]),birth:fields[19],uid:info.uid,device:exe.dev,inode:exe.ino,exe:name};
13
+ }
14
+ /** Find the actual native CLI ancestor, including shell/relay intermediaries.
15
+ * A process name or a bare parent PID never establishes this association. */
16
+ export async function claudeHostProcess({pid=process.pid,env=process.env,home=homedir(),readBirth=processBirth,
17
+ readExecutable=stat,readBoot=async()=>(await bounded('/proc/sys/kernel/random/boot_id')).toString().trim(),purpose='bridge',
18
+ entryFile=process.argv[1],readCommand=async pid=>(await bounded(`/proc/${pid}/cmdline`)).toString().split('\0')}={}){
19
+ if(process.platform!=='linux'||env.CLAUDECODE!=='1')return null;
20
+ try{
21
+ const uid=process.getuid(),boot=await readBoot();
22
+ let child=await readBirth(pid),visited=new Set();
23
+ for(let depth=0;depth<32&&child.ppid>1;depth++){
24
+ if(visited.has(child.ppid))return null;visited.add(child.ppid);
25
+ const host=await readBirth(child.ppid);
26
+ const roots=[path.join(home,'.claude','remote','ccd-cli'),path.join(home,'.local','share','claude','versions')];
27
+ if(roots.some(root=>path.dirname(host.exe)===root)){
28
+ const executable=await readExecutable(host.exe);
29
+ if(host.uid!==uid||![uid,0].includes(executable.uid)||!executable.isFile()||(executable.mode&0o022)
30
+ ||host.inode!==executable.ino||host.device!==executable.dev)return null;
31
+ if(purpose==='hook'){
32
+ const command=await readCommand(child.pid);
33
+ if(!entryFile||!command.some(arg=>arg.includes(entryFile))
34
+ ||!command.some(arg=>arg==='claude-host-hook'||arg.includes(' claude-host-hook')))return null;
35
+ }
36
+ const binding={pid:host.pid,birth:host.birth,uid,device:host.device,inode:host.inode,exe:host.exe,boot};
37
+ const digest=hash(binding);
38
+ return{binding,digest,eventOrder:{birth:child.birth,pid:child.pid},async isCurrent(){
39
+ try{const current=await readBirth(binding.pid);return current.birth===binding.birth&&current.uid===uid
40
+ &&current.device===binding.device&&current.inode===binding.inode&&current.exe===binding.exe
41
+ &&await readBoot()===boot;}catch{return false;}
42
+ }};
43
+ }
44
+ child=host;
45
+ }
46
+ }catch{}
47
+ return null;
48
+ }
@@ -0,0 +1,150 @@
1
+ import {constants} from 'node:fs';
2
+ import {open,mkdir,lstat,rename,unlink,rmdir} from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import {homedir} from 'node:os';
5
+ import {createHash,randomBytes} from 'node:crypto';
6
+ import {CreationClientError} from './credentials.mjs';
7
+ import {claudeHostProcess} from './claude-host-process.mjs';
8
+
9
+ export const CLAUDE_HOST_PROOF='_promptframeHostProof';
10
+ const uuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
11
+ const hex=/^[0-9a-f]{64}$/;
12
+ const error=code=>new CreationClientError('creation.'+code);
13
+ const canonical=value=>{
14
+ if(value===null||typeof value==='string'||typeof value==='boolean'||typeof value==='number'&&Number.isFinite(value))return JSON.stringify(value);
15
+ if(Array.isArray(value))return '['+value.map(canonical).join(',')+']';
16
+ if(value&&typeof value==='object'&&[Object.prototype,null].includes(Object.getPrototypeOf(value)))
17
+ return '{'+Object.keys(value).sort().map(key=>JSON.stringify(key)+':'+canonical(value[key])).join(',')+'}';
18
+ throw error('request_invalid');
19
+ };
20
+ const digest=value=>createHash('sha256').update(canonical(value)).digest('hex');
21
+ const withoutProof=args=>Object.fromEntries(Object.entries(args??{}).filter(([key])=>key!==CLAUDE_HOST_PROOF));
22
+ const later=(a,b)=>BigInt(a.birth)>BigInt(b.birth)||a.birth===b.birth&&a.pid>b.pid;
23
+ async function privateDirectory(directory){
24
+ try{await mkdir(directory,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}
25
+ const info=await lstat(directory);
26
+ if(!info.isDirectory()||info.isSymbolicLink()||info.uid!==process.getuid?.()||(info.mode&0o077))throw error('host_identity_unavailable');
27
+ }
28
+ async function privateRead(file){
29
+ let handle;try{
30
+ handle=await open(file,constants.O_RDONLY|constants.O_NOFOLLOW);const info=await handle.stat();
31
+ if(!info.isFile()||info.uid!==process.getuid?.()||(info.mode&0o077)||info.size>196608)throw error('host_identity_unavailable');
32
+ return JSON.parse(await handle.readFile('utf8'));
33
+ }catch(e){if(e.code==='ENOENT')return null;throw e;}finally{await handle?.close();}
34
+ }
35
+
36
+ /** Local host provenance only. No Token, platform permission or editor lease is
37
+ * stored here. Every controlled call needs its own unguessable, one-use ticket
38
+ * delivered by the host's PreToolUse hook; a SessionStart record alone cannot
39
+ * lend authority to a later call when its hook failed or was disabled. */
40
+ export async function createClaudeHostSession({configFile,env=process.env,root,association,hookProcess=false}={}){
41
+ const owner=association===undefined?await claudeHostProcess({env,purpose:hookProcess?'hook':'bridge'}):association;
42
+ const base=root??path.join(env.CLAUDE_CONFIG_DIR??path.join(homedir(),'.claude'),'promptframe-host-sessions');
43
+ const namespace=owner?path.join(base,digest([owner.digest,path.resolve(configFile)])):null;
44
+ const stateFile=namespace&&path.join(namespace,'state.json');
45
+ async function state(){
46
+ if(!owner||!await owner.isCurrent())return null;
47
+ const value=await privateRead(stateFile);
48
+ if(!value)return null;
49
+ if(value.contractVersion!=='claude-host-session/v1'||value.binding!==owner.digest||!Number.isSafeInteger(value.epoch)
50
+ ||value.epoch<1||!value.order||!/^\d+$/.test(value.order.birth)||!Number.isSafeInteger(value.order.pid)
51
+ ||value.sessionId!==null&&!uuid.test(value.sessionId)||!value.tickets||typeof value.tickets!=='object'
52
+ ||Array.isArray(value.tickets)||Object.keys(value.tickets).length>128)throw error('host_identity_unavailable');
53
+ return value;
54
+ }
55
+ async function transaction(work){
56
+ if(!owner||!await owner.isCurrent())throw error('host_identity_unavailable');
57
+ await privateDirectory(base);await privateDirectory(namespace);
58
+ const lock=path.join(namespace,'write.lock');let acquired=false;
59
+ for(let count=0;count<100;count++)try{await mkdir(lock,{mode:0o700});acquired=true;break;}
60
+ catch(e){if(e.code!=='EEXIST')throw e;await new Promise(resolve=>setTimeout(resolve,10));}
61
+ if(!acquired)throw error('host_identity_unavailable');
62
+ let temporary;
63
+ try{
64
+ if(!await owner.isCurrent())throw error('host_identity_unavailable');
65
+ const current=await state(),next=await work(current);
66
+ if(next===undefined)return;
67
+ if(next===null){if(current)await unlink(stateFile);return;}
68
+ const body=JSON.stringify(next);if(Buffer.byteLength(body)>196608)throw error('host_identity_unavailable');
69
+ temporary=path.join(namespace,'state-'+randomBytes(16).toString('hex')+'.partial');
70
+ const file=await open(temporary,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);
71
+ try{await file.writeFile(body);await file.sync();}finally{await file.close();}
72
+ if(!await owner.isCurrent())throw error('host_identity_unavailable');
73
+ await rename(temporary,stateFile);temporary=undefined;
74
+ const directory=await open(namespace,constants.O_RDONLY|constants.O_DIRECTORY|constants.O_NOFOLLOW);
75
+ try{await directory.sync();}finally{await directory.close();}
76
+ }finally{if(temporary)await unlink(temporary).catch(()=>{});await rmdir(lock);}
77
+ }
78
+ async function begin(raw){
79
+ const proof=raw.arguments?.[CLAUDE_HOST_PROOF],args=withoutProof(raw.arguments);
80
+ if(proof===undefined)return{host:{kind:'claude-code'},assertCurrent:async()=>{},arguments:args};
81
+ if(typeof proof!=='string'||!hex.test(proof))throw error('host_identity_invalid');
82
+ let accepted;
83
+ try{await transaction(current=>{
84
+ const ticket=current?.tickets[proof];
85
+ if(!current?.sessionId||!ticket||ticket.epoch!==current.epoch||ticket.sessionId!==current.sessionId
86
+ ||ticket.digest!==digest([raw.name,args]))throw error('host_identity_invalid');
87
+ accepted={threadId:current.sessionId,epoch:current.epoch};delete current.tickets[proof];return current;
88
+ });}catch(e){if(e instanceof CreationClientError)throw e;throw error('host_identity_unavailable');}
89
+ return{host:{kind:'claude-code',threadId:accepted.threadId},arguments:args,epoch:accepted.epoch,async assertCurrent(){
90
+ try{const current=await state();if(current?.epoch!==accepted.epoch||current.sessionId!==accepted.threadId)
91
+ throw error('host_session_changed');}
92
+ catch(e){if(e instanceof CreationClientError)throw e;throw error('host_identity_unavailable');}
93
+ }};
94
+ }
95
+ async function hook(input){
96
+ const event=input?.hook_event_name;
97
+ if(!['SessionStart','PreToolUse','SessionEnd'].includes(event))throw error('host_identity_invalid');
98
+ const valid=typeof input.session_id==='string'&&uuid.test(input.session_id),sessionId=valid?input.session_id.toLowerCase():null;
99
+ const rawArgs=input.tool_input;
100
+ if(event==='PreToolUse'&&(!rawArgs||typeof rawArgs!=='object'||Array.isArray(rawArgs)
101
+ ||typeof input.tool_name!=='string'||!/^mcp__[A-Za-z0-9_.:-]+__[A-Za-z0-9_.:-]+$/.test(input.tool_name)))throw error('host_identity_invalid');
102
+ if(!owner)return event==='PreToolUse'&&Object.hasOwn(rawArgs,CLAUDE_HOST_PROOF)
103
+ ?{hookSpecificOutput:{hookEventName:event,updatedInput:withoutProof(rawArgs)}}:{};
104
+ let result={};
105
+ await transaction(current=>{
106
+ if(current&&later(current.order,owner.eventOrder))return undefined;
107
+ if(event==='SessionEnd'){
108
+ if(current?.sessionId===sessionId&&['prompt_input_exit','logout','other','bypass_permissions_disabled'].includes(input.reason))return null;
109
+ if(!current||current.sessionId!==sessionId)return undefined;
110
+ }
111
+ if(event==='SessionStart'&&!['startup','resume','fork','clear','compact'].includes(input.source))throw error('host_identity_invalid');
112
+ const inconsistent=event==='PreToolUse'&&current?.sessionId!==sessionId
113
+ ||event==='SessionStart'&&input.source==='compact'&&current?.sessionId!==sessionId
114
+ ||event==='SessionStart'&&input.source==='startup'&&current?.sessionId&&current.sessionId!==sessionId;
115
+ const nextId=event==='SessionEnd'||inconsistent?null:sessionId;
116
+ const same=current&&current.sessionId===nextId;
117
+ const next={contractVersion:'claude-host-session/v1',binding:owner.digest,epoch:(current?.epoch??0)+(same?0:1),
118
+ order:owner.eventOrder,sessionId:nextId,tickets:same?current.tickets:{}};
119
+ if(event!=='PreToolUse')return next;
120
+ const args=withoutProof(rawArgs),tool=input.tool_name.slice(input.tool_name.lastIndexOf('__')+2),key=digest([tool,args]);
121
+ if(!nextId){result={hookSpecificOutput:{hookEventName:event,updatedInput:args}};return next;}
122
+ const existing=rawArgs[CLAUDE_HOST_PROOF],prior=typeof existing==='string'&&next.tickets[existing];
123
+ // Auto mode can review the changed input before dispatch. Preserve a still
124
+ // unused exact ticket on that retry; never approve the tool or change its
125
+ // business arguments. The bridge consumes the ticket only on actual call.
126
+ if(prior&&prior.digest===key&&prior.epoch===next.epoch&&prior.sessionId===nextId){result={};return next;}
127
+ // Bounded unused local tickets are not accepted platform work. Evicting
128
+ // one can only refuse a late not-yet-dispatched call, never cancel a task.
129
+ if(Object.keys(next.tickets).length>=128)delete next.tickets[Object.keys(next.tickets)[0]];
130
+ const token=randomBytes(32).toString('hex');
131
+ next.tickets[token]={digest:key,epoch:next.epoch,sessionId:nextId};
132
+ result={hookSpecificOutput:{hookEventName:event,updatedInput:{...args,[CLAUDE_HOST_PROOF]:token}}};return next;
133
+ });
134
+ if(event==='SessionEnd')try{await rmdir(namespace);}catch(e){if(!['ENOTEMPTY','ENOENT'].includes(e.code))throw e;}
135
+ return result;
136
+ }
137
+ return{begin,hook};
138
+ }
139
+
140
+ export async function readClaudeHookInput(input){
141
+ const chunks=[];let bytes=0;
142
+ for await(const value of input){const chunk=Buffer.isBuffer(value)?value:Buffer.from(value);bytes+=chunk.length;
143
+ if(bytes>2*1024*1024+65536)throw error('host_identity_invalid');chunks.push(chunk);}
144
+ return JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks,bytes)));
145
+ }
146
+ export async function runClaudeHostHook({configFile,input=process.stdin,output=process.stdout,env=process.env}={}){
147
+ const body=await readClaudeHookInput(input);
148
+ const store=await createClaudeHostSession({configFile,env,hookProcess:true});
149
+ output.write(JSON.stringify(await store.hook(body))+'\n');
150
+ }
@@ -2,6 +2,7 @@ import {createHash,randomBytes} from 'node:crypto';
2
2
  import {mkdir,open,readFile,rename,rm} from 'node:fs/promises';
3
3
  import {homedir} from 'node:os';
4
4
  import path from 'node:path';
5
+ import {claudeHostHooks} from './claude-hook-definition.mjs';
5
6
  import {CreationClientError} from './credentials.mjs';
6
7
  import {inspectRuntimePackage} from './runtime-package.mjs';
7
8
  import {profileCredentialsPath,installationFiles} from './user-installation.mjs';
@@ -68,6 +69,8 @@ async function verifyVersion(root,{version,profile,configFile,payloadDigest,plug
68
69
  ||JSON.stringify(mcp)!==JSON.stringify(transport(serverName,configFile,command)))fail('claude_installed_files_invalid');
69
70
  runtimeCommand=command;
70
71
  }
72
+ if(compareVersions(version,'0.3.1')>=0&&JSON.stringify(manifest.hooks)!==JSON.stringify(claudeHostHooks({pluginName,configFile,nodeCommand:runtimeCommand})))
73
+ fail('claude_installed_files_invalid');
71
74
  return{...ready,runtimeCommand};
72
75
  }
73
76
 
@@ -89,7 +92,7 @@ async function installClaudeUserLocked({sourceRoot,profile='default',env=process
89
92
  validProfile(profile);
90
93
  if(!path.isAbsolute(nodeCommand))fail('runtime_command_invalid');
91
94
  const hostVersion=(await runClaude(['--version'])).trim().match(/^(\d+\.\d+\.\d+) \(Claude Code\)$/);
92
- if(!hostVersion||compareVersions(hostVersion[1],'2.0.12')<0)fail('claude_2012_required');
95
+ if(!hostVersion||compareVersions(hostVersion[1],'2.1.295')<0)fail('claude_21295_required');
93
96
  const help=await runClaude(['--help']);
94
97
  if(typeof help!=='string'||Buffer.byteLength(help)>128*1024)fail('claude_capabilities_unconfirmed');
95
98
  const hasPlugin=/^\s+plugin(?:\|plugins)?\s/m.test(help),hasMcp=/^\s+mcp\s/m.test(help);
@@ -154,6 +157,7 @@ async function installClaudeUserLocked({sourceRoot,profile='default',env=process
154
157
  await mkdir(path.dirname(dest),{recursive:true,mode:0o700});const fd=await open(dest,'wx',0o600);
155
158
  try{await fd.writeFile(file.body);await fd.sync();}finally{await fd.close();}}
156
159
  const manifest=JSON.parse(await readFile(path.join(temporary,'.claude-plugin/plugin.json'),'utf8'));manifest.name=pluginName;
160
+ if(manifest.hooks)manifest.hooks=claudeHostHooks({pluginName,configFile,nodeCommand});
157
161
  await atomicJSON(path.join(temporary,'.claude-plugin/plugin.json'),manifest);
158
162
  for(const file of['.mcp.json','.claude-mcp.json'])await atomicJSON(path.join(temporary,file),transport(serverName,configFile,nodeCommand));
159
163
  await checkRuntime(temporary,payload.version);
@@ -6,6 +6,7 @@ import {CreationClientError} from './credentials.mjs';
6
6
  import {inspectRuntimePackage} from './runtime-package.mjs';
7
7
  import {installationFiles} from './user-installation.mjs';
8
8
  import {claudeConfigRoot,readClaudeUserServer} from './claude-local-state.mjs';
9
+ import {registerClaudeFallbackHooks,verifyClaudeFallbackHooks} from './claude-hook-registration.mjs';
9
10
 
10
11
  const {info,privateDirectory,privateRead,atomicJSON,acquire,compareVersions}=installationFiles;
11
12
  const hash=body=>createHash('sha256').update(body).digest('hex');
@@ -85,6 +86,7 @@ export async function installClaudeMcpFallback({sourceRoot,profile,env,configFil
85
86
  const ready=await verifyVersion(record.versionRoot,record);
86
87
  if(!same(record.server,mcpDefinition(record,ready.nodeCommand)))fail('claude_installed_files_invalid');
87
88
  if(!same(saved,record.server))return false;
89
+ if(compareVersions(record.version,'0.3.1')>=0)await verifyClaudeFallbackHooks(record.hostHooks,env);
88
90
  if(!Array.isArray(record.skills)||record.skills.length!==2)fail('claude_skill_requires_review');
89
91
  for(const [i,skill]of record.skills.entries()){
90
92
  const name=['creation-setup','video-creation'][i]+suffix;
@@ -159,6 +161,7 @@ export async function installClaudeMcpFallback({sourceRoot,profile,env,configFil
159
161
  await atomicJSON(path.join(plan.root,'promptframe-installation.json'),{host:'claude-code',profile,configFile,name:plan.name,sha256:plan.sha256});
160
162
  }
161
163
  signal?.throwIfAborted();
164
+ if(compareVersions(payload.version,'0.3.1')>=0)complete.hostHooks=await registerClaudeFallbackHooks({record:complete,root,env,nodeCommand:ready.nodeCommand,signal});
162
165
  if(!same(await readClaudeUserServer(serverName,env),complete.beforeServer))fail('claude_local_registration_changed');
163
166
  await atomicJSON(pendingFile,{...complete,phase:'mcp'});writeStarted=true;
164
167
  await runClaude(['mcp','add-json','--scope','user',serverName,JSON.stringify(complete.server)]);
package/lib/cli.mjs CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  import { connectPlatform } from "./connection.mjs";
25
25
  import { createHostCallBridge } from "./host-context.mjs";
26
26
  import { resolveHostIdentity } from "./host-identity.mjs";
27
+ import {createClaudeHostSession,runClaudeHostHook} from './claude-host-session.mjs';
27
28
  import {declaredHostContentCapabilities,readPlatformBridgePolicy,bridgeErrorDetails} from './bridge-negotiation.mjs';
28
29
  import {selectBridgeRuntime,runtimeErrorDetails} from './runtime-bootstrap.mjs';
29
30
  import {launchSelectedBridge} from './runtime-launch.mjs';
@@ -190,6 +191,7 @@ async function bridge() {
190
191
  await client.close();const result=await launchSelectedBridge(selection,{host:identity,configFile:configFile()});
191
192
  process.exitCode=result.code;return;
192
193
  }
194
+ const hostSession=identity.kind==='claude-code'?await createClaudeHostSession({configFile:configFile()}):undefined;
193
195
  const server = new Server(
194
196
  { name: "promptframe-creation", version: CLIENT_VERSION },
195
197
  { capabilities: { tools: {listChanged:true},...(upstream.resources?{resources:{listChanged:true}}:{}),
@@ -197,7 +199,7 @@ async function bridge() {
197
199
  experimental:{...(policy?{'promptframe.creation':policy}:{}),
198
200
  'promptframe.runtime':{version:selection.version,locked:selection.locked,status:selection.status}} } },
199
201
  ),
200
- host=createHostCallBridge(client,{credentials,host:identity,onCatalogChange:()=>server.sendToolListChanged(),
202
+ host=createHostCallBridge(client,{credentials,host:identity,hostSession,onCatalogChange:()=>server.sendToolListChanged(),
201
203
  onKnowledgeChange:kind=>kind==='resources'?server.sendResourceListChanged():server.sendPromptListChanged()});
202
204
  server.oninitialized=()=>{const declared=declaredHostContentCapabilities(server.getClientCapabilities());
203
205
  contentTypes=declared.types;contentSource=declared.source;};
@@ -242,8 +244,10 @@ async function bridge() {
242
244
  success: false,
243
245
  errorCode: error instanceof CreationClientError
244
246
  ? error.message : "creation.connection_unresolved",
247
+ ...(error instanceof CreationClientError&&error.message==='creation.host_session_changed'
248
+ ?{effectStatus:'unknown',automaticReplayAllowed:false}:{}),
245
249
  action: error instanceof CreationClientError
246
- ? error.message.startsWith("creation.host_")
250
+ ? error.message==='creation.host_session_changed'?'read_original_task_without_replaying_business':error.message.startsWith("creation.host_")
247
251
  ? "use_supported_host_with_session_identity"
248
252
  : error.message === "creation.editor_not_current"
249
253
  ? "request_control_and_confirm_in_studio"
@@ -297,6 +301,7 @@ try {
297
301
  }finally{process.removeListener('SIGINT',abort);process.removeListener('SIGTERM',abort);}
298
302
  }
299
303
  else if (command === "bridge") await bridge();
304
+ else if(command==='claude-host-hook')await runClaudeHostHook({configFile:configFile()});
300
305
  else if(command==='--version')process.stdout.write(CLIENT_VERSION+'\n');
301
306
  else if (command === "status") {
302
307
  const saved = await readCredentials(configFile());
@@ -308,7 +313,7 @@ try {
308
313
  });
309
314
  } else if (command === "help" || command === "--help" || !command) {
310
315
  process.stdout.write(
311
- "promptframe-creation connect --endpoint <platform-api-base> [--host codex|claude-code] [--profile <environment-account>] [--claude-bin <absolute-file>] [--no-open]\npromptframe-creation setup --endpoint <platform-api-base> [--host codex|claude-code] [--no-open] [--replace] [--name <client-name>]\npromptframe-creation status [--profile <environment-account>] [--host codex|claude-code]\npromptframe-creation bridge [--config <private-file>] [--host codex|claude-code] [--bridge-version <X.Y.Z>]\npromptframe-creation --version\nNode.js >=20 is required. Plugin installation supports Codex >=0.160.0 or Claude Code >=2.0.12 with its structured plugin commands. Token input is masked in a terminal or accepted through --token-stdin; never use a Token command argument.\nBridge startup checks the platform minimum/recommended version. --bridge-version locks one exact compatible version for this new session; active bridges are not replaced.\n",
316
+ "promptframe-creation connect --endpoint <platform-api-base> [--host codex|claude-code] [--profile <environment-account>] [--claude-bin <absolute-file>] [--no-open]\npromptframe-creation setup --endpoint <platform-api-base> [--host codex|claude-code] [--no-open] [--replace] [--name <client-name>]\npromptframe-creation status [--profile <environment-account>] [--host codex|claude-code]\npromptframe-creation bridge [--config <private-file>] [--host codex|claude-code] [--bridge-version <X.Y.Z>]\npromptframe-creation --version\nNode.js >=20 is required. Plugin installation supports Codex >=0.160.0 or Claude Code >=2.1.295 with its structured plugin commands. Token input is masked in a terminal or accepted through --token-stdin; never use a Token command argument.\nBridge startup checks the platform minimum/recommended version. --bridge-version locks one exact compatible version for this new session; active bridges are not replaced.\n",
312
317
  );
313
318
  } else throw new CreationClientError("command.unknown");
314
319
  } catch (error) {
@@ -2,6 +2,7 @@ import {createHash} from 'node:crypto';
2
2
  import {CreationClientError} from './credentials.mjs';
3
3
  import {hostParameters,resolveHostIdentity} from './host-identity.mjs';
4
4
  import {assertMcpResponseBudget} from './content-budget.mjs';
5
+ import {CLAUDE_HOST_PROOF} from './claude-host-session.mjs';
5
6
  export {hostParameters} from './host-identity.mjs';
6
7
 
7
8
  const digestPattern=/^sha256:[a-f0-9]{64}$/;
@@ -19,12 +20,12 @@ const boundedSet=(map,key,value)=>{if(!map.has(key)&&map.size>=1024)map.delete(m
19
20
 
20
21
  /** The authenticated platform owns classification and editor authority.
21
22
  * Business text and model annotations never populate this cache. */
22
- export function createHostCallBridge(client,{credentials,host=resolveHostIdentity(),onCatalogChange=()=>{},onKnowledgeChange=()=>{}}={}){
23
+ export function createHostCallBridge(client,{credentials,host=resolveHostIdentity(),hostSession,onCatalogChange=()=>{},onKnowledgeChange=()=>{}}={}){
23
24
  if(!credentials?.endpoint||!credentials.clientId)throw new CreationClientError('creation.bridge_identity_required');
24
25
  const installationDigest=digest(credentials.clientId);
25
26
  const versions=new Map(),controllers=new Map(),catalogs=new Map(),inflight=new Map();
26
27
  const knowledgeVersions=new Map(),upstream=client.getServerCapabilities?.()??{};
27
- let platformDigest,accountDigest,directory,directoryRead,sequence=0;
28
+ let platformDigest,accountDigest,directory,directoryRead,sequence=0,hostEpoch;
28
29
  function catalog(channel,version,order){
29
30
  if(typeof version!=='string'||!digestPattern.test(version))return;
30
31
  const old=catalogs.get(channel);if(old&&old.order>order)return;
@@ -69,8 +70,10 @@ export function createHostCallBridge(client,{credentials,host=resolveHostIdentit
69
70
  }
70
71
  return v;
71
72
  }
72
- async function send(params){
73
+ async function send(params,binding){
74
+ await binding?.assertCurrent();
73
75
  const order=++sequence,result=assertMcpResponseBudget(await client.callTool(params,undefined,{timeout:60000}));
76
+ await binding?.assertCurrent();
74
77
  return {result,trusted:remember(params,result,order)};
75
78
  }
76
79
  async function listTools(){
@@ -79,9 +82,11 @@ export function createHostCallBridge(client,{credentials,host=resolveHostIdentit
79
82
  if(!directory||order>=directory.order)directory={tools:new Map(result.tools.map(t=>[t.name,t])),order};
80
83
  catalog('outer',result._meta?.['promptframe.catalogVersion'],order);
81
84
  return {...result,tools:result.tools.map(tool=>{
82
- const p=tool.inputSchema.properties;if(!Object.hasOwn(p??{},'controlVersion'))return tool;
83
- const {controlVersion:_managed,...properties}=p;
84
- return {...tool,inputSchema:{...tool.inputSchema,properties,...(tool.inputSchema.required
85
+ const p=tool.inputSchema.properties;
86
+ const {controlVersion:_managed,...properties}=p??{};
87
+ return {...tool,inputSchema:{...tool.inputSchema,properties:{...properties,...(host.kind==='claude-code'?{
88
+ [CLAUDE_HOST_PROOF]:{type:'string',pattern:'^[a-f0-9]{64}$',description:'由当前宿主hook填入的单次身份凭证;请保留,不自行填写。'}
89
+ }:{})},...(tool.inputSchema.required
85
90
  ?{required:tool.inputSchema.required.filter(name=>name!=='controlVersion')}:{})}};
86
91
  })};
87
92
  }
@@ -92,15 +97,19 @@ export function createHostCallBridge(client,{credentials,host=resolveHostIdentit
92
97
  const found=[...directory.tools.values()].filter(t=>t._meta?.['promptframe.role']===name);
93
98
  if(found.length!==1)throw new CreationClientError('creation.upgrade_required');return found[0].name;
94
99
  }
95
- async function controlRead(params,key){
96
- if(!inflight.has(key))inflight.set(key,send({name:role('control-read'),_meta:params._meta,
97
- arguments:{projectId:params.arguments.projectId,sessionId:params.arguments.sessionId,pageSize:1}}).finally(()=>{inflight.delete(key);}));
100
+ async function controlRead(params,key,binding){
101
+ if(!inflight.has(key)){
102
+ const pending=send({name:role('control-read'),_meta:params._meta,
103
+ arguments:{projectId:params.arguments.projectId,sessionId:params.arguments.sessionId,pageSize:1}},binding)
104
+ .finally(()=>{if(inflight.get(key)===pending)inflight.delete(key);});
105
+ inflight.set(key,pending);
106
+ }
98
107
  const observation=await inflight.get(key);if(observation.result.isError)return observation.result;
99
108
  if(!observation.trusted||!versions.has(key)||versions.get(key).needsRead)throw new CreationClientError('creation.control_unverified');
100
109
  }
101
110
  async function knowledgeRead(kind,method,raw={}){
102
111
  if(!upstream[kind])throw new CreationClientError('creation.knowledge_unsupported');
103
- const params=hostParameters(raw,host,'independent-read'),order=++sequence;
112
+ const params=hostParameters(raw,host.kind==='claude-code'?{kind:host.kind}:host,'independent-read'),order=++sequence;
104
113
  const result=assertMcpResponseBudget(await client[method](params,undefined,{timeout:60000}));
105
114
  const version=result._meta?.[kind==='resources'&&method==='listResources'
106
115
  ?'promptframe.guideDirectoryVersion':'promptframe.guideVersion'];
@@ -123,34 +132,52 @@ export function createHostCallBridge(client,{credentials,host=resolveHostIdentit
123
132
  getPrompt:params=>knowledgeRead('prompts','getPrompt',params),async call(raw){
124
133
  for(const field of ['threadId','controller','clientDigest','token','controlVersion'])if(Object.hasOwn(raw.arguments??{},field))
125
134
  throw new CreationClientError('creation.transport_authority_managed_by_bridge');
126
- await ensureDirectory();const definition=directory.tools.get(raw.name);
135
+ let binding={host,arguments:raw.arguments,assertCurrent:async()=>{}};
136
+ if(host.kind==='claude-code'){
137
+ if(hostSession)binding=await hostSession.begin(raw);
138
+ else if(raw.arguments?.[CLAUDE_HOST_PROOF]!==undefined)throw new CreationClientError('creation.host_identity_invalid');
139
+ else binding={host:{kind:'claude-code'},arguments:raw.arguments,assertCurrent:async()=>{}};
140
+ if(binding.epoch!==hostEpoch){versions.clear();controllers.clear();inflight.clear();hostEpoch=binding.epoch;}
141
+ }else if(Object.hasOwn(raw.arguments??{},CLAUDE_HOST_PROOF))throw new CreationClientError('creation.transport_authority_managed_by_bridge');
142
+ raw={...raw,arguments:binding.arguments};
143
+ await ensureDirectory();await binding.assertCurrent();const definition=directory.tools.get(raw.name);
127
144
  if(!definition)throw new CreationClientError('creation.tool_unavailable');
128
145
  const access=definition._meta['promptframe.access'],managed=Object.hasOwn(definition.inputSchema.properties??{},'controlVersion');
129
- const params=hostParameters(raw,host,managed?'controlled':access);let effectiveAccess=access;
146
+ // Resolve parameter-dependent access before requiring a controller. A
147
+ // missing host UUID must not block an independently authorized read.
148
+ const params=hostParameters(raw,binding.host,'independent-read');let effectiveAccess=access,resolvedControl;
130
149
  if(definition._meta['promptframe.resolveAccess']==='target'){
131
150
  const {projectId,sessionId,tool,arguments:input}=params.arguments??{};
132
151
  if(typeof tool!=='string'||!input||typeof input!=='object'||Array.isArray(input))throw new CreationClientError('creation.request_invalid');
133
- const observed=await send({name:role('describe-target'),_meta:params._meta,arguments:{projectId,sessionId,tool,arguments:input}});
152
+ const observed=await send({name:role('describe-target'),_meta:params._meta,arguments:{projectId,sessionId,tool,arguments:input}},binding);
134
153
  if(observed.result.isError)return observed.result;
135
154
  const resolved=observed.trusted?.resolvedAccess;
136
155
  if(resolved?.tool!==tool||resolved.argumentsDigest!==argumentsDigest(input)||!accesses.has(resolved.access))throw new CreationClientError('creation.access_unverified');
137
156
  effectiveAccess=resolved.access;
157
+ resolvedControl=observed.trusted?.control;
138
158
  }
159
+ hostParameters(raw,binding.host,effectiveAccess);
139
160
  const key=keyFor(params);let outgoing=params;
140
161
  if(managed){
141
- if(!key)throw new CreationClientError('creation.request_invalid');let entry=versions.get(key);
142
- if(!entry||entry.needsRead){const denied=await controlRead(params,key);if(denied)return denied;entry=versions.get(key);}
162
+ if(!key){
163
+ if(effectiveAccess!=='independent-read'||!Number.isSafeInteger(resolvedControl?.controlVersion)||resolvedControl.controlVersion<=0)
164
+ throw new CreationClientError('creation.control_unverified');
165
+ outgoing={...params,arguments:{...params.arguments,controlVersion:resolvedControl.controlVersion}};
166
+ }else{let entry=versions.get(key);
167
+ if(!entry||entry.needsRead){const denied=await controlRead(params,key,binding);if(denied)return denied;entry=versions.get(key);}
143
168
  if(effectiveAccess!=='independent-read'&&!entry.owned)throw new CreationClientError('creation.editor_not_current');
144
169
  outgoing={...params,arguments:{...params.arguments,controlVersion:entry.version}};
170
+ }
145
171
  }
146
172
  const dispatched=key&&versions.get(key);
147
173
  const invalidate=()=>{
174
+ if(host.kind==='claude-code'&&binding.epoch!==hostEpoch)return;
148
175
  const current=key&&versions.get(key);
149
176
  if(dispatched&&current&&current.version<=dispatched.version)
150
177
  boundedSet(versions,key,{...current,needsRead:true,invalidatedAt:++sequence});
151
178
  };
152
179
  let response;
153
- try{response=await send(outgoing);}catch(error){invalidate();throw error;}
180
+ try{response=await send(outgoing,binding);}catch(error){invalidate();throw error;}
154
181
  if(response.result.isError)invalidate();
155
182
  return response.result;
156
183
  }};