@promptframe/creation 0.2.6 → 0.3.0

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.
@@ -8,10 +8,13 @@
8
8
  | --- | --- |
9
9
  | 命令和 stdio 桥 | `bin/promptframe-creation.mjs`预检 → `lib/cli.mjs` / `dist/cli.mjs`自包含构建 |
10
10
  | 用户级安装与profile | `lib/user-installation.mjs` |
11
+ | Claude Code 本机入口和插件登记 | `lib/claude-command.mjs`、`lib/claude-installation.mjs` |
12
+ | Claude 独立 MCP/Skill 备用登记与本地配置读面 | `lib/claude-mcp-installation.mjs`、`lib/claude-local-state.mjs` |
11
13
  | 依赖闭包/许可证 | `scripts/build-runtime.mjs` |
12
14
  | 环境地址与安全凭据 | `lib/credentials.mjs` |
13
15
  | 平台 MCP HTTP 连接 | `lib/connection.mjs` |
14
16
  | 当前源码的宿主 thread 与控制版本接线 | `lib/host-context.mjs` |
17
+ | 新会话固定版本选择、完整性缓存与 stdio 接续 | `lib/runtime-bootstrap.mjs`、`lib/runtime-package.mjs`、`lib/runtime-launch.mjs` |
15
18
  | 插件加载与启动 | `.codex-plugin/plugin.json`、`.mcp.json` |
16
19
  | 公开视频创作规则 | `skills/video-creation/SKILL.md` |
17
20
  | 插件目录索引 | `.agents/plugins/marketplace.json` |
@@ -29,7 +32,17 @@
29
32
 
30
33
  ## 安装与运行路径
31
34
 
32
- 宿主桥为受支持的业务只读和 Skill 说明工具附加平台返回的作品控制版本。Web 或另一聊天正在编辑时,仍可按读取权限查询。`skill_view` 的 usage 省略或为 view/none 时读取说明,为 use 时需要编辑和执行权限。读取的控制版本不会授予编辑权;服务端同时检查工具注册表的只读属性和白名单,写操作仍需当前聊天的编辑权。项目入门 `platform_read_onboarding` 不依赖作品或编辑控制,由 Token 和项目 ACL 验证访问权限。此能力已随 npm 0.2.5 发行,0.2.4 不包含;平台服务也需要支持对应工具合同。
35
+ 当前源码的薄桥从平台目录读取工具分类和协议角色,按固定响应元数据管理作品控制版本。Web 或另一聊天编辑时,独立读取仍受项目和素材权限约束;执行与修改需要当前聊天编辑权。工具名称、正文中的同名字段和模型传入的分类都不会授予权限。目录版本变化在后续正常交互中发送标准工具目录变更通知,不额外轮询平台或替换活动进程。
36
+
37
+ 当前源码按平台握手结果提供标准 resources/prompts 读取。项目公开指引复用平台已验证的创作基线;资源 URI 由平台解析,每次读取重新检查账号和项目权限。带版本的引用遇到正文版本变化会提示重新列取,不静默替换内容。桥保留标准正文和元数据,按序列化 UTF-8 计算单块400000字节、整次2000000字节上限;超限不会重执行业务。后续正常读取观察到版本变化时发送对应目录通知,不启动后台轮询。未声明这些能力的平台仍可通过原工具入口读取入门说明。源码能力、公开包和宿主实际支持分别核实。
38
+
39
+ 当前源码在新会话启动时读取平台初始化中的 `experimental.promptframe.creation` 兼容声明。在接收宿主工具调用前,按真实版本检查 `minBridge`,从官方 npm registry 获取固定的 `recommendedBridge`;`--bridge-version X.Y.Z` 可锁定一个兼容版本。下载只允许公开的 `@promptframe/creation` 固定版本,核 SHA-512 integrity、包身份及自包含运行文件后,再原子放入私有缓存。缓存按完整文件摘要复核,同版本不能更换完整性摘要,准备过程不运行安装脚本或注册宿主。新进程继承同一凭据路径和冻结的宿主会话身份,活动桥不被替换。
40
+
41
+ 获取或校验失败时,只有当前程序已经达到已知最低版本才可继续;显式锁定失败不会另选版本。平台缺少兼容声明时提示先更新平台。缓存位于安全凭据目录下的 `runtime-cache`,不会自动删除旧版本或清除不明准备锁。新运行进程启动后的错误不会触发第二次桥启动。
42
+
43
+ 外部宿主可在初始化声明 `experimental.promptframe.contentTypes`,桥只转发已知种类,未声明时使用明确的文字降级。媒体能力来自宿主声明,不从模型或宿主名称推断;真实桌面是否展示图片、音频和资源仍需分别验证。源码、公开包及实际宿主加载分别核实。
44
+
45
+ `bridge --host codex`使用宿主提供的threadId;`bridge --host claude-code`使用启动环境中的`CLAUDE_CODE_SESSION_ID`。未指定host时,`CLAUDECODE=1`选择Claude Code,其余选择Codex。Claude会话ID缺失时,本进程使用临时UUID;下次启动不能据此保留原编辑身份。无效会话ID会报错,不从调用参数接受替代值。公开发行与两种桌面宿主的实际加载分别核实。
33
46
 
