@promptframe/creation 0.1.1 → 0.2.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.
@@ -0,0 +1,228 @@
1
+ import {execFile} from 'node:child_process';
2
+ import {promisify} from 'node:util';
3
+ import {createHash,randomBytes} from 'node:crypto';
4
+ import {lstat,mkdir,readdir,readFile,writeFile,rename,rm} from 'node:fs/promises';
5
+ import {homedir} from 'node:os';
6
+ import path from 'node:path';
7
+ import {CreationClientError,credentialsPath} from './credentials.mjs';
8
+
9
+ const execute=promisify(execFile),hash=b=>createHash('sha256').update(b).digest('hex');
10
+ const fail=code=>{throw new CreationClientError('installation.'+code);};
11
+ const entries=['package.json','README.md','LICENSE','bin','dist','lib','skills','docs','.codex-plugin','.mcp.json'];
12
+ const json=async file=>JSON.parse(await readFile(file,'utf8'));
13
+ const pause=ms=>new Promise(r=>setTimeout(r,ms));
14
+ function validProfile(profile){if(typeof profile!=='string'||!/^[a-z][a-z0-9-]{0,31}$/.test(profile))fail('profile_invalid');return profile;}
15
+ export function profileCredentialsPath(profile='default',env=process.env){
16
+ validProfile(profile);
17
+ return profile==='default'?credentialsPath(env):path.resolve(env.XDG_CONFIG_HOME??path.join(homedir(),'.config'),
18
+ 'promptframe-creation','profiles',profile,'credentials.json');
19
+ }
20
+ async function info(file){try{return await lstat(file);}catch(e){if(e.code==='ENOENT')return null;throw e;}}
21
+ async function privateDirectory(dir){
22
+ await mkdir(dir,{recursive:true,mode:0o700});const s=await lstat(dir);
23
+ if(!s.isDirectory()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o077))fail('private_owner_required');
24
+ }
25
+ async function privateRead(file){
26
+ const s=await info(file);if(!s)return null;
27
+ if(!s.isFile()||s.isSymbolicLink()||s.uid!==process.getuid?.()||(s.mode&0o077)||s.size>512*1024)fail('state_invalid');
28
+ return json(file);
29
+ }
30
+ async function packageJSON(file){
31
+ const s=await info(file);
32
+ if(!s?.isFile()||s.isSymbolicLink()||s.size>512*1024)fail('installed_files_invalid');
33
+ return json(file);
34
+ }
35
+ function sameTransport(actual,expected){
36
+ return actual?.type==='stdio'&&actual.command===expected.command
37
+ &&typeof actual.cwd==='string'&&path.resolve(actual.cwd)===path.resolve(expected.cwd)
38
+ &&JSON.stringify(actual.args)===JSON.stringify(expected.args)
39
+ &&JSON.stringify(actual.env_vars??[])===JSON.stringify(expected.env_vars??[])
40
+ &&!Object.keys(actual.env??{}).length;
41
+ }
42
+ async function managedTransport(installed,versions,serverName,profile,configFile){
43
+ if(!installed)return null;
44
+ const root=installed.source?.path;
45
+ if(installed.source?.source!=='local'||typeof root!=='string'
46
+ ||!/^\d+\.\d+\.\d+$/.test(installed.version??'')||root!==path.join(versions,installed.version))fail('existing_registration_requires_review');
47
+ const directory=await info(root),definition=await info(path.join(root,'.mcp.json'));
48
+ if(!directory?.isDirectory()||directory.isSymbolicLink()||!definition?.isFile()||definition.isSymbolicLink())fail('installed_files_invalid');
49
+ const ready=await privateRead(path.join(root,'installation.json'));
50
+ if(!ready||ready.profile!==profile||ready.configFile!==configFile||ready.version!==installed.version)fail('existing_registration_requires_review');
51
+ const bytes=await readFile(path.join(root,'.mcp.json')),entry=ready.files?.find(x=>x.path==='.mcp.json');
52
+ if(!entry||entry.bytes!==bytes.length||entry.sha256!==hash(bytes))fail('installed_files_invalid');
53
+ const mcp=JSON.parse(bytes).mcpServers?.[serverName];
54
+ if(!mcp||typeof mcp.command!=='string'||!mcp.command||mcp.cwd!==root
55
+ ||JSON.stringify(mcp.args)!==JSON.stringify([path.join(root,'bin/promptframe-creation.mjs'),'bridge','--config',configFile]))fail('existing_registration_requires_review');
56
+ return mcp;
57
+ }
58
+ async function officialNpmInstallation(installed,servers,env,profile,configFile){
59
+ if(profile!=='default'||configFile!==profileCredentialsPath('default',env))return null;
60
+ const candidates=installed.filter(p=>p.enabled===true&&p.name==='promptframe-creation'
61
+ &&p.pluginId==='promptframe-creation@'+p.marketplaceName&&/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,140}$/.test(p.marketplaceName??'')
62
+ &&/^\d+\.\d+\.\d+$/.test(p.version??'')&&p.source?.source==='npm'
63
+ &&p.source.package==='@promptframe/creation'&&p.source.version===p.version
64
+ &&['https://registry.npmjs.org','https://registry.npmjs.org/'].includes(p.source.registry));
65
+ if(candidates.length>1)fail('existing_registration_requires_review');
66
+ if(!candidates.length)return null;
67
+ const p=candidates[0],root=path.join(path.resolve(env.CODEX_HOME??path.join(homedir(),'.codex')),'plugins/cache',p.marketplaceName,p.name,p.version);
68
+ const directory=await info(root);if(!directory?.isDirectory()||directory.isSymbolicLink())fail('installed_files_invalid');
69
+ const pkg=await packageJSON(path.join(root,'package.json')),manifest=await packageJSON(path.join(root,'.codex-plugin/plugin.json'));
70
+ if(pkg.name!=='@promptframe/creation'||pkg.version!==p.version||manifest.name!==p.name||manifest.version!==p.version)fail('installed_files_invalid');
71
+ const definition=(await packageJSON(path.join(root,'.mcp.json'))).mcpServers?.promptframe;
72
+ if(!definition||definition.command!=='node'||definition.cwd!=='.'
73
+ ||JSON.stringify(definition.args)!==JSON.stringify(['bin/promptframe-creation.mjs','bridge'])
74
+ ||JSON.stringify(definition.env_vars)!==JSON.stringify(['PROMPTFRAME_CREATION_CONFIG','XDG_CONFIG_HOME']))fail('legacy_mcp_entry_requires_review');
75
+ if(servers.length!==1||servers[0].enabled!==true||!sameTransport(servers[0].transport,{...definition,cwd:root})
76
+ ||JSON.stringify(servers[0].transport.env_vars)!==JSON.stringify(definition.env_vars))fail('legacy_mcp_entry_requires_review');
77
+ // Keep the host's verified npm registration and running cache. Do not create a
78
+ // second effective plugin or delete an active cache to migrate it.
79
+ return{version:p.version,profile,configFile,pluginId:p.pluginId,versionRoot:root,currentFile:null,
80
+ reused:true,installedFiles:0,registered:true,reloadRequired:false};
81
+ }
82
+ async function atomicJSON(file,value){
83
+ const temp=file+'.'+randomBytes(12).toString('hex')+'.tmp';
84
+ try{await writeFile(temp,JSON.stringify(value,null,2)+'\n',{flag:'wx',mode:0o600});await rename(temp,file);}
85
+ finally{await rm(temp,{force:true});}
86
+ }
87
+ async function packageFiles(root){
88
+ const files=[];let bytes=0;
89
+ async function walk(relative){
90
+ const s=await info(path.join(root,relative));
91
+ if(!s||s.isSymbolicLink())fail('package_file_invalid');
92
+ if(s.isDirectory()){
93
+ for(const name of (await readdir(path.join(root,relative))).sort()){
94
+ if(name==='node_modules'||name==='credentials.json'||name.startsWith('.env'))fail('package_file_invalid');
95
+ await walk(path.join(relative,name));
96
+ }
97
+ }else if(s.isFile()){
98
+ if(s.size>32*1024*1024)fail('package_too_large');
99
+ const body=await readFile(path.join(root,relative));bytes+=body.length;
100
+ if(files.length>=1024||bytes>32*1024*1024)fail('package_too_large');
101
+ files.push({path:relative,bytes:body.length,sha256:hash(body),body});
102
+ }else fail('package_file_invalid');
103
+ }
104
+ for(const name of entries)await walk(name);
105
+ for(const name of ['dist/cli.mjs','dist/THIRD_PARTY_NOTICES.txt','skills/creation-setup/SKILL.md','skills/video-creation/SKILL.md'])
106
+ if(!files.some(f=>f.path===name))fail('package_incomplete');
107
+ const pkg=JSON.parse(files.find(f=>f.path==='package.json').body),plugin=JSON.parse(files.find(f=>f.path==='.codex-plugin/plugin.json').body);
108
+ if(pkg.name!=='@promptframe/creation'||!/^\d+\.\d+\.\d+$/.test(pkg.version)||plugin.version!==pkg.version)fail('package_identity_invalid');
109
+ return{files,version:pkg.version,payloadDigest:hash(JSON.stringify(files.map(({path,bytes,sha256})=>({path,bytes,sha256}))))};
110
+ }
111
+ async function acquire(root,signal){
112
+ const lock=path.join(root,'install.lock');
113
+ const end=Date.now()+30_000;let owned=false;
114
+ while(!owned){
115
+ signal?.throwIfAborted();
116
+ try{await mkdir(lock,{mode:0o700});owned=true;}
117
+ catch(e){if(e.code!=='EEXIST')throw e;if(Date.now()>=end)fail('in_progress_or_interrupted_keep_existing');await pause(50);}
118
+ }
119
+ try{await writeFile(path.join(lock,'owner.json'),JSON.stringify({pid:process.pid,startedAt:new Date().toISOString()}),{flag:'wx',mode:0o600});}
120
+ catch(e){await rm(lock,{recursive:true,force:true});throw e;}
121
+ return()=>rm(lock,{recursive:true,force:true});
122
+ }
123
+ export async function runCodexCommand(args,{env=process.env}={}){
124
+ try{return(await execute('codex',args,{env,encoding:'utf8',timeout:30_000,maxBuffer:2*1024*1024})).stdout;}
125
+ catch(e){throw new CreationClientError(e.code==='ENOENT'?'installation.codex_required':'installation.codex_command_unconfirmed');}
126
+ }
127
+ async function runNode(root,version){
128
+ try{const result=await execute(process.execPath,[path.join(root,'bin/promptframe-creation.mjs'),'--version'],{encoding:'utf8',timeout:10_000,maxBuffer:8192});
129
+ if(result.stdout.trim()!==version)fail('runtime_version_mismatch');
130
+ }catch(e){if(e instanceof CreationClientError)throw e;fail('runtime_check_failed');}
131
+ }
132
+
133
+ /** No daemon or global environment switch. All writes are confined to this
134
+ * user's managed profile. Host registration uses Codex's ordinary commands.
135
+ * Completed versions are retained: a running bridge may still use any of them. */
136
+ export async function installForUser({sourceRoot,profile='default',env=process.env,
137
+ configFile=profileCredentialsPath(profile,env),runCodex=args=>runCodexCommand(args,{env}),
138
+ checkRuntime=runNode,signal}={}){
139
+ validProfile(profile);
140
+ const versionOutput=await runCodex(['--version']);
141
+ const match=versionOutput.match(/codex-cli (\d+)\.(\d+)\.(\d+)/);
142
+ if(!match||Number(match[1])===0&&Number(match[2])<160)fail('codex_0160_required');
143
+ const payload=await packageFiles(path.resolve(sourceRoot));
144
+ const root=path.resolve(env.XDG_DATA_HOME??path.join(homedir(),'.local/share'),'promptframe-creation',profile);
145
+ await privateDirectory(root);const release=await acquire(root,signal);
146
+ const versions=path.join(root,'versions'),currentFile=path.join(root,'current.json');
147
+ const marketplaceFile=path.join(root,'.agents/plugins/marketplace.json');
148
+ const pluginName='promptframe-creation'+(profile==='default'?'':'-'+profile),marketplace='promptframe-creation-user'+(profile==='default'?'':'-'+profile);
149
+ const pluginId=pluginName+'@'+marketplace;
150
+ const versionRoot=path.join(versions,payload.version),temporary=path.join(versions,'.partial-'+randomBytes(12).toString('hex'));
151
+ let previousCatalog,previous,registrationStarted=false,newFiles=0;
152
+ try{
153
+ signal?.throwIfAborted();await privateDirectory(versions);await privateDirectory(path.dirname(marketplaceFile));
154
+ previous=await privateRead(currentFile);previousCatalog=await privateRead(marketplaceFile);
155
+ if(previous&&(previous.profile!==profile||previous.pluginId!==pluginId||previous.configFile!==configFile))fail('profile_binding_conflict');
156
+ const state=JSON.parse(await runCodex(['plugin','list','--json']));
157
+ const installed=state.installed?.find(x=>x.pluginId===pluginId);
158
+ const legacy=JSON.parse(await runCodex(['mcp','list','--json']));
159
+ const serverName='promptframe'+(profile==='default'?'':'-'+profile);
160
+ const servers=legacy.filter(x=>x.name===serverName);
161
+ const official=await officialNpmInstallation(state.installed??[],servers,env,profile,configFile);
162
+ if(official){if(installed||previous)fail('existing_registration_requires_review');return official;}
163
+ const recorded=await managedTransport(installed,versions,serverName,profile,configFile);
164
+ if(legacy.some(x=>{
165
+ if(x.name!==serverName)return false;
166
+ return !recorded||!sameTransport(x.transport,recorded);
167
+ }))fail('legacy_mcp_entry_requires_review');
168
+ const target=await info(versionRoot);
169
+ if(target){
170
+ if(!target.isDirectory()||target.isSymbolicLink())fail('version_content_conflict');
171
+ const ready=await privateRead(path.join(versionRoot,'installation.json'));
172
+ if(!ready||ready.payloadDigest!==payload.payloadDigest||ready.profile!==profile||ready.configFile!==configFile)fail('version_content_conflict');
173
+ for(const f of ready.files){
174
+ if(!payload.files.some(p=>p.path===f.path))fail('installed_files_invalid');
175
+ const file=path.join(versionRoot,f.path),s=await info(file);
176
+ if(!s?.isFile()||s.isSymbolicLink()||s.size!==f.bytes||hash(await readFile(file))!==f.sha256)fail('installed_files_invalid');
177
+ }
178
+ if(ready.files.length!==payload.files.length)fail('installed_files_invalid');
179
+ }else{
180
+ await mkdir(temporary,{mode:0o700});
181
+ for(const f of payload.files){signal?.throwIfAborted();await mkdir(path.dirname(path.join(temporary,f.path)),{recursive:true,mode:0o700});await writeFile(path.join(temporary,f.path),f.body,{flag:'wx',mode:0o600});}
182
+ const manifest=await json(path.join(temporary,'.codex-plugin/plugin.json'));manifest.name=pluginName;
183
+ await writeFile(path.join(temporary,'.codex-plugin/plugin.json'),JSON.stringify(manifest,null,2)+'\n');
184
+ const mcp={mcpServers:{['promptframe'+(profile==='default'?'':'-'+profile)]:{
185
+ command:process.execPath,args:[path.join(versionRoot,'bin/promptframe-creation.mjs'),'bridge','--config',configFile],cwd:versionRoot,
186
+ }}};
187
+ await writeFile(path.join(temporary,'.mcp.json'),JSON.stringify(mcp,null,2)+'\n');
188
+ await checkRuntime(temporary,payload.version);
189
+ const files=[];for(const f of payload.files){const body=await readFile(path.join(temporary,f.path));files.push({path:f.path,bytes:body.length,sha256:hash(body)});}
190
+ await atomicJSON(path.join(temporary,'installation.json'),{version:payload.version,profile,configFile,payloadDigest:payload.payloadDigest,files});
191
+ signal?.throwIfAborted();await rename(temporary,versionRoot);newFiles=payload.files.length;
192
+ }
193
+ const complete={version:payload.version,profile,configFile,pluginId,versionRoot,payloadDigest:payload.payloadDigest};
194
+ const already=previous?.version===payload.version&&previous.payloadDigest===payload.payloadDigest&&installed?.version===payload.version&&installed.enabled===true;
195
+ if(!already){
196
+ const catalog={name:marketplace,interface:{displayName:'PromptFrame Creation'},plugins:[{name:pluginName,
197
+ source:{source:'local',path:'./versions/'+payload.version},policy:{installation:'AVAILABLE',authentication:'ON_USE'},category:'Productivity'}]};
198
+ await atomicJSON(marketplaceFile,catalog);signal?.throwIfAborted();registrationStarted=true;
199
+ await runCodex(['plugin','marketplace','add',root,'--json']);
200
+ await runCodex(['plugin','add',pluginId,'--json']);
201
+ const observed=JSON.parse(await runCodex(['plugin','list','--json'])).installed?.find(x=>x.pluginId===pluginId);
202
+ if(observed?.version!==payload.version||observed.enabled!==true)fail('registration_unconfirmed');
203
+ await atomicJSON(currentFile,complete);
204
+ }
205
+ return{...complete,currentFile,reused:newFiles===0,installedFiles:newFiles,registered:true,reloadRequired:!already,
206
+ recordedRuntimeRetained:Boolean(already&&recorded&&recorded.command!==process.execPath)};
207
+ }catch(error){
208
+ if(registrationStarted){
209
+ // A lost command result may already have installed the complete candidate.
210
+ // Keep all versions and the old default; never delete a possibly running copy.
211
+ if(previousCatalog){
212
+ await atomicJSON(marketplaceFile,previousCatalog);
213
+ // Compensate only our exact earlier registration. If the command outcome
214
+ // cannot be verified, report pending; the old files/default remain intact.
215
+ if(previous){try{
216
+ await runCodex(['plugin','add',pluginId,'--json']);
217
+ const restored=JSON.parse(await runCodex(['plugin','list','--json'])).installed?.find(x=>x.pluginId===pluginId);
218
+ if(restored?.version!==previous.version||restored.enabled!==true)fail('registration_unconfirmed');
219
+ }catch{ /* No deletion, retry loop, token replacement or claim of restoration. */ }}
220
+ }
221
+ else await rm(marketplaceFile,{force:true});
222
+ fail('registration_unconfirmed_keep_existing');
223
+ }
224
+ if(error instanceof CreationClientError)throw error;
225
+ if(signal?.aborted)fail('interrupted_keep_existing');
226
+ fail('failed_keep_existing');
227
+ }finally{await rm(temporary,{recursive:true,force:true});await release();}
228
+ }
@@ -0,0 +1,2 @@
1
+ export const CLIENT_VERSION = "0.2.2";
2
+ export const CLIENT_PROTOCOL = "creation-client/v1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promptframe/creation",
3
- "version": "0.1.1",
3
+ "version": "0.2.2",
4
4
  "private": false,
