@promptframe/creation 0.2.7 → 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.
- package/.agents/plugins/marketplace.json +1 -1
- package/.claude-mcp.json +8 -0
- package/.claude-plugin/marketplace.json +5 -0
- package/.claude-plugin/plugin.json +60 -0
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +6 -4
- package/dist/THIRD_PARTY_NOTICES.txt +59 -0
- package/dist/cli.mjs +6222 -1557
- package/docs/development.md +20 -1
- package/docs/install-guidance.json +36 -0
- package/docs/installing.md +23 -3
- package/docs/releases/0.3.0.md +10 -0
- package/docs/releases/0.3.1.md +7 -0
- package/lib/bridge-negotiation.mjs +54 -0
- package/lib/claude-command.mjs +57 -0
- package/lib/claude-hook-definition.mjs +11 -0
- package/lib/claude-hook-registration.mjs +66 -0
- package/lib/claude-host-process.mjs +48 -0
- package/lib/claude-host-session.mjs +150 -0
- package/lib/claude-installation.mjs +195 -0
- package/lib/claude-local-state.mjs +17 -0
- package/lib/claude-mcp-installation.mjs +177 -0
- package/lib/cli.mjs +89 -15
- package/lib/connection.mjs +15 -4
- package/lib/content-budget.mjs +15 -0
- package/lib/host-context.mjs +178 -123
- package/lib/host-identity.mjs +34 -0
- package/lib/runtime-bootstrap.mjs +208 -0
- package/lib/runtime-launch.mjs +27 -0
- package/lib/runtime-package.mjs +41 -0
- package/lib/user-installation.mjs +6 -25
- package/lib/version.mjs +1 -1
- package/package.json +5 -2
- package/skills/creation-setup/SKILL.md +9 -3
- package/skills/video-creation/SKILL.md +16 -40
package/docs/development.md
CHANGED
|
@@ -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,21 @@
|
|
|
29
32
|
|
|
30
33
|
## 安装与运行路径
|
|
31
34
|
|
|
32
|
-
|
|
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、包身份及自包含运行文件后,再原子放入私有缓存。缓存按完整文件摘要复核,同版本不能更换完整性摘要,准备过程不运行安装脚本或注册宿主。新进程继承同一凭据路径和宿主种类,活动桥不被替换。宿主 hook 随插件安装,不由运行文件选择器更新。
|
|
40
|
+
|
|
41
|
+
获取或校验失败时,只有当前程序已经达到已知最低版本才可继续;显式锁定失败不会另选版本。平台缺少兼容声明时提示先更新平台。缓存位于安全凭据目录下的 `runtime-cache`,不会自动删除旧版本或清除不明准备锁。新运行进程启动后的错误不会触发第二次桥启动。
|
|
42
|
+
|
|
43
|
+
外部宿主可在初始化声明 `experimental.promptframe.contentTypes`,桥只转发已知种类,未声明时使用明确的文字降级。媒体能力来自宿主声明,不从模型或宿主名称推断;真实桌面是否展示图片、音频和资源仍需分别验证。源码、公开包及实际宿主加载分别核实。
|
|
44
|
+
|
|
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安装、桌面实际会话与模型收图分别验证。
|
|
33
50
|
|
|
34
51
|
源码经 GitHub Actions 打包发行到 npm;插件目录记录包名/版本或源码位置。安装后,Codex 加载本地副本并按配置启动 Node 桥;桥通过 stdio 接收调用,读取独立安全配置,再通过 HTTPS MCP 连接所选平台。GitHub、npm 与目录索引负责获取版本,不进入正常工具调用链。Token 不进入源码、插件包或命令参数。
|
|
35
52
|
|
|
@@ -52,3 +69,5 @@
|
|
|
52
69
|
安装发现使用 `$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
70
|
|
|
54
71
|
宿主插件已安装/启用、平台连接验证与聊天加载分别报告。外部安装器不接私有 app-server 生产刷新通道;当前使用官方新聊天/新 session 路径,选择 Local 和独立非 Git 目录即可。候选包、公共 registry 固定包和真实宿主新聊天工具/两个 Skill 的验收分开记录。
|
|
72
|
+
|
|
73
|
+
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.1",
|
|
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.1",
|
|
22
|
+
"requirements": "Node.js 20+ 与 Claude Code 2.1.295+;受控会话身份使用 Linux/WSL 原生 CLI 或桌面版的同机远程入口",
|
|
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
|
+
}
|
package/docs/installing.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# 安装、连接与升级
|
|
2
2
|
|
|
3
|
-
需要 Node.js 20
|
|
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.
|
|
9
|
+
npx --yes @promptframe/creation@0.3.1 connect --endpoint <Studio提供的API地址>
|
|
10
10
|
```
|
|
11
11
|
<!-- /creation-install-command -->
|
|
12
12
|
|
|
@@ -20,6 +20,24 @@ npx --yes @promptframe/creation@0.2.7 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.1 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.7 connect --endpoint <Studio提供的API地
|
|
|
28
46
|
|
|
29
47
|
<!-- creation-install-command -->
|
|
30
48
|
```bash
|
|
31
|
-
npx --yes @promptframe/creation@0.
|
|
49
|
+
npx --yes @promptframe/creation@0.3.1 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.7 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,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,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,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,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&¤t.uid===uid
|
|
40
|
+
&¤t.device===binding.device&¤t.inode===binding.inode&¤t.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'&¤t?.sessionId!==sessionId
|
|
113
|
+
||event==='SessionStart'&&input.source==='compact'&¤t?.sessionId!==sessionId
|
|
114
|
+
||event==='SessionStart'&&input.source==='startup'&¤t?.sessionId&¤t.sessionId!==sessionId;
|
|
115
|
+
const nextId=event==='SessionEnd'||inconsistent?null:sessionId;
|
|
116
|
+
const same=current&¤t.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
|
+
}
|