34
47
  源码经 GitHub Actions 打包发行到 npm;插件目录记录包名/版本或源码位置。安装后,Codex 加载本地副本并按配置启动 Node 桥;桥通过 stdio 接收调用,读取独立安全配置,再通过 HTTPS MCP 连接所选平台。GitHub、npm 与目录索引负责获取版本,不进入正常工具调用链。Token 不进入源码、插件包或命令参数。
35
48
 
@@ -52,3 +65,5 @@
52
65
  安装发现使用 `$CODEX_HOME/config.toml` 的结构化插件登记 ID、`codex plugin marketplace list --json` 的本地根索引、有界目录 JSON 和 `plugin list --marketplace <name> --json`。TOML 使用随运行文件打包的成熟解析器,只保留相关插件身份;目录条目删除后仍查询原登记,读面无法解析该登记就保持 unknown。覆盖全部相关入口,不把不可读目录当未安装,也不调用必需全量远端插件查询。注册前持久保存 pending 登记;注册请求未确认时先查询该登记状态,确认前不重复 add 或回退旧登记。测试从 pack 的实际 npx/connect 入口核隔离配置、两个 profile、并发和失 ACK,不读个人配置。
53
66
 
54
67
  宿主插件已安装/启用、平台连接验证与聊天加载分别报告。外部安装器不接私有 app-server 生产刷新通道;当前使用官方新聊天/新 session 路径,选择 Local 和独立非 Git 目录即可。候选包、公共 registry 固定包和真实宿主新聊天工具/两个 Skill 的验收分开记录。
68
+
69
+ Claude Code 使用官方 `plugin list --json` 与 `plugin marketplace list --json` 读取登记,不调用会健康检查 MCP 的 `mcp list/get`。本地 marketplace 的 `readFromFolder/folderVersion` 表示实际读取目录,与安装记录的缓存路径分别核对;版本目录及两份 MCP 定义均验证摘要。每个登记写前保存阶段,回程未知后只观察原身份。隔离 CLI 安装不等于桌面模型会话加载。
@@ -0,0 +1,36 @@
1
+ {
2
+ "schemaVersion": "creation-install-guidance/v1",
3
+ "package": "@promptframe/creation",
4
+ "version": "0.3.0",
5
+ "hosts": [
6
+ {
7
+ "kind": "codex",
8
+ "name": "Codex",
9
+ "minimumBridge": "0.2.3",
10
+ "requirements": "Node.js 20+ 与支持插件的 Codex(最低0.160.0)",
11
+ "commandArgs": [
12
+ "connect",
13
+ "--endpoint",
14
+ "{{endpoint}}"
15
+ ],
16
+ "nextSession": "在同一主机打开 Local 新聊天;CLI 使用新 session。"
17
+ },
18
+ {
19
+ "kind": "claude-code",
20
+ "name": "Claude Code",
21
+ "minimumBridge": "0.3.0",
22
+ "requirements": "Node.js 20+ 与 Claude Code 2.0.12+,或桌面版提供的同机远程入口",
23
+ "commandArgs": [
24
+ "connect",
25
+ "--host",
26
+ "claude-code",
27
+ "--endpoint",
28
+ "{{endpoint}}"
29
+ ],
30
+ "nextSession": "在同一主机开始新的 Claude Code session;桌面版远程连接 WSL 时在该 WSL 安装。"
31
+ }
32
+ ],
33
+ "versionInstructions": "比较已安装版本:同版本复用,更新版本不降级;待升级或 Node 不可用时按明确指引处理,不把旧版复用当作升级成功。",
34
+ "credentialInstructions": "复用已有有效授权,不轮换 Token。首次 Token 仅在本机终端隐藏输入,不放进聊天。",
35
+ "loadingInstructions": "确认 creation-setup/video-creation Skill 与 MCP 都已加载;保留原 Token,无需重装或产品源码。"
36
+ }
@@ -1,12 +1,12 @@
1
1
  # 安装、连接与升级
2
2
 