5
5
  "description": "PromptFrame video creation Skill, Codex plugin and MCP client bridge.",
6
6
  "repository": {
@@ -9,6 +9,7 @@
9
9
  },
10
10
  "files": [
11
11
  "bin/",
12
+ "dist/",
12
13
  "lib/",
13
14
  "skills/",
14
15
  "docs/",
@@ -29,9 +30,11 @@
29
30
  "promptframe-creation": "bin/promptframe-creation.mjs"
30
31
  },
31
32
  "scripts": {
32
- "test": "node --test --test-concurrency=1 test/*.test.mjs"
33
+ "test": "npm run build && node --test --test-concurrency=1 test/*.test.mjs",
34
+ "build": "node scripts/build-runtime.mjs"
33
35
  },
34
- "dependencies": {
35
- "@modelcontextprotocol/sdk": "1.32.1"
36
+ "devDependencies": {
37
+ "@modelcontextprotocol/sdk": "1.32.1",
38
+ "esbuild": "0.27.7"
36
39
  }
37
40
  }
@@ -0,0 +1,20 @@
1
+ ---
2
+ name: creation-setup
3
+ description: 安装、连接或升级 PromptFrame Creation 的 Codex 插件,复用平台创作授权并检查 Skill 和 MCP 是否已加载。已有连接的普通视频创作使用 video-creation。
4
+ ---
5
+
6
+ # 连接 PromptFrame
7
+
8
+ 使用 Studio“连接与授权”提供的完整 API 地址及公开安装入口。保留用户当前环境的 origin 和 `/api`,不替换成 localhost,不从旧聊天猜另一账号或环境。
9
+
10
+ 在用户本机终端运行 `npx --yes @promptframe/creation connect --endpoint <Studio提供的API地址>`。需要隔离另一个环境或账号时显式加 `--profile <用户选择的名称>`;正在运行的桥不会切换。此命令管理用户级版本和 Codex 插件,不向当前项目安装依赖。
11
+
12
+ 命令会复用并验证有效凭据。首次授权或明确更换已失效凭据时,由用户在 Studio 登录并在终端的不回显输入框提供 Token;不要要求用户把 Token 粘进聊天,也不要把它写进命令参数、URL或日志。网络失败不等于授权失效,不自动轮换或覆盖凭据。
13
+
14
+ 区分安装完成、平台连接成功和当前聊天已加载。首次安装或升级后按命令结果正常重载插件或开新聊天。检查宿主是否同时发现此安装的 setup/video-creation Skill 和 PromptFrame MCP 工具;`npx` 执行成功或 `status` 能读目录不代表当前聊天已有插件。只有真实宿主工具调用带来的身份经平台接受,才确认当前聊天可用;不要向模型参数补 threadId、Token、controlVersion 或 controller。
15
+
16
+ 连接后按用户意图新建或选择作品。歧义名称让用户选目标,不重装、不覆盖原作品。先动态读取平台目录和工具 schema;编辑权申请在 Studio 明确确认,安装本身不会接管作品或启动付费制作。已有任务保留原 task/idempotency,升级或断线后先观察,不重新派发。
17
+
18
+ 如需自行开发组件,沿 README 的独立组件 authoring Skill/CLI;普通创作与平台组件复用不要求安装四个组件包。
19
+
20
+ 出现 `installation.*` 或 `setup.*` 时保留旧版本、凭据及明确错误。不要删除不明配置、终止其它聊天或反复重装追绿。卸载和排障见包内[安装与排障](../../docs/installing.md)。
@@ -33,7 +33,7 @@ CLI 的端点与组件上传授权按其公开说明配置,创作 Token 不代
33
33
 
