@tomflow/chatloop-tools 0.4.34 → 0.9.4

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.
Files changed (50) hide show
  1. package/README.md +120 -127
  2. package/bin/cli.mjs +48 -38
  3. package/bin/supervisor.mjs +4 -0
  4. package/index.mjs +269 -0
  5. package/lib/adapters/fixture.mjs +3 -2
  6. package/lib/adapters/index.mjs +14 -5
  7. package/lib/adapters/mcp-child.mjs +29 -7
  8. package/lib/adapters/tunnel.mjs +25 -7
  9. package/lib/api-aspect.mjs +190 -0
  10. package/lib/cli-command-router.mjs +34 -0
  11. package/lib/context-control-auth.mjs +12 -1
  12. package/lib/context-control-run.mjs +17 -79
  13. package/lib/context-gateway.mjs +108 -15
  14. package/lib/control.mjs +3 -2
  15. package/lib/extension-cli-contract.mjs +22 -0
  16. package/lib/extension-proxy.mjs +48 -19
  17. package/lib/gateway.mjs +46 -176
  18. package/lib/mcp-tool-router.mjs +60 -0
  19. package/lib/release-owner-preflight.mjs +41 -0
  20. package/lib/release.mjs +94 -49
  21. package/lib/{supervisor.mjs → supervisor-runtime.mjs} +143 -80
  22. package/lib/trace-gateway.mjs +25 -7
  23. package/lib/trace-observation.mjs +123 -0
  24. package/lib/tunnel.mjs +17 -29
  25. package/package.json +20 -14
  26. package/providers/context.mjs +20 -0
  27. package/providers/desktop.mjs +80 -0
  28. package/{lib/extension-contract.mjs → providers/extension.mjs} +36 -0
  29. package/providers/runtime.mjs +32 -0
  30. package/providers/trace.mjs +25 -0
  31. package/providers.generated.mjs +8 -0
  32. package/scripts/build-providers.mjs +69 -0
  33. package/lib/context-cli.mjs +0 -2
  34. package/lib/context-migration.mjs +0 -2
  35. package/lib/context-protocol.mjs +0 -2
  36. package/lib/task-registry-managed.mjs +0 -38
  37. package/lib/task-registry.mjs +0 -221
  38. package/node_modules/@tomflow/chatloop-context/README.md +0 -271
  39. package/node_modules/@tomflow/chatloop-context/bin/cli.mjs +0 -273
  40. package/node_modules/@tomflow/chatloop-context/lib/context-cli.mjs +0 -301
  41. package/node_modules/@tomflow/chatloop-context/lib/context-migration.mjs +0 -272
  42. package/node_modules/@tomflow/chatloop-context/lib/context-protocol.mjs +0 -1617
  43. package/node_modules/@tomflow/chatloop-context/lib/methods.mjs +0 -264
  44. package/node_modules/@tomflow/chatloop-context/lib/operations.mjs +0 -219
  45. package/node_modules/@tomflow/chatloop-context/lib/project-diagnostic.mjs +0 -455
  46. package/node_modules/@tomflow/chatloop-context/lib/workspace-operator.mjs +0 -159
  47. package/node_modules/@tomflow/chatloop-context/package.json +0 -21
  48. package/node_modules/@tomflow/chatloop-trace/README.md +0 -13
  49. package/node_modules/@tomflow/chatloop-trace/lib/trace.mjs +0 -259
  50. package/node_modules/@tomflow/chatloop-trace/package.json +0 -11
package/README.md CHANGED
@@ -1,140 +1,133 @@
1
1
  # @tomflow/chatloop-tools
2
2
 
3
- 独立本机 MCP Gateway + Supervisor + Tunnel。先查询 CLI Help,按需运行。
4
-
5
- ```sh
6
- npx --yes --package=@tomflow/chatloop-tools@latest chatloop-tools --help
7
- ```
3
+ Tools is the single private MCP Gateway and local Supervisor for Chat Loop.
4
+ The installed SDK and its CLI entrypoints are stable; tool capabilities are
5
+ independently assembled at **build time**, not detected from arbitrary runtime
6
+ files, registry URLs, or user-supplied executable paths.
7
+
8
+ ## Public entrypoints
9
+
10
+ - npm SDK: `index.mjs` exposes `loadToolsCli()` and `runToolsSupervisor()`.
11
+ - npm executable: `bin/cli.mjs`, command `chatloop-tools`.
12
+ - Private process entry: `bin/supervisor.mjs`; not another npm executable.
13
+ - MCP stdio: `chatloop-tools mcp`.
14
+
15
+ Run `chatloop-tools --help`, `chatloop-tools capabilities`, or
16
+ `chatloop-tools doctor` for the installed commands and local readiness.
17
+ Doctor does not verify ChatGPT authorization, Chrome Owner, or deployment.
18
+
19
+ `chatloop-tools api-usage 60` asks the **existing local Supervisor** for the last
20
+ 60 minutes of recorded MCP, Tools SDK/CLI, Extension/Native, Trace SDK and
21
+ platform Tunnel SDK API calls.
22
+ With an exact authorized Context Project grant it also aggregates that
23
+ Project's sanitized `context.api` events. Counts, success, failure,
24
+ incomplete calls and calls per minute are grouped by named entrypoint and
25
+ deduplicated by call/span ID; unmatched completions are reported separately.
26
+ Nested calls share a soft `traceId` and retain unique `spanId/parentSpanId`,
27
+ including a sanitized MCP-to-Context-CLI parent handoff.
28
+ It never starts a Supervisor, opens a browser, replays a call, or reads model
29
+ inputs. The Trace writer stores only safe API identity, call ID, phase, time
30
+ and bounded duration/error code; Context logs remain Project-scoped.
31
+ Browser dispatch is only listener acceptance, not an authenticated user
32
+ click or successful ChatGPT action. These rates are **API invocation rates**,
33
+ not UI click-through rates. This is best-effort telemetry, not proof that
34
+ every standalone package invocation reached the Supervisor; without a
35
+ verified running Supervisor it returns BLOCKED, not invented data.
36
+ `npm run check` verifies generated six-package AOP copies and all published
37
+ callable SDK facades (the gate reports its live count), while Context's 34
38
+ declared methods and MCP Provider
39
+ catalog have separate capability tests. Internal Trace Writer health/record
40
+ operations are excluded from re-submitting themselves to prevent recursive logs.
41
+ Non-authoritative process/control logs use a bounded async queue, with drops
42
+ and pending counts visible in Supervisor Trace health.
8
43
 