3
- 需要 Node.js 20+、支持插件命令的 Codex(本版最低0.160.0),以及可以访问 Studio 的网络。原生 Windows ACL 尚未验证;Linux、WSL、macOS 使用用户目录和私有文件权限,不需要 sudo。
3
+ 需要 Node.js 20+,支持插件命令的 Codex0.160.0+ 或 Claude Code2.0.12+,以及可以访问 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.2.6 connect --endpoint <Studio提供的API地址>
9
+ npx --yes @promptframe/creation@0.3.0 connect --endpoint <Studio提供的API地址>
10
10
  ```
11
11
  <!-- /creation-install-command -->
12
12
 
@@ -20,6 +20,24 @@ npx --yes @promptframe/creation@0.2.6 connect --endpoint <Studio提供的API地
20
20
 
21
21
  安装输出分别报告插件已安装、已启用、平台凭据连接已核验;`hostMcpConnected` 与 `sessionLoaded` 在安装器中仍为 `not_verified`。当前聊天是否已加载,要由该聊天实际发现 Skill 和调用 MCP 只读工具验证。若宿主将来提供明确受支持的同会话刷新入口,也须同时核回这两类能力后才能报告加载成功。
22
22
 
23
+ ## Claude Code 接入
24
+
25
+ 在 Claude Code 所在主机使用同一固定包和独立宿主参数。桌面版连接 WSL 时,在该 WSL 运行:
26
+
27
+ <!-- creation-install-command -->
28
+ ```bash
29
+ npx --yes @promptframe/creation@0.3.0 connect --host claude-code --endpoint <Studio提供的API地址>
30
+ ```
31
+ <!-- /creation-install-command -->
32
+
33
+ CLI 优先使用 PATH 中的 Claude;桌面版远程连接 WSL 时,也识别同一用户桌面端管理的实际远程构建。可用 `--claude-bin <绝对可执行文件>` 明确指定入口。不会启动 Claude 模型会话或固定桌面构建文件名。
34
+
35
+ 两个宿主共用所选 profile 的安全凭据,插件登记和版本目录独立。Claude 适配通过官方 user-scope 本地 marketplace/install 命令注册,再读取完整插件身份、实际版本目录、MCP 定义和文件摘要;当前聊天是否加载仍需在同一主机的新 Claude Code session 检查两个 Skill 与 MCP。安装期间不会替换活动桥或清理旧版本。登记回程未知时只核原身份,不能重复 install 或改用另一登记方式。已有同名手工 MCP、其它来源或不明目录需要先核实,不自动覆盖。
36
+
37
+ 本机隔离检查覆盖 CLI 插件登记与版本复用;桌面版真实加载、恢复会话和编辑权仍单独验证。原生 Windows ACL 尚未验证。
38
+
39
+ 启动帮助明确不提供插件命令时,安装器使用官方 user-scope MCP 登记并准备两份用户 Skill。返回 `installationMode: mcp-and-skills`、`pluginInstalled: false` 与实际 Skill 名称;不同 profile 分开命名,原凭据保持。MCP 写后从本地配置核回,不通过 `mcp list/get` 启动健康检查。已有陌生 MCP/Skill 或未确认的插件安装不会转到备用路径;备用 MCP 的回程未知也只核原身份,不重复 add。以后宿主增加插件命令时保留现有备用登记,避免同一 profile 两份连接。
40
+
23
41
  ## 环境与账号
24
42
 
25
43
  默认凭据沿用 `$XDG_CONFIG_HOME/promptframe-creation/credentials.json`(未配置 XDG 时位于用户 `.config`)。旧的 `PROMPTFRAME_CREATION_CONFIG` 仍可显式引用安全文件。
@@ -28,7 +46,7 @@ npx --yes @promptframe/creation@0.2.6 connect --endpoint <Studio提供的API地
28
46
 
29
47
  <!-- creation-install-command -->
30
48
  ```bash