34
34
  正式制作需要已保存 Plan 和平台本人点击开始。把平台返回的确认状态与准确 Studio 入口交给用户;工具参数、已打开网页和 URL 都不能代为批准。批准后由当前外部客户端继续,不启动第二个网页导演。
35
35
 
36
- 每次新动作使用当前编辑权 controlVersion 与平台作品 revision。失权后停止新派发和写入,重新读事实;不要把旧整份 Spec 覆盖当前作品。预算沿同一作品的原有段,不把换工具、换端或新 task 当作重置额度。
36
+ 宿主自动提供当前 Codex thread 身份,薄桥按本线程已获批准的编辑权携带 controlVersion;不要在工具参数中自行填写或猜测 threadId、controller、Token 或 controlVersion。作品 revision 仍须按真实读取结果用于原业务并发检测,薄桥不会替你填最新内容版本。失权后停止新派发和写入,重新读事实并按需申请由本人在 Studio 确认;不要把旧整份 Spec 覆盖当前作品。原 task 仍用原身份查询,不借接管重派。预算沿同一作品的原有段,不把换工具、换端或新 task 当作重置额度。
37
37
 
38
38
  长工具返回持久 task ID;保存它和原订单身份,用有上限的 wait/状态读取接续。RPC 结束或没再 poll 都不取消原订单。网络结果不明时先查询原 task,重试用同一个幂等键,不自动重派。保留原输入、期限和未知事实。
39
39