9
44
  ```text
10
45
  Usage: chatloop-tools <command> [target]
11
- Commands: doctor, mcp, start, stop, restart, status, upgrade, tunnel, capabilities, context
46
+ Commands: doctor, mcp, start, stop, restart, status, upgrade, tunnel, capabilities, api-usage
12
47
  Run: chatloop-tools <command> --help
13
48
  ```
14
49
 
15
- ```sh
16
- npx --yes --package=@tomflow/chatloop-tools@latest chatloop-tools start --help
17
- ```
18
-
19
50
  ```text
20
51
  Usage: chatloop-tools start [desktop-commander|tunnel]
21
52
  Start all enabled tools or one.
22
53
  ```
23
54
 
24
- **同 Chat 新接口(候选)**:`chat_loop_extension__start({projectId,mode:'adopt',confirmed:true})`(无 prompt)只尝试接管原 Chat,并由扩展自己检查 R/P 真实用户回合与版本。`mode:'adopt'` 与 `prompt` 互斥;从原 Chat 提出执行请求不能降级为新 Chat。
25
-
26
- MCP `chat_loop_extension__start` 入参为 `{projectId, prompt, confirmed:true}`,可选 `replaceBlockedSessionId` 仅用于在双重核验旧 Session `BLOCKED` 且新 projectId 不同的情况下显式开启**新任务**;不提供 `force`,不重发旧任务。`status` 保持只读,未知回执不自动重试。
27
-
28
- Extension Actions 委托 `@tomflow/chatloop-extension` 公共 CLI,不复制浏览器操作。具体安全边界和协议见 [Local Tools 产品文档](../../docs/local-tools.md),实际部署与已验证状态见 [CURRENT](../../docs/CONTEXT.md)。
29
-
30
-
31
- 正式运行环境的版本切换命令:
32
-
33
- ```sh
34
- npx --yes --package=@tomflow/chatloop-tools@latest chatloop-tools upgrade
35
- ```
36
-
37
- 升级先独立安装新版本、核实 Supervisor 所有权与运行状态,再通过原 Supervisor 停止旧版、将 Tunnel MCP 启动命令固定到新版本并启动;不在 Tunnel 正处理 MCP 调用时直接自我重启。若返回 `BLOCKED`,先核对原任务回执,不要盲重试。`start` 全量入口在正常用户安装环境检测到版本差异时复用此流程;带隔离状态目录的测试不触发升级。详情见 [Local Tools 主文档](../../docs/local-tools.md)。
38
-
39
- **0.4.20 离线候选升级(尚未切换生产)**:源码版或已经安装的新 CLI 支持 `upgrade prepare <absolute-single-tools.tgz> <sha256>`,在同 UID 私有 Release 根离线验证单包的固定 SDK 版本、Context/Trace、真实 Tunnel 二进制、doctor 与关键文件哈希,**只生成不可变阶段安装,不停止旧 Supervisor、不修改 MCP Profile/runtime.json/Context**;返回 `STAGED_ONLY` 才表示预备完毕。后续独立的 `upgrade activate` 仅接受含阶段证据、且在启动前重新哈希核对的版本,先核实旧 Owner 状态再按已有停启流程处理;Owner/浏览器副作用不可信时不得调用。`upgrade` 无子命令是原有 npm Registry 兼容切换路径,不能把它等同于离线准备。当前公开 Tools 0.4.19 **并不支持新子命令**,需要使用本机已验证的新版 CLI。**运行根门禁**:升级准备/激活要求默认 HOME 与操作系统实际用户 HOME 一致、且显式 State Dir(如有)指向同一用户运行目录;Desktop Commander 隔离 HOME 下直接调用会返回 `RUNTIME_HOME_MISMATCH`,以免向沙箱错装版本或误把生产旧 Supervisor 判作已停。已有 Release 父目录允许同 UID、他人不可写的 755,**新建的临时阶段目录仍为 700**,不会为部署擅改旧运行目录权限。开发测试使用 API 显式指定独立 `base`,生产操作必须现场核实实际用户根、Owner 与浏览器受控任务,不得通过伪造身份绕过。
40
-
41
- **M10 Tools 0.4.21 新候选(尚未发布/生产激活)**:上一轮真实用户根中已暂存的 0.4.20 归档 SHA-256 为 `a2dbf4da...`,与 M10 最新单包归档 `6f9447d3...` 不相同,实际多出三项文件内容差异(README、Gateway、Trace Gateway);**不可激活旧 0.4.20 暂存版冒充新交付物**。新 CLI 改为 `upgrade activate <expected-artifact-sha256>`,在旧 Supervisor 停机前校验不可变准备回执与调用者指定包哈希,缺参/不一致一律 BLOCKED。0.4.21 离线单包已完成隔离 `STAGED_ONLY` 验证,但正式 HOME 下未准备、发布或激活。完整源码与回归证据见 [M10 模块计划](../../docs/research/chat-loop-module-api-alignment-plan-20261110.md)。
42
-
43
- **0.4.22 GUI Terminal 禁用与纯 MCP 执行**:执行命令只走已授权 Chat Loop MCP `desktop_commander__start_process` / `read_process_output`,或用户明确授权的 Local Dev MCP 备用通道;**禁止**通过 `open -n -a Terminal`、`osascript`、iTerm 或 .app 二进制启动图形终端窗口。Gateway 对直接启动 Terminal/iTerm 的 `start_process` 和 `interact_with_process` 返回 `GUI_TERMINAL_LAUNCH_PROHIBITED`,普通 shell/CLI 命令、文件与目录访问不受此规则限制。本机正式用户 HOME 的 CLI 验收可以直接经 Local Dev MCP 完成,不需要打开任何 Terminal 窗口。此检查仅能拦截明确命令形式;Tooling Skill 同时约束调用者,不声称能拦截任意嵌套脚本。
44
-
45
- **0.4.23 正式 Mac 用户环境(本轮目标)**:Chat Loop 自己的 MCP Gateway 仍路由同一 pinned Desktop Commander 子进程;Supervisor 不再给它创建 `~/.chat-loop/local-tools/tools/desktop-commander/home` 假 HOME,改从 OS 实际登录账号 `userInfo()` 取得用户 HOME/USER/LOGNAME,保留原有 PATH 和本机服务环境。意味着 MCP 文件、shell、npm、配置与用户的 Mac 账号目录一致,不必使用 Local Dev 或桌面 Terminal 中转。独立 Local Dev MCP 仅用于本轮迁移/研发;新 Gateway 仍拒绝图形 Terminal/iTerm 启动。新增真实 Gateway→Desktop Commander→`node os.homedir()` 的本机回读测试。**该包需单独正式发布和真实生产激活;源码回归通过不等于云端已切换。**
46
-
47
- **0.4.24 防止文字误拦截**:`0.4.23` 在 Mac 本机执行已通过,但 Gateway 的图形终端拦截会把文档或 heredoc 内提及的命令当成真实执行,造成误拒。本版只检查实际 shell 命令位置,跳过 heredoc 正文;真实启动图形 Terminal/iTerm 的命令仍被阻止,普通代码、文档、目录和服务命令不受影响。独立回归覆盖实际启动和字符串/文档反例。**本机 MCP 权限/资源模型与 0.4.23 相同**。
48
-
49
- **0.4.25 Trace 真实会话关联修复**:Tunnel 显式继承唯一 Tools Supervisor 的 Context/Trace opt-in Gateway 配置(不继承其它账号密钥),避免线上 Gateway 无法暴露 `chat_loop_trace_diagnose`。Trace Gateway 兼容 Chrome Status 的真实嵌套 `session.sessionId` 回执,对 BLOCKED Status 记录故障码和助手消息身份引用(不写原文、不冒充 Native 发送确认)。专项真实 Supervisor/Gateway 桥接测试覆盖同一 Session 的日志、诊断和不泄漏消息正文。生产必须分别验证 Runtime 环境、Tunnel MCP tools/list、Trace writerHealth 和 Chrome DOM/文字回执。旧日志仍保留,缺失的历史事件不能补造成已确认事件。
50
-
51
- **0.4.26 Trace 精确 Start 阻断原因**:真实 Extension Status 同时给出泛化 Owner 原因与更精确的 `lastStartFailureCode` 时,Trace 只在 `BLOCKED + action=START` 的情况下优先记录经过严格格式验证的故障码;无精确故障码仍使用原理由,不提权、不补发,不将 DOM 中的用户消息当作 Native 成功回执。真实 Gateway→Supervisor→唯一 Trace Writer 集成测试覆盖 `FIRST_SEND_RECEIPT_UNKNOWN`。
52
-
53
- **Start 长页面准备(0.4.17)**:私人 MCP `chat_loop_extension__start` 的 CLI 子调用等待窗口最多 330 秒,仅用于允许 Chrome 安全校验和 ChatGPT 编辑器自然就绪。超时仍返回不确定错误,不重新启动或重发,必须单独查询 Status。
54
-
55
-
56
- **0.4.18 原有接口结构(历史候选)**:九个 Extension MCP 接口的名字、参数 Schema、CLI 映射和本机参数准入统一维护于 lib/extension-contract.mjs(纯契约、无进程副作用);extension-proxy.mjs 仅负责 npx 转发、超时和回执验证,Gateway 单独暴露一个安全限定 UUID 的 operation_status 查询。发布工具总数为 36:26 DC + 9 Extension + 1 Runtime 回执。发行/运行版本与源码候选需分开核验。
57
-
58
- **源码候选 0.4.20(未发布)**:在不增加公开 Extension 工具数量的前提下,原 `chat_loop_extension__start` 增加只允许 `mode:adopt`、不含 prompt 的同 Chat 原地接管方式;可选 `chatUrl` 精确限制候选。真实 Chrome 正向链路、用户交互原生表单和 npm 正式发布仍须单独验收。
59
-
60
- **M04 Gateway API 商减(本地候选,未发布)**:保持同一 Desktop Commander 子进程与静态 26 项上游 Schema,只在唯一 `lib/gateway.mjs` 的对外工具列表/调用路由中隐藏 5 项非研发 API(`set_config_value`、`get_usage_stats`、`get_recent_tool_calls`、`give_feedback_to_desktop_commander`、`get_prompts`),公开 21 项文件、搜索、进程等工具;隐藏工具的 `tools/call` 必须返回 `UNKNOWN_TOOL`,不能只藏名字。高噪声说明缩为准确描述,输入 Schema 与原能力保持不变。默认配置(无可选 Context/Trace/研究探针)下 Gateway 共有 **32 项**:21 Desktop + 9 Extension + 1 Runtime 回执 + 1 旧 Registry 兼容。获授权的 Context 增加两项统一 get/mutate;Trace 可独立 opt-in 增加一项只读诊断,不启动附加服务。以上仅是源码候选,发布前和真实连接后均需分别回读 `tools/list`。
61
-
62
- ## 轻量任务索引(S1 源码候选,尚未发布)
63
-
64
- 现有 **Local Tools Gateway 内增加且仅增加一个** `chat_loop_task_registry` MCP 工具,无第四个服务、HTTP Socket、额外进程或 Node 24 要求;存储位于现有私有 State Dir 的 `task-registry.v1.json`,写入采用互斥锁和原子替换,不复制业务需求、审批、状态和原始文档。
65
-
66
- 工具请求始终携带 `action` 与 `projectId`,操作示例:
67
-
68
- | action | 必需参数 | 效果 |
69
- | --- | --- | --- |
70
- | `register` | `taskId,title,taskDocPath,projectRoot` | 首次登记明确 Task 与原始任务文件;文件必须存在且包含唯一匹配的 `taskId: ...`,可选 `parentTaskId/contextRoot` |
71
- | `list` | 无其它参数 | 只列指定项目任务 |
72
- | `get` | `taskId` | 返回任务、权威任务文件和引用文件(含 PRESENT/MISSING/UNVERIFIED 文件状态) |
73
- | `link` | `taskId,sourcePath` | 登记已存在的授权文件引用,可选 `role/versionRef`;重复登记幂等 |
74
- | `unlink` | `taskId,sourcePath,expectedRevision` | 明确解除错误引用,不删除原文件;`sourcePath` 必须从 get 返回的规范化引用读取 |
75
- | `update` | `taskId,expectedRevision` 及 `title` 或 `taskDocPath` | 纠正任务标题/权威文件入口,保留 taskId 和同项目归属,不重写原文件 |
76
-
77
- 首次登记的 `projectRoot` 和可选 `contextRoot` 必须来自 Project Skill 对用户授权工作区的实际确认;后续只允许在这一明确范围内引用原文件,不从项目名或最近的 Chat 猜测位置。注册后变更项目根必须走明确的新项目绑定流程,不允许用同名覆盖。用户授权的来源判断仍是 Project/Tooling 的职责,**调用方传入根路径不等于系统已经证明其获得用户授权**。
78
-
79
- Registry 只索引长期需要跟踪的工作;普通 Chat 和一次性操作不必创建 Task。Agent + Skills 决定任务推进及业务审批;Chrome Extension / Native 继续独占受控发送与 Session。Registry 不写 `status/stage/approved`,且创建成功绝不等于 R/P 已获批准。
80
-
81
- 测试:仓库内 `node --test packages/local-tools/test/task-registry.test.mjs`(Node 20 支持),以及 `npm test`。该源码尚未通过发行版、云端私人 MCP 及真实 Chrome 接班的发布验收。
82
-
83
-
84
- ## 统一 Context Manager(V8 源码候选 / 生产未激活)
85
-
86
- 启用后仅在私人 MCP Gateway 增加两个可调用工具:`chat_loop_context_get`(只读)和 `chat_loop_context_mutate`(读写)。未配置 `CHAT_LOOP_CONTEXT_API_ENABLE=1`、绝对路径 `CHAT_LOOP_CONTEXT_DB`、可信预绑定项目集 `CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS` 时均不暴露。模型传入的 `principal/role` 不提供权限;同一私人 MCP、同 UID shell 不是跨 Chat 硬身份隔离。首次创建数据库只能由**本机管理员**显式 `context init`,不能因请求缺库而自动创建。
87
-
88
- | 通道 | 操作(代表性) | 约束 |
89
- | --- | --- | --- |
90
- | Get | `project.list/get/authority`、`project.material.list/get`、`task.list/get`、`document.get/list`、`evidence.list`、`context.history/resume`、`context.request.status` | 服务端读取授权;不返回原始写凭据 |
91
- | Mutate | `project.create/patch/archive`、`project.material.put`、`task.create/patch/reopen/complete/accept/archive`、`task.reviewProjectRules`、`document.createDraft/prepareIssue`、`presentation.resolve`、`approval.observe/revoke`、`evidence.attach/detach`、`context.patch/checkpoint`、`start.reserve` | 严格 operation Schema、expectedStoreEpoch、相应 revision、writeRequestId;活动任务还必须使用正式 Start/Handoff 提供的 runRef + 私有 runCredential + bindingRevision |
92
- | 内部控制 | `permit.consume`、`run.bind.initial/handoff`、`run.fence`、`run.fence.terminal`、`run.restore-same-owner` | **绝不暴露为普通 MCP mutate**;只从 Worker 正式 Action → Native Host → Local Tools 私有受限 IPC 调用 |
93
-
94
- `context.request.status` 只查询本服务原 writeRequestId 的持久回执;不明外部工具操作的结果仍须找原工具核实,不能重放。内部 `START permit.consume` 消费的是**精确 leaseRef**,其业务/审批版本在 `run.bind.initial` 提交时再次校验;已经发送但版本漂移时拒绝激活,不能补发。Handoff/NOT_SENT 恢复也必须与冻结的 Checkpoint 业务/审批版本完全一致,刷新最新 revision 不授写权;旧 v5 候选遗留、缺少原 lease 关联的在途 START 不自动恢复,需只读核实。当前 SQLite 候选使用 Node 24+ 的 `node:sqlite`;工具包其余旧接口仍兼容 Node 20,Node 20 上不启用此候选。此处是源码接口及本地候选测试,**不代表云端 Plugin、真实 Chrome、生产迁移已通过或发布**。
95
-
96
- 仅本机命令,非 MCP 工具:
97
-
98
- `Usage: chatloop-tools context <init|doctor|scan|backup|restore-branch|project-create|shadow|status|classify|import-sources|prepare|activate> [args]`
99
-
100
- `Requires explicit CHAT_LOOP_CONTEXT_DB and CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS. Classify/import-sources/prepare/activate require interactive operator consent; never execute as an MCP tool.`
101
-
102
-
103
- **V6 Project Material**:版本化的项目专属指令、历史全文与旧证据统一入库,`project.material.list` 只出元数据,`project.material.get` 必须带精确版本才返正文;同 ID+版本不可修改,原物理 Markdown 的整份正文及 SHA-256 经 `context import-sources <projectId> <privateReviewJsonPath>` 真实本地操作员核验后仅登记为 `LEGACY_UNVERIFIED`。不因此导入 R/P 批准、Chrome Owner 或伪 Checkpoint。旧 `schemaVersion=5` Store 不自动升为 v6,必须另有可回滚迁移。
104
-
105
- 混合 `CURRENT.md` 必须先通过本机 `context classify <projectId> <shadowManifestPath> <privateReviewJsonPath>` 人工归属审核,再进入 `prepare`。Review JSON 必须含核实过的 `projectId/sourceUnitId/sourceHash/currentFactsComplete/reviewRef/projectSharedContext/taskContexts/unknownHistoryRefs`,其中 `unknownHistoryRefs` **必须至少包含整个原文件的精确绝对路径与源 SHA-256**,即使已分类当前事实也保留历史 EvidenceOnly。只接受当前操作员可访问的 0600 私有 Review 文件、原物理 SourceUnit 不变与精确 revision;没有可信归属、review 或真实操作员输入时继续 SHADOW_RO,不得自动认领。已存在的旧格式 SQLite 数据库不会自动升级或覆盖:先核对 schema/epoch/mode,升级方案及备份未核实之前明确拒绝。
106
-
107
- 迁移按 SourceUnit 只读扫描/哈希对账 → SHADOW_RO → CUTOVER_FENCED → MANAGED_RW;旧 Registry 写入口只有**源单元已证明切换**后才拒写,新客户端不得双写,旧缓存进程不受新 adapter 自动约束。`context restore-branch` 只生成**新 epoch 的诊断只读分支**,不自动恢复 Browser Owner、用户审批或私有写凭据;恢复包、未知副作用与原文件保留。`/g` ChatGPT Project 路由当前仍必须单独验证,不允许绕过 Handoff guard。
108
-
109
- **迁移写权门禁(源码候选)**:`project.authority(projectId)` 是只读可回查入口,区分 SQLite `ACTIVE` 与物理 SourceUnit `MANAGED_RW`。已导入 `LEGACY_UNVERIFIED` 的正文若没有对应已激活且来源路径+哈希均相符的 SourceUnit,返回 `MIGRATION_NOT_MANAGED/writable=false`;普通 MCP 写和 Native 运行绑定拒绝 `PROJECT_CUTOVER_NOT_VERIFIED`,保留只读检查。新 Project 没有遗留来源且 Store ACTIVE 时返回 `NEW_PROJECT`。实际切换仍需本地操作员 TTY 与旧写者收口,不能靠 `project.patch` 伪造。
110
-
111
- ## Context SDK CLI (候选,未发布)
112
-
113
- 独立 Context npm 包源码在 ../context,候选包名 @tomflow/chatloop-context@0.1.0。真实 ChatGPT Agent 通过已连接的两个 MCP 工具 chat_loop_context_get / chat_loop_context_mutate 访问 SDK,而不是直接操作本机 Node/SQLite。调用前先用 sdk.methods.list 获取方法摘要,再按需要用 sdk.methods.describe 获取精确参数合同;SDK、CLI 和 MCP Schema 共用一个 Method Catalog。
114
-
115
- Tools 的普通 MCP 实现直接调用**自身固定依赖**的独立 Context SDK CLI(`require.resolve('@tomflow/chatloop-context/cli')`,受信 Node24 子进程,非 `npx`),省去每个请求额外一次 npm 离线解析与缓存查找;版本从已安装 SDK Method Catalog 与 CLI 回执核对,不能由模型指定包版本、执行路径或参数。内部 Native run.bind/fence/permit 依旧限制在已有签名控制通道。**独立 Project 库候选**:设置 `CHAT_LOOP_CONTEXT_API_ENABLE=1`、`CHAT_LOOP_CONTEXT_ROOT=<privateContextRoot>`、`CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS=<grantedId>`(不设置 `CHAT_LOOP_CONTEXT_DB`);普通 Gateway 和 Native 签名 IPC 共用 SDK 的 Project 身份校验与同一份 `<projectId>/context.sqlite`。旧共享 Store 仅在单独配置 `CHAT_LOOP_CONTEXT_DB` 时作为迁移兼容入口;两种根路径同时配置会拒绝提供 Context MCP、Native 写入与 SDK 数据访问,以防双写。Native 内部权限仍需要实际 Extension/Owner 身份、Session 及运行凭证通过,根路径并不授权执行。已完成隔离 Gateway/Native Handoff 回归,**不是生产旧版 Tools 或真实 Chrome 已升级**。当前发布版的真实 tools/list 尚未升级,因此这只是代码候选;完成 npm 打包、发布、连接回读和旧写者收口之前,禁止生产数据切换,也不得把本地测试视为真实 Chrome E2E。
116
-
117
-
118
- ## 单一 Tools tarball 发行候选(尚未发布)
119
-
120
- `@tomflow/chatloop-tools` 是用户连接 ChatGPT 的唯一 Tools 安装入口。
121
- 其 SDK 依赖仍各自独立维护,Tools 仅在构建发布包时将精确固定版本的
122
- `@tomflow/chatloop-context` 和 `@tomflow/chatloop-trace` 作为 npm
123
- `bundleDependencies` 放入一份 Tools tarball,避免要求用户先安装或
124
- 发布另外两个 SDK。这不是新增服务,也不改变 SDK 方法/版本合同。
125
-
126
- 在仓库根使用 `npm run pack:tools -- /absolute/existing/output-directory`
127
- 进行**离线、本地、无发布副作用**的打包。构建脚本先比对 Tools
128
- dependencies 与两个 SDK 实际 package version,只复制三个包各自的
129
- 发行白名单文件,不追随 workspace symlink;在独立临时目录执行
130
- `npm pack --offline --ignore-scripts` 并核对真正 bundled 文件,
131
- 然后以禁止覆盖的方式产出 tarball 与 SHA-256 回执。
132
- **不要直接从 workspace `npm pack packages/local-tools` 作为正式
133
- 捆绑发行包**:该位置的 SDK `node_modules` 是开发用 symlink,
134
- 常规 pack 无法证明 SDK 实际随包交付。
135
-
136
- 已经在干净目录中**只安装这一份 Tools tarball**(本机离线),
137
- 验证其 bundled Context/Trace 均可加载,且 Gateway 不经 npx 完成
138
- 独立 Project SQLite 的 get → mutate → readback。正式 npm publish、
139
- 升级 Supervisor/Tunnel、可信操作员 SourceUnit 审核及 Chrome Owner E2E
140
- 仍是后续独立门禁,**不得用打包通过代替生产已部署**。
55
+ ## Capability composition
56
+
57
+ `providers/<id>.mjs` owns each MCP Provider's tool names, schemas,
58
+ activation condition, scoped call adapter and optional CLI commands.
59
+
60
+ The five built-in Providers are:
61
+
62
+ - `desktop`: allowlisted Desktop Commander tools and isolated fixtures
63
+ - `extension`: official pinned Extension CLI and nine scoped actions
64
+ - `runtime`: exact-request receipt lookup without replay
65
+ - `context`: independent Context SDK read/write schemas and fixed CLI
66
+ - `trace`: Project-scoped diagnosis and SOFT stage observations
67
+
68
+ `npm run build:providers` generates `providers.generated.mjs`, the static
69
+ assembly and release fingerprint manifest. Both `tools/list` and `tools/call`
70
+ use a single `lib/mcp-tool-router.mjs` instance. `lib/gateway.mjs` handles
71
+ MCP framing only; it knows no individual Provider. There is no parallel
72
+ hand-maintained API inventory or runtime plugin directory scan.
73
+
74
+ `lib/cli-command-router.mjs` also recognizes additional CLI commands owned
75
+ by Providers, without another central command branch.
76
+
77
+ ### Add a tool or CLI command
78
+
79
+ 1. Create `providers/<id>.mjs` with a `provider` export: unique `id` and
80
+ `names`, plus `create(services)` returning `tools()` and `call(name,args)`.
81
+ An optional `commands` list can declare `name`, `help` and
82
+ `run({args,api})` returning `{exitCode,result}`.
83
+ A CLI-only Provider may set `names:[]` and omit `create()` entirely;
84
+ it does not need a fake MCP tool or adapter.
85
+ 2. Build: `npm run build:providers`.
86
+ 3. Verify: `npm run build:providers:check`, `npm test` and workspace
87
+ `npm run check`.
88
+
89
+ The compiler rejects duplicate tool and command identities, missing
90
+ implementations, and attempts to shadow built-in CLI names. At runtime
91
+ unregistered, undeclared and disabled tools fail closed as `UNKNOWN_TOOL`.
92
+ `test/provider-composition.test.mjs` demonstrates adding and removing a
93
+ sixth isolated Provider with an MCP tool and CLI command, with no edits
94
+ to any existing Provider, the Gateway, or either npm entrypoint.
95
+
96
+ ## Authority and lifecycle
97
+
98
+ - Desktop Commander publishes only the reviewed 21 tools, regardless of
99
+ upstream vendor additions. GUI Terminal launches remain prohibited.
100
+ - Context enforces Project authorization, CAS, Store epochs, and durable
101
+ request receipts. Tools does not own a second task database.
102
+ - Extension alone controls browser Owner and actual ChatGPT Action sends.
103
+ - Supervisor alone owns child-process lifecycle, serialization, unknown
104
+ side-effect receipts and the single Trace writer.
105
+ - Trace observations and logging never authorize business writes or
106
+ trigger retries of unknown effects. In particular, verified Extension MCP
107
+ results are returned **before** optional Trace transport finishes; a
108
+ slow, rejecting or unavailable observer cannot replace the action receipt.
109
+ These events are best-effort evidence, not an all-API AOP coverage claim.
110
+
111
+ No legacy Task Registry MCP or JSON fallback is shipped. Historical
112
+ SourceUnit files remain migration evidence, not alternate current facts.
113
+
114
+ ## Local validation and packaging
115
+
116
+ - `npm test` runs isolated package and Gateway regression tests.
117
+ - Workspace `npm run check` verifies API boundaries, source syntax,
118
+ documentation links, and both Context/Tools generated compositions.
119
+ - Workspace `npm run pack:tools -- <existing-output-directory>` produces
120
+ an offline, version-pinned Tools tarball containing the declared Context
121
+ and Trace SDKs **plus their verified runtime dependency closure**
122
+ (`ps-list` and `@tomflow/chatloop-extension` for the current Context SDK).
123
+ Release tests must cold-install the tarball and actually load Context's
124
+ Local Operator; checking filenames or importing only the SDK root is insufficient. The build checks the provider manifest before packaging.
125
+ Release staging uses the **candidate package's own** generated Provider manifest
126
+ and fingerprints every Tools-owned source file, including new Provider helpers;
127
+ missing, substituted, or added files block activation before Owner handoff.
128
+ - `chatloop-tools upgrade prepare <absolute-tarball.tgz> <sha256>` and
129
+ `chatloop-tools upgrade activate <sha256>` are separate authorized steps.
130
+
131
+ Source tests and a release tarball do **not** prove npm publication, an
132
+ installed Supervisor upgrade, private MCP activation or real Chrome E2E.
133
+ Check the installed version and authoritative runtime evidence separately.
package/bin/cli.mjs CHANGED
@@ -5,35 +5,39 @@ import {randomUUID} from 'node:crypto';
5
5
  import {createRequire} from 'node:module';