31
- npx --yes @promptframe/creation@0.2.6 connect --profile work-account --endpoint <另一环境API地址>
49
+ npx --yes @promptframe/creation@0.3.0 connect --profile work-account --endpoint <另一环境API地址>
32
50
  ```
33
51
  <!-- /creation-install-command -->
34
52
 
@@ -36,6 +54,8 @@ npx --yes @promptframe/creation@0.2.6 connect --profile work-account --endpoint
36
54
 
37
55
  ## 版本与失败
38
56
 
57
+ 新会话启动时,根据平台给出的最低和推荐版本选择兼容的固定 npm 包。包从官方 registry 获取并校验完整性,已校验缓存可以复用;Token、profile 和会话身份保持。可在桥启动配置中加 `--bridge-version X.Y.Z` 锁定版本,锁定低于最低要求时会明确拒绝。获取失败时仅兼容的当前程序可继续;显式锁定失败不会悄悄使用另一个版本。活动聊天的桥不被替换,源码中的新启动能力也不会自动出现在既有旧版插件中。
58
+
39
59
  推荐版本由 Studio 当前连接指引提供,入口每次对照命令中的固定版本检查安装。同版本复用;受管旧版准备新版并切换后续入口;已安装更新版返回 `newer_retained`,不降级。没有后台自动追踪 latest;再次连接时从 Studio 复制当前指令,不沿用旧聊天中的版本。
40
60
 
41
61
  每个 profile 的安装位于 `$XDG_DATA_HOME/promptframe-creation/<profile>`(默认用户 `.local/share`),版本在 `versions/<version>`。同版本完整内容复用,不再次下载运行依赖;两个入口串行合并。新版本先完整准备和检查,再注册并原子更新 `current.json`。旧版本及其依赖保留,不覆盖、不枚举或终止其它聊天。
@@ -0,0 +1,5 @@
1
+ # 0.2.7 作品用量读取
2
+
3
+ Studio 或另一聊天正在编辑作品时,创作客户端可以按原账号、项目和作品读取权限查询该作品的平台用量。读取不会接管编辑权,也不会新建制作任务或改变账本;生成、修改和显式 Skill 使用仍需要原编辑与执行权限。
4
+
5
+ 该读取需要相容的平台服务。按 Studio 提供的固定版本升级,保留原 profile 和有效凭据;安装后在同一主机的新聊天中检查插件加载状态。已发布的版本和标签保持不变。
@@ -0,0 +1,10 @@
1
+ # 0.3.0
2
+
3
+ 支持 Codex 与 Claude Code 使用同一平台创作授权。两个宿主分别登记,命名 profile 隔离环境与账号;默认客户端名称按宿主显示,自定义名称保留。
4
+
5
+ - Claude Code 通过官方用户级插件命令安装。插件命令不可用时可准备独立 MCP 和两份用户 Skill,安装结果明确区分这两种方式。登记回程未知时先核原身份,不重复登记或覆盖其它配置。
6
+ - 桥从平台目录发现工具和访问类别,转发标准 text、image、audio、resource_link、resource 及结构化结果。媒体表示按宿主实际声明选择,预算按序列化 UTF-8 核验;超限降级不会重复执行业务。
7
+ - 公开创作基线可通过版本化 resources/prompts 读取,逐次检查账号和项目权限。正常交互观察到目录变化后发送相应通知,不在空闲期轮询平台。
8
+ - 新会话按平台最低/推荐桥版本选择固定官方包,校验完整性并使用私有缓存;`--bridge-version X.Y.Z` 可锁定兼容版本。活动桥不被替换,已受理任务保持原身份与期限。
9
+
10
+ 需要 Node.js20+ 和相容的平台服务。已有旧版插件保持原安装来源;按安装说明升级后,在同一主机的新聊天中检查两个 Skill 和 MCP 加载状态。原生 Windows ACL、具体桌面版本的媒体展示和恢复体验分别验证。平台工具可提供的素材与检查能力,以当前目录为准。
@@ -0,0 +1,54 @@
1
+ import {CreationClientError} from './credentials.mjs';
2
+ import {MCP_BLOCK_BYTES,MCP_RESPONSE_BYTES} from './content-budget.mjs';
3
+
4
+ export const CONTENT_TYPES=Object.freeze(['text','image','audio','resource_link','resource']);
5
+ const versionParts=value=>{
6
+ if(typeof value!=='string'||value.length>40||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value))
7
+ throw new CreationClientError('creation.bridge_policy_invalid');
8
+ const parts=value.split('.').map(Number);
9
+ if(parts.some(n=>!Number.isSafeInteger(n)))throw new CreationClientError('creation.bridge_policy_invalid');
10
+ return parts;
11
+ };
12
+ export function compareBridgeVersions(left,right){
13
+ const a=versionParts(left),b=versionParts(right);
14
+ for(let i=0;i<3;i++)if(a[i]!==b[i])return a[i]<b[i]?-1:1;
15
+ return 0;
16
+ }
17
+ export function readPlatformBridgePolicy(capabilities){
18
+ const policy=capabilities?.experimental?.['promptframe.creation'];
19
+ if(policy===undefined)return null;
20
+ if(!policy||policy.contractVersion!=='creation-bridge-capabilities/v1'
21
+ ||policy.blockMaxBytes!==MCP_BLOCK_BYTES||policy.responseMaxBytes!==MCP_RESPONSE_BYTES
22
+ ||!Array.isArray(policy.contentTypes)||policy.contentTypes.length>CONTENT_TYPES.length
23
+ ||new Set(policy.contentTypes).size!==policy.contentTypes.length||!policy.contentTypes.includes('text')
24
+ ||policy.contentTypes.some(type=>!CONTENT_TYPES.includes(type))
25
+ ||compareBridgeVersions(policy.recommendedBridge,policy.minBridge)<0)
26
+ throw new CreationClientError('creation.bridge_policy_invalid');
27
+ return Object.freeze({contractVersion:policy.contractVersion,minBridge:policy.minBridge,
28
+ recommendedBridge:policy.recommendedBridge,contentTypes:[...policy.contentTypes],
29
+ blockMaxBytes:policy.blockMaxBytes,responseMaxBytes:policy.responseMaxBytes});
30
+ }
31
+ export function assertBridgeCompatible(capabilities,version){
32
+ const policy=readPlatformBridgePolicy(capabilities);
33
+ if(policy&&compareBridgeVersions(version,policy.minBridge)<0)
34
+ throw new BridgeCompatibilityError(version,policy);
35
+ return policy;
36
+ }
37
+ class BridgeCompatibilityError extends CreationClientError{
38
+ constructor(version,policy){
39
+ super('creation.upgrade_required');
40
+ this.bridgeFacts=Object.freeze({currentVersion:version,minimumVersion:policy.minBridge,
41
+ recommendedVersion:policy.recommendedBridge,action:'upgrade_bridge_in_new_session'});
42
+ }
43
+ }
44
+ export const bridgeErrorDetails=error=>error instanceof BridgeCompatibilityError?error.bridgeFacts:undefined;
45
+
46
+ /** An unrecognized/absent host extension proves no media support. Text is the
47
+ * fallback; host/model names and the Studio director version are not probes. */
48
+ export function declaredHostContentCapabilities(capabilities){
49
+ const requested=capabilities?.experimental?.['promptframe.contentTypes'];
50
+ if(!Array.isArray(requested)||requested.length>CONTENT_TYPES.length
51
+ ||requested.some(type=>!CONTENT_TYPES.includes(type)))return{types:['text'],source:'text-fallback'};
52
+ return{types:['text',...CONTENT_TYPES.filter(type=>type!=='text'&&requested.includes(type))],source:'declared'};
53
+ }
54
+ export const declaredHostContentTypes=capabilities=>declaredHostContentCapabilities(capabilities).types;
@@ -0,0 +1,57 @@
1
+ import {execFile} from 'node:child_process';
2
+ import {promisify} from 'node:util';
3
+ import {access,lstat,readdir} from 'node:fs/promises';
4
+ import {constants} from 'node:fs';
5
+ import {homedir} from 'node:os';
6
+ import path from 'node:path';
7
+ import {CreationClientError} from './credentials.mjs';
8
+
9
+ const execute=promisify(execFile);
10
+ class ClaudeCommandError extends CreationClientError{
11
+ constructor(code,details){super('installation.'+code);this.details=details;}
12
+ }
13
+ export const claudeErrorDetails=error=>error instanceof ClaudeCommandError?error.details:undefined;
14
+ export async function resolveClaudeCommand({env=process.env,homeDirectory=homedir(),executable}={}){
15
+ const selected=executable??env.PROMPTFRAME_CLAUDE_BIN;
16
+ if(selected){
17
+ if(!path.isAbsolute(selected))throw new CreationClientError('installation.claude_executable_invalid');
18
+ await access(selected,constants.X_OK);return selected;
19
+ }
20
+ for(const directory of(env.PATH??'').split(path.delimiter).filter(path.isAbsolute)){
21
+ const file=path.join(directory,process.platform==='win32'?'claude.exe':'claude');
22
+ try{await access(file,constants.X_OK);return file;}catch(e){if(!['ENOENT','EACCES','ENOTDIR'].includes(e.code))throw e;}
23
+ }
24
+ // Desktop-managed remote builds have no PATH entry. Select by the actual
25
+ // semantic version present, never by a compiled-in desktop build filename.
26
+ const root=path.join(homeDirectory,'.claude/remote/ccd-cli');let entries;
27
+ try{entries=await readdir(root);}catch(e){if(e.code==='ENOENT')throw new CreationClientError('installation.claude_required');throw e;}
28
+ if(entries.length>32)throw new CreationClientError('installation.claude_executable_unconfirmed');
29
+ const candidates=[];
30
+ for(const name of entries){
31
+ const match=name.match(/^(\d+)\.(\d+)\.(\d+)-[a-f0-9]{6,40}$/);if(!match)continue;
32
+ const file=path.join(root,name),s=await lstat(file);
33
+ if(s.isFile()&&!s.isSymbolicLink()&&s.uid===process.getuid?.()){await access(file,constants.X_OK);candidates.push({file,version:match.slice(1).map(Number)});}
34
+ }
35
+ candidates.sort((a,b)=>b.version[0]-a.version[0]||b.version[1]-a.version[1]||b.version[2]-a.version[2]);
36
+ if(!candidates.length)throw new CreationClientError('installation.claude_required');
37
+ if(candidates[1]&&JSON.stringify(candidates[0].version)===JSON.stringify(candidates[1].version))
38
+ throw new CreationClientError('installation.claude_executable_unconfirmed');
39
+ return candidates[0].file;
40
+ }
41
+ export function createClaudeRunner({env=process.env,executable,signal,resolve=resolveClaudeCommand}={}){
42
+ let command;
43
+ return async args=>{
44
+ command??=resolve({env,executable});const binary=await command;
45
+ const write=args[0]==='mcp'&&args[1]==='add-json'
46
+ ||args[0]==='plugin'&&(args[1]==='install'||args[1]==='marketplace'&&args[2]==='add');
47
+ const kind=args[0]==='--version'?'host_version':args[1]==='marketplace'
48
+ ?write?'marketplace_register':'marketplace_read':args[0]==='mcp'?'mcp_register':write?'plugin_register':'plugin_read';
49
+ const timeoutMs=write?30000:5000,start=performance.now();
50
+ try{return(await execute(binary,args,{env,signal,encoding:'utf8',windowsHide:true,timeout:timeoutMs,maxBuffer:2*1024*1024})).stdout;}
51
+ catch(e){throw new ClaudeCommandError(e.code==='ERR_CHILD_PROCESS_STDIO_MAXBUFFER'?'command_output_limit'
52
+ :e.killed?'command_timeout':'command_failed',{phase:write?'registration':'local_check',commandKind:kind,
53
+ elapsedMs:Math.round(performance.now()-start),timeoutMs,exitCode:Number.isInteger(e.code)?e.code:null,
54
+ signal:['SIGTERM','SIGKILL','SIGINT'].includes(e.signal)?e.signal:null,localRegistrationState:'unknown',
55
+ action:write?'observe_same_registration_before_retry':'retry_local_read'});}
56
+ };
57
+ }
@@ -0,0 +1,191 @@
1
+ import {createHash,randomBytes} from 'node:crypto';
2
+ import {mkdir,open,readFile,rename,rm} from 'node:fs/promises';
3
+ import {homedir} from 'node:os';
4
+ import path from 'node:path';
5
+ import {CreationClientError} from './credentials.mjs';
6
+ import {inspectRuntimePackage} from './runtime-package.mjs';
7
+ import {profileCredentialsPath,installationFiles} from './user-installation.mjs';
8
+ import {createClaudeRunner,claudeErrorDetails} from './claude-command.mjs';
9
+ import {readClaudeUserServer} from './claude-local-state.mjs';
10
+ import {installClaudeMcpFallback} from './claude-mcp-installation.mjs';
11
+
12
+ const {info,privateDirectory,privateRead,atomicJSON,acquire,runNode,checkInstalledRuntime,compareVersions,validProfile}=installationFiles;
13
+ const hash=b=>createHash('sha256').update(b).digest('hex');
14
+ const effectiveRoot=plugin=>plugin.readFromFolder??plugin.installPath;
15
+ class ClaudeInstallationError extends CreationClientError{
16
+ constructor(code,details){super('installation.'+code);this.details=details;}
17
+ }
18
+ export const claudeInstallationDetails=error=>error instanceof ClaudeInstallationError?error.details:undefined;
19
+ const fail=(code,details)=>{throw new ClaudeInstallationError(code,details);};
20
+ async function jsonCommand(run,args){
21
+ const body=await run(args);let value;
22
+ try{if(typeof body!=='string'||Buffer.byteLength(body)>2*1024*1024)throw Error();value=JSON.parse(body);}catch{fail('claude_local_registration_unconfirmed');}
23
+ if(!Array.isArray(value)||value.length>1024)fail('claude_local_registration_unconfirmed');return value;
24
+ }
25
+ async function registrations(run,pluginName,marketplace,root){
26
+ const [plugins,markets]=await Promise.all([jsonCommand(run,['plugin','list','--json']),
27
+ jsonCommand(run,['plugin','marketplace','list','--json'])]);
28
+ if(plugins.some(p=>!p||typeof p.id!=='string'||!p.id||p.id.length>256||typeof p.scope!=='string'
29
+ ||typeof p.version!=='string'||typeof p.enabled!=='boolean'||typeof p.installPath!=='string')
30
+ ||markets.some(p=>!p||typeof p.name!=='string'||!p.name||typeof p.source!=='string'))
31
+ fail('claude_local_registration_unconfirmed');
32
+ const related=plugins.filter(p=>typeof p?.id==='string'&&p.id.startsWith(pluginName+'@'));
33
+ if(related.length>1||related.some(p=>p.id!==pluginName+'@'+marketplace||p.scope!=='user'
34
+ ||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)))
36
+ fail('claude_existing_registration_requires_review');
37
+ const found=markets.filter(p=>p?.name===marketplace);
38
+ if(found.length>1||found.some(p=>p.source!=='directory'||p.path!==root||p.installLocation!==root))
39
+ fail('claude_existing_registration_requires_review');
40
+ return{plugin:related[0],market:found[0]};
41
+ }
42
+ async function legacyUserMcp(env,serverName){
43
+ // Reading configuration does not start or health-check any MCP server.
44
+ if(await readClaudeUserServer(serverName,env))fail('legacy_mcp_entry_requires_review');
45
+ }
46
+ function transport(serverName,configFile,command=process.execPath){
47
+ return{mcpServers:{[serverName]:{command,
48
+ args:['${CLAUDE_PLUGIN_ROOT}/bin/promptframe-creation.mjs','bridge','--config',configFile,'--host','claude-code']}}};
49
+ }
50
+ async function verifyVersion(root,{version,profile,configFile,payloadDigest,pluginName,serverName}){
51
+ const directory=await info(root);
52
+ if(!directory?.isDirectory()||directory.isSymbolicLink()||directory.uid!==process.getuid?.()||(directory.mode&0o077))
53
+ fail('claude_installed_files_invalid');
54
+ const ready=await privateRead(path.join(root,'installation.json'));
55
+ if(!ready||ready.host!=='claude-code'||ready.version!==version||ready.profile!==profile||ready.configFile!==configFile
56
+ ||ready.payloadDigest!==payloadDigest||!Array.isArray(ready.files)||ready.files.length>1024)fail('claude_installed_files_invalid');
57
+ const actual=await inspectRuntimePackage(root);
58
+ if(actual.version!==version||JSON.stringify(actual.files.map(({path,bytes,sha256})=>({path,bytes,sha256})))!==JSON.stringify(ready.files))
59
+ fail('claude_installed_files_invalid');
60
+ const manifest=JSON.parse(await readFile(path.join(root,'.claude-plugin/plugin.json'),'utf8'));
61
+ if(manifest.name!==pluginName||manifest.version!==version||manifest.skills!=='./skills/'||manifest.mcpServers!=='./.claude-mcp.json')
62
+ fail('claude_installed_files_invalid');
63
+ let runtimeCommand;
64
+ for(const file of['.mcp.json','.claude-mcp.json']){
65
+ const mcp=JSON.parse(await readFile(path.join(root,file),'utf8'));
66
+ const command=mcp.mcpServers?.[serverName]?.command;
67
+ if(!path.isAbsolute(command??'')||runtimeCommand!==undefined&&command!==runtimeCommand
68
+ ||JSON.stringify(mcp)!==JSON.stringify(transport(serverName,configFile,command)))fail('claude_installed_files_invalid');
69
+ runtimeCommand=command;
70
+ }
71
+ return{...ready,runtimeCommand};
72
+ }
73
+
74
+ /** Official local-directory marketplace only. The host loads immutable version
75
+ * directories in place; this adapter never updates/prunes host caches or starts
76
+ * Claude model sessions. Codex registration and credentials stay independent. */
77
+ export async function installForClaudeUser(options={}){
78
+ const profile=options.profile??'default',env=options.env??process.env;validProfile(profile);
79
+ // One installer-owned mode guard covers selection and registration for this
80
+ // host/profile. It does not lock Claude's configuration or other clients.
81
+ const modeRoot=path.resolve(env.XDG_DATA_HOME??path.join(homedir(),'.local/share'),'promptframe-creation',profile,'claude-code-mode');
82
+ await privateDirectory(modeRoot);const release=await acquire(modeRoot,options.signal);
83
+ try{return await installClaudeUserLocked(options);}finally{await release();}
84
+ }
85
+ async function installClaudeUserLocked({sourceRoot,profile='default',env=process.env,
86
+ configFile=profileCredentialsPath(profile,env),executable,signal,
87
+ runClaude=createClaudeRunner({env,executable,signal}),checkRuntime=runNode,verifyInstalledRuntime=checkInstalledRuntime,
88
+ nodeCommand=process.execPath}={}){
89
+ validProfile(profile);
90
+ if(!path.isAbsolute(nodeCommand))fail('runtime_command_invalid');
91
+ 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');
93
+ const help=await runClaude(['--help']);
94
+ if(typeof help!=='string'||Buffer.byteLength(help)>128*1024)fail('claude_capabilities_unconfirmed');
95
+ const hasPlugin=/^\s+plugin(?:\|plugins)?\s/m.test(help),hasMcp=/^\s+mcp\s/m.test(help);
96
+ const base=path.resolve(env.XDG_DATA_HOME??path.join(homedir(),'.local/share'),'promptframe-creation',profile),
97
+ fallbackRoot=path.join(base,'claude-code-mcp'),pluginRoot=path.join(base,'claude-code');
98
+ const pluginPending=await info(path.join(pluginRoot,'registration-pending.json')),pluginCurrent=await info(path.join(pluginRoot,'current.json')),
99
+ fallbackState=await info(path.join(fallbackRoot,'current.json'))||await info(path.join(fallbackRoot,'registration-pending.json'));
100
+ if((!hasPlugin||fallbackState)&&(pluginPending||pluginCurrent))fail('registration_unconfirmed_keep_existing');
101
+ if(!hasPlugin||fallbackState){
102
+ if(!hasMcp)fail('claude_capabilities_unconfirmed');
103
+ return installClaudeMcpFallback({sourceRoot,profile,env,configFile,signal,runClaude,checkRuntime,verifyInstalledRuntime,nodeCommand});
104
+ }
105
+ const payload=await inspectRuntimePackage(path.resolve(sourceRoot));
106
+ if(!payload.files.some(f=>f.path==='.claude-plugin/plugin.json')||!payload.files.some(f=>f.path==='.claude-mcp.json'))
107
+ fail('claude_package_incomplete');
108
+ const root=path.resolve(env.XDG_DATA_HOME??path.join(homedir(),'.local/share'),'promptframe-creation',profile,'claude-code');
109
+ await privateDirectory(root);const release=await acquire(root,signal);
110
+ const suffix=profile==='default'?'':'-'+profile,pluginName='promptframe-creation'+suffix,
111
+ marketplace='promptframe-creation-user'+suffix,pluginId=pluginName+'@'+marketplace,serverName='promptframe'+suffix;
112
+ const versions=path.join(root,'versions'),currentFile=path.join(root,'current.json'),pendingFile=path.join(root,'registration-pending.json'),
113
+ catalogFile=path.join(root,'.claude-plugin/marketplace.json'),versionRoot=path.join(versions,payload.version),
114
+ temporary=path.join(versions,'.partial-'+randomBytes(12).toString('hex'));
115
+ let registrationStarted=false,newFiles=0;
116
+ try{
117
+ signal?.throwIfAborted();await privateDirectory(versions);await privateDirectory(path.dirname(catalogFile));
118
+ await legacyUserMcp(env,serverName);
119
+ let previous=await privateRead(currentFile),pending=await privateRead(pendingFile),state=await registrations(runClaude,pluginName,marketplace,root);
120
+ const binding={profile,configFile,pluginId,pluginName,serverName,host:'claude-code'};
121
+ const checkBinding=record=>{if(record&&(record.profile!==profile||record.configFile!==configFile||record.pluginId!==pluginId
122
+ ||record.host!=='claude-code'||!/^\d+\.\d+\.\d+$/.test(record.version??'')
123
+ ||record.versionRoot!==path.join(versions,record.version)))fail('profile_binding_conflict');};
124
+ checkBinding(previous);checkBinding(pending);
125
+ const runtimeCommands=new Map();
126
+ 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;
128
+ const ready=await verifyVersion(record.versionRoot,{...record,pluginName,serverName});
129
+ runtimeCommands.set(record.versionRoot,ready.runtimeCommand);return true;
130
+ };
131
+ if(pending){
132
+ if(await observed(pending)){
133
+ await atomicJSON(currentFile,pending);await rm(pendingFile);previous=pending;pending=null;
134
+ }else if(pending.phase!=='marketplace'||!state.market||state.plugin)
135
+ fail('registration_unconfirmed_keep_existing',{phase:'registration_observation',localRegistrationState:'unknown',action:'inspect_same_registration_no_second_add'});
136
+ }
137
+ if(state.plugin&&!previous&&!pending)fail('claude_existing_registration_requires_review');
138
+ if(previous&&(!await observed(previous))&&!pending)fail('claude_local_registration_unconfirmed');
139
+ if(previous&&compareVersions(previous.version,payload.version)>0){
140
+ const recorded=runtimeCommands.get(previous.versionRoot);
141
+ await verifyInstalledRuntime(previous.versionRoot,previous.version,recorded,{env});
142
+ return{...previous,currentFile,reused:true,installedFiles:0,registered:true,pluginInstalled:true,versionStatus:'newer_retained',
143
+ requestedVersion:payload.version,recordedRuntimeRetained:recorded!==nodeCommand};
144
+ }
145
+ const complete={...binding,version:payload.version,versionRoot,payloadDigest:payload.payloadDigest};
146
+ if(pending&&(pending.version!==complete.version||pending.payloadDigest!==complete.payloadDigest))
147
+ fail('registration_unconfirmed_keep_existing');
148
+ if(await info(versionRoot)){
149
+ const ready=await verifyVersion(versionRoot,{...complete,pluginName,serverName});runtimeCommands.set(versionRoot,ready.runtimeCommand);
150
+ }
151
+ else{
152
+ await mkdir(temporary,{mode:0o700});
153
+ for(const file of payload.files){signal?.throwIfAborted();const dest=path.join(temporary,file.path);
154
+ await mkdir(path.dirname(dest),{recursive:true,mode:0o700});const fd=await open(dest,'wx',0o600);
155
+ try{await fd.writeFile(file.body);await fd.sync();}finally{await fd.close();}}
156
+ const manifest=JSON.parse(await readFile(path.join(temporary,'.claude-plugin/plugin.json'),'utf8'));manifest.name=pluginName;
157
+ await atomicJSON(path.join(temporary,'.claude-plugin/plugin.json'),manifest);
158
+ for(const file of['.mcp.json','.claude-mcp.json'])await atomicJSON(path.join(temporary,file),transport(serverName,configFile,nodeCommand));
159
+ await checkRuntime(temporary,payload.version);
160
+ const installed=await inspectRuntimePackage(temporary);
161
+ await atomicJSON(path.join(temporary,'installation.json'),{...binding,version:payload.version,payloadDigest:payload.payloadDigest,
162
+ files:installed.files.map(({path,bytes,sha256})=>({path,bytes,sha256}))});
163
+ signal?.throwIfAborted();await rename(temporary,versionRoot);newFiles=payload.files.length;
164
+ }
165
+ if(newFiles===0)await verifyInstalledRuntime(versionRoot,payload.version,runtimeCommands.get(versionRoot),{env});
166
+ const already=previous?.version===payload.version&&previous.payloadDigest===payload.payloadDigest&&await observed(complete);
167
+ if(!already){
168
+ await atomicJSON(catalogFile,{name:marketplace,owner:{name:'PromptFrame'},plugins:[{name:pluginName,source:'./versions/'+payload.version}]});
169
+ if(!state.market){
170
+ if(pending)fail('registration_unconfirmed_keep_existing');
171
+ await atomicJSON(pendingFile,{...complete,phase:'marketplace'});registrationStarted=true;
172
+ await runClaude(['plugin','marketplace','add',root,'--scope','user','--json']);
173
+ state=await registrations(runClaude,pluginName,marketplace,root);
174
+ if(!state.market)fail('claude_registration_unconfirmed');
175
+ }
176
+ await atomicJSON(pendingFile,{...complete,phase:'plugin'});registrationStarted=true;
177
+ await runClaude(['plugin','install',pluginId,'--scope','user','--json']);
178
+ state=await registrations(runClaude,pluginName,marketplace,root);
179
+ if(!await observed(complete))fail('claude_registration_unconfirmed');
180
+ await atomicJSON(currentFile,complete);await rm(pendingFile);
181
+ }
182
+ return{...complete,currentFile,reused:newFiles===0,installedFiles:newFiles,registered:true,pluginInstalled:true,
183
+ reloadRequired:!already,versionStatus:'current',requestedVersion:payload.version,
184
+ recordedRuntimeRetained:runtimeCommands.has(versionRoot)&&runtimeCommands.get(versionRoot)!==nodeCommand};
185
+ }catch(error){
186
+ if(registrationStarted)fail('registration_unconfirmed_keep_existing',{...claudeErrorDetails(error),
187
+ phase:'registration_observation',localRegistrationState:'unknown',action:'inspect_same_registration_no_second_add'});
188
+ if(error instanceof CreationClientError)throw error;
189
+ fail(signal?.aborted?'interrupted_keep_existing':'failed_keep_existing');
190
+ }finally{await rm(temporary,{recursive:true,force:true});await release();}
191
+ }
@@ -0,0 +1,17 @@
1
+ import {readFile,lstat} from 'node:fs/promises';
2
+ import {homedir} from 'node:os';
3
+ import path from 'node:path';
4
+ import {CreationClientError} from './credentials.mjs';
5
+
6
+ export function claudeConfigRoot(env=process.env){return path.resolve(env.CLAUDE_CONFIG_DIR??path.join(homedir(),'.claude'));}
7
+ export async function readClaudeUserServer(serverName,env=process.env){
8
+ const file=env.CLAUDE_CONFIG_DIR?path.join(claudeConfigRoot(env),'.claude.json'):path.join(homedir(),'.claude.json');
9
+ let info;try{info=await lstat(file);}catch(e){if(e.code==='ENOENT')return null;throw new CreationClientError('installation.claude_local_registration_unconfirmed');}
10
+ if(!info.isFile()||info.isSymbolicLink()||info.uid!==process.getuid?.()||info.size>4*1024*1024)
11
+ throw new CreationClientError('installation.claude_local_registration_unconfirmed');
12
+ let state;try{state=JSON.parse(await readFile(file,'utf8'));}catch{throw new CreationClientError('installation.claude_local_registration_unconfirmed');}
13
+ if(!state||typeof state!=='object'||Array.isArray(state))throw new CreationClientError('installation.claude_local_registration_unconfirmed');
14
+ if(state?.mcpServers!==undefined&&(!state.mcpServers||typeof state.mcpServers!=='object'||Array.isArray(state.mcpServers)))
15
+ throw new CreationClientError('installation.claude_local_registration_unconfirmed');
16
+ return state?.mcpServers?.[serverName]??null;
17
+ }