@promptframe/creation 0.3.0 → 0.3.2

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
 
@@ -66,4 +70,4 @@
66
70
 
67
71
  宿主插件已安装/启用、平台连接验证与聊天加载分别报告。外部安装器不接私有 app-server 生产刷新通道;当前使用官方新聊天/新 session 路径,选择 Local 和独立非 Git 目录即可。候选包、公共 registry 固定包和真实宿主新聊天工具/两个 Skill 的验收分开记录。
68
72
 
69
- Claude Code 使用官方 `plugin list --json` 与 `plugin marketplace list --json` 读取登记,不调用会健康检查 MCP 的 `mcp list/get`。本地 marketplace 的 `readFromFolder/folderVersion` 表示实际读取目录,与安装记录的缓存路径分别核对;版本目录及两份 MCP 定义均验证摘要。每个登记写前保存阶段,回程未知后只观察原身份。隔离 CLI 安装不等于桌面模型会话加载。
73
+ Claude Code 使用官方 `plugin list --json` 与 `plugin marketplace list --json` 读取登记,不调用会健康检查 MCP 的 `mcp list/get`。本地 marketplace 的 `readFromFolder/folderVersion` 表示实际读取目录,其folderVersion与安装记录的缓存版本可不同;按实际目录版本和完整性核对;版本目录及两份 MCP 定义均验证摘要。每个登记写前保存阶段,回程未知后只观察原身份。隔离 CLI 安装不等于桌面模型会话加载。
@@ -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.2",
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.2 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.2 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.2 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,5 @@
1
+ # 0.3.2
2
+
3
+ 修复Claude Code本地目录插件升级时,安装缓存版本与实际读取目录版本不同造成的确认失败。安装器核对官方返回的实际目录版本、文件完整性及原登记;已经完成的登记通过读取原状态确认。其它插件、已有凭据与活动会话保持原状,新版本在新会话中加载。
4
+
5
+ 通用调用可接收平台按目标schema给出的作用域缺省值和规范化摘要,只补同一项目与作品,拒绝冲突或额外权威字段。当前宿主hook仍绑定原始调用与代次,规范化不会授予编辑权。
@@ -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';
@@ -12,6 +13,7 @@ import {installClaudeMcpFallback} from './claude-mcp-installation.mjs';
12
13
  const {info,privateDirectory,privateRead,atomicJSON,acquire,runNode,checkInstalledRuntime,compareVersions,validProfile}=installationFiles;
13
14
  const hash=b=>createHash('sha256').update(b).digest('hex');
14
15
  const effectiveRoot=plugin=>plugin.readFromFolder??plugin.installPath;
16
+ const effectiveVersion=plugin=>plugin.readFromFolder!==undefined?plugin.folderVersion:plugin.version;
15
17
  class ClaudeInstallationError extends CreationClientError{
16
18
  constructor(code,details){super('installation.'+code);this.details=details;}
17
19
  }
@@ -32,7 +34,7 @@ async function registrations(run,pluginName,marketplace,root){
32
34
  const related=plugins.filter(p=>typeof p?.id==='string'&&p.id.startsWith(pluginName+'@'));
33
35
  if(related.length>1||related.some(p=>p.id!==pluginName+'@'+marketplace||p.scope!=='user'
34
36
  ||typeof p.enabled!=='boolean'||!/^\d+\.\d+\.\d+$/.test(p.version??'')||!path.isAbsolute(p.installPath??'')
35
- ||p.readFromFolder!==undefined&&(!path.isAbsolute(p.readFromFolder)||p.folderVersion!==p.version)))
37
+ ||p.readFromFolder!==undefined&&(!path.isAbsolute(p.readFromFolder)||!/^\d+\.\d+\.\d+$/.test(p.folderVersion??''))))
36
38
  fail('claude_existing_registration_requires_review');
37
39
  const found=markets.filter(p=>p?.name===marketplace);
38
40
  if(found.length>1||found.some(p=>p.source!=='directory'||p.path!==root||p.installLocation!==root))
@@ -68,6 +70,8 @@ async function verifyVersion(root,{version,profile,configFile,payloadDigest,plug
68
70
  ||JSON.stringify(mcp)!==JSON.stringify(transport(serverName,configFile,command)))fail('claude_installed_files_invalid');
69
71
  runtimeCommand=command;
70
72
  }
73
+ if(compareVersions(version,'0.3.1')>=0&&JSON.stringify(manifest.hooks)!==JSON.stringify(claudeHostHooks({pluginName,configFile,nodeCommand:runtimeCommand})))
74
+ fail('claude_installed_files_invalid');
71
75
  return{...ready,runtimeCommand};
72
76
  }
73
77
 
@@ -89,7 +93,7 @@ async function installClaudeUserLocked({sourceRoot,profile='default',env=process
89
93
  validProfile(profile);
90
94
  if(!path.isAbsolute(nodeCommand))fail('runtime_command_invalid');
91
95
  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');
96
+ if(!hostVersion||compareVersions(hostVersion[1],'2.1.295')<0)fail('claude_21295_required');
93
97
  const help=await runClaude(['--help']);
94
98
  if(typeof help!=='string'||Buffer.byteLength(help)>128*1024)fail('claude_capabilities_unconfirmed');
95
99
  const hasPlugin=/^\s+plugin(?:\|plugins)?\s/m.test(help),hasMcp=/^\s+mcp\s/m.test(help);
@@ -124,7 +128,7 @@ async function installClaudeUserLocked({sourceRoot,profile='default',env=process
124
128
  checkBinding(previous);checkBinding(pending);
125
129
  const runtimeCommands=new Map();
126
130
  const observed=async record=>{
127
- if(!state.market||!state.plugin||state.plugin.enabled!==true||state.plugin.version!==record.version||effectiveRoot(state.plugin)!==record.versionRoot)return false;
131
+ if(!state.market||!state.plugin||state.plugin.enabled!==true||effectiveVersion(state.plugin)!==record.version||effectiveRoot(state.plugin)!==record.versionRoot)return false;
128
132
  const ready=await verifyVersion(record.versionRoot,{...record,pluginName,serverName});
129
133
  runtimeCommands.set(record.versionRoot,ready.runtimeCommand);return true;
130
134
  };
@@ -154,6 +158,7 @@ async function installClaudeUserLocked({sourceRoot,profile='default',env=process
154
158
  await mkdir(path.dirname(dest),{recursive:true,mode:0o700});const fd=await open(dest,'wx',0o600);
155
159
  try{await fd.writeFile(file.body);await fd.sync();}finally{await fd.close();}}
156
160
  const manifest=JSON.parse(await readFile(path.join(temporary,'.claude-plugin/plugin.json'),'utf8'));manifest.name=pluginName;
161
+ if(manifest.hooks)manifest.hooks=claudeHostHooks({pluginName,configFile,nodeCommand});
157
162
  await atomicJSON(path.join(temporary,'.claude-plugin/plugin.json'),manifest);
158
163
  for(const file of['.mcp.json','.claude-mcp.json'])await atomicJSON(path.join(temporary,file),transport(serverName,configFile,nodeCommand));
159
164
  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) {