6
6
  import {dirname,join} from 'node:path';
7
7
  import {fileURLToPath} from 'node:url';
8
- import {lifecycleDeadlineMs,CONTRACT,ACTIONS,registry,ensurePrivateDir,paths,
9
- safeFallback,recoverStaleLock,exitCode,talk} from '../lib/control.mjs';
10
- import {runGateway} from '../lib/gateway.mjs';
11
- import {tunnelDoctor,runTunnel} from '../lib/tunnel.mjs';
12
- import {promptTunnelRuntimeKey,storeTunnelRuntimeKey} from '../lib/tunnel-auth.mjs';
13
- import {upgradeRuntime,runtimeNeedsUpgrade,prepareReleaseCandidate} from '../lib/release.mjs';
8
+ import {loadToolsCli} from '../index.mjs';
14
9
 
10
+ const cliApi=await loadToolsCli();
11
+ const cliExtensions=cliApi.cliExtensions;
15
12
  const HELP={
16
- '': 'Usage: chatloop-tools <command> [target]\nCommands: doctor, mcp, start, stop, restart, status, upgrade, tunnel, capabilities, context\nRun: chatloop-tools <command> --help',
13
+ '': 'Usage: chatloop-tools <command> [target]\nCommands: doctor, mcp, start, stop, restart, status, upgrade, tunnel, capabilities, api-usage\nRun: chatloop-tools <command> --help',
17
14
  doctor:'Usage: chatloop-tools doctor\nInspect local readiness without changing services.',
18
15
  mcp:'Usage: chatloop-tools mcp\nServe namespaced MCP tools over stdio.',
19
16
  start:'Usage: chatloop-tools start [desktop-commander|tunnel]\nStart all enabled tools or one.',
20
17
  stop:'Usage: chatloop-tools stop [desktop-commander|tunnel]\nStop all enabled tools or one.',
21
18
  restart:'Usage: chatloop-tools restart [desktop-commander|tunnel]\nRestart all or one.',
22
19
  status:'Usage: chatloop-tools status [desktop-commander|tunnel]\nRead runtime state.',
23
- upgrade:'Usage: chatloop-tools upgrade prepare <absolute-tarball.tgz> <sha256> | upgrade activate <sha256>\nPrepare is offline and never stops the old service. Activate checks the expected artifact SHA-256 before stopping any service; bare upgrade retains legacy registry behavior.',
24
- tunnel:'Usage: chatloop-tools tunnel <doctor|auth|--version|run>\nTunnel runs under Supervisor; auth requires explicit setup.',
20
+ upgrade:'Usage: chatloop-tools upgrade prepare <absolute-tarball.tgz> <sha256> | upgrade activate <sha256>\nPrepare is offline and never stops the old service. Activate checks the expected artifact SHA-256 before stopping any service. No unpinned upgrade.',
21
+ tunnel:'Usage: chatloop-tools tunnel <doctor|auth|--version>\nTunnel runs under Supervisor; auth requires explicit setup.',
25
22
  capabilities:'Usage: chatloop-tools capabilities\nList supported tool categories.',
26
- context:'Usage: chatloop-tools context <init|doctor|scan|backup|restore-branch|project-create|shadow|status|classify|import-sources|prepare|activate> [args]\nRequires explicit CHAT_LOOP_CONTEXT_DB and CHAT_LOOP_CONTEXT_ALLOWED_PROJECTS. Classify/import-sources/prepare/activate require interactive operator consent; never execute as an MCP tool.'
23
+ 'api-usage':'Usage: chatloop-tools api-usage [window-minutes]\nRead local Supervisor aggregated API calls and rates; never replays calls.'
27
24
  };
28
25
  const helpArgs=process.argv.slice(2);
29
26
  const helpSection=helpArgs.length===1&&['-h','--help','help'].includes(helpArgs[0])?''
30
27
  : helpArgs.at(-1)==='--help'||helpArgs.at(-1)==='-h'
31
28
  ? helpArgs.slice(0,-1).join(' '):null;
32
29
  if(helpSection!==null){
33
- process.stdout.write((HELP[helpSection]||'Unknown help topic. Run: chatloop-tools --help')+'\n');
34
- process.exit(helpSection in HELP?0:2);
35
- }
30
+ await cliApi.observeCliCommand('help',async()=>{
31
+ const help=HELP[helpSection]||cliExtensions.help(helpSection);
32
+ process.stdout.write((help||'Unknown help topic. Run: chatloop-tools --help')+'\n');
33
+ process.exitCode=help?0:2;
34
+ });
35
+ }else{
36
36
 
37
+ const {lifecycleDeadlineMs,CONTRACT,ACTIONS,registry,ensurePrivateDir,
38
+ safeFallback,recoverStaleLock,exitCode,talk,runGateway,apiUsage,tunnelDoctor,runTunnel,
39
+ promptTunnelRuntimeKey,storeTunnelRuntimeKey,upgradeRuntime,runtimeNeedsUpgrade,
40
+ prepareReleaseCandidate}=cliApi;
37
41
  const require=createRequire(import.meta.url);
38
42
  const command=process.argv[2]??'doctor';
39
43
  const extra=process.argv.slice(3);
@@ -69,7 +73,7 @@ async function connectOrLaunch(request){
69
73
  }
70
74
  throw Object.assign(new Error('Owner alive, IPC unavailable'),{code:'MANAGER_UNAVAILABLE'});
71
75
  }
72
- const entry=fileURLToPath(new URL('../lib/supervisor.mjs',import.meta.url));
76
+ const entry=fileURLToPath(new URL('./supervisor.mjs',import.meta.url));
73
77
  const manager=spawn(process.execPath,[entry],{detached:true,stdio:'ignore',env:process.env});
74
78
  manager.unref();
75
79
  let last;
@@ -116,21 +120,8 @@ async function runControl(action=command, params=extra){
116
120
  }
117
121
  emit(reply);process.exitCode=exitCode(reply);
118
122
  }
119
- if(command==='context'){
120
- if(Number(process.versions.node.split('.')[0])<24){
121
- // Do not even import node:sqlite on the published legacy Node 20 path.
122
- emit({contract:'chat-loop.context-cli.v1',status:'BLOCKED',
123
- code:'CONTEXT_RUNTIME_UNSUPPORTED'});
124
- process.exitCode=5;
125
- }else try{
126
- const {runContextCli}=await import('../lib/context-cli.mjs');
127
- emit({contract:'chat-loop.context-cli.v1',...await runContextCli(extra)});
128
- }catch(e){
129
- emit({contract:'chat-loop.context-cli.v1',status:'BLOCKED',
130
- code:e.code||'CONTEXT_ADMIN_FAILED'});
131
- process.exitCode=5;
132
- }
133
- }else if(command==='mcp'){
123
+ await cliApi.observeCliCommand(command,async()=>{
124
+ if(command==='mcp'){
134
125
  if(extra.length){process.stderr.write(JSON.stringify(fail('INVALID_ARGUMENT'))+'\n');process.exitCode=2;}
135
126
  else runGateway();
136
127
  }else if(command==='upgrade'){
@@ -138,9 +129,7 @@ if(command==='context'){
138
129
  ?await prepareReleaseCandidate({tarball:extra[1],sha256:extra[2]})
139
130
  :extra[0]==='activate'&&extra.length===2
140
131
  ?await upgradeRuntime({args:[],requirePrepared:true,expectedArtifactSha256:extra[1]})
141
- :extra[0]==='activate'
142
- ?{command:'upgrade',status:'BLOCKED',code:'RELEASE_ARTIFACT_PIN_REQUIRED'}
143
- :await upgradeRuntime({args:extra});
132
+ :{command:'upgrade',status:'BLOCKED',code:'RELEASE_ARTIFACT_PIN_REQUIRED'};
144
133
  emit(result);if(result.status!=='OK')process.exitCode=result.status==='STARTING'?4:5;
145
134
  }else if(command==='start'&&extra.length===0&&
146
135
  !process.env.CHAT_LOOP_LOCAL_TOOLS_FIXTURES&&
@@ -154,12 +143,9 @@ else if(command==='doctor'){
154
143
  else{const snapshot=inspect();emit({contract:'chat-loop.local-tools.v1',command,...snapshot});if(snapshot.status!=='LOCAL_READY')process.exitCode=1;}
155
144
  }else if(command==='tunnel'){
156
145
  if(extra.length===1&&extra[0]==='doctor'){
157
- const result=tunnelDoctor();
146
+ const result=await tunnelDoctor();
158
147
  emit({contract:'chat-loop.local-tools.v1',command,...result});
159
148
  if(result.status!=='BUNDLED_READY')process.exitCode=1;
160
- }else if(extra.length===1&&extra[0]==='run'){
161
- // Compatibility alias: all tunnel execution now belongs to the Supervisor.
162
- await runControl('start',['tunnel']);
163
149
  }else if(extra.length===1&&extra[0]==='auth'){
164
150
  try{
165
151
  const key=await promptTunnelRuntimeKey();
@@ -176,13 +162,37 @@ else if(command==='doctor'){
176
162
  code:e.code||'TUNNEL_EXEC_FAILED'});process.exitCode=1;}
177
163
  }else{
178
164
  emit({contract:'chat-loop.local-tools.v1',command,status:'FAILED',
179
- code:'INVALID_ARGUMENT',usage:'tunnel doctor | tunnel --version | tunnel auth | tunnel run (managed)'});
165
+ code:'INVALID_ARGUMENT',usage:'tunnel doctor | tunnel --version | tunnel auth'});
180
166
  process.exitCode=2;
181
167
  }
168
+ }else if(command==='api-usage'){
169
+ const windowMinutes=extra.length===0?60:
170
+ extra.length===1&&/^[1-9][0-9]{0,3}$/.test(extra[0])?Number(extra[0]):0;
171
+ if(windowMinutes<1||windowMinutes>1440){
172
+ emit({contract:CONTRACT,command,status:'FAILED',code:'TRACE_INVALID_LIMIT'});
173
+ process.exitCode=2;
174
+ }else{
175
+ try{
176
+ const result=await apiUsage({windowMinutes});
177
+ emit(result);
178
+ if(result.status!=='OK')process.exitCode=1;
179
+ }catch(e){
180
+ emit({contract:CONTRACT,command,status:'BLOCKED',code:e.code||'MANAGER_UNAVAILABLE'});
181
+ process.exitCode=3;
182
+ }
183
+ }
182
184
  }else if(command==='capabilities'){
183
185
  if(extra.length){emit(fail('INVALID_ARGUMENT'));process.exitCode=2;}
184
186
  else emit({contract:'chat-loop.local-tools.v1',command,status:'OK',
185
- implemented:['capabilities','doctor','mcp','start','stop','restart','status','upgrade','tunnel'],
187
+ implemented:[...Object.keys(HELP).filter(Boolean),...cliExtensions.names()].sort(),
186
188
  lifecycle:'SUPERVISOR_MCP_GATEWAY',mcpTools:'Namespaced tool catalog',
187
189
  tunnel:'BUNDLED_SUPERVISOR_MANAGED'});
190
+ }else if(cliExtensions.names().includes(command)){
191
+ try{
192
+ const outcome=await cliExtensions.execute(command,extra,cliApi);
193
+ emit(outcome.result);process.exitCode=outcome.exitCode;
194
+ }catch(e){emit({contract:'chat-loop.local-tools.v1',command,status:'FAILED',
195
+ code:e.code||'CLI_COMMAND_FAILED'});process.exitCode=1;}
188
196
  }else{emit({contract:'chat-loop.local-tools.v1',command,status:'FAILED',code:'UNKNOWN_COMMAND'});process.exitCode=1;}
197
+ });
198
+ }
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ // Private process entry. Obtain API only from the npm SDK root.
3
+ import {runToolsSupervisor} from '../index.mjs';
4
+ await runToolsSupervisor();