@tomflow/chatloop-extension 0.3.84 → 0.4.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.
Files changed (54) hide show
  1. package/README.md +74 -73
  2. package/actions.generated.mjs +11 -0
  3. package/bin/cli.mjs +22 -24
  4. package/bin/native-host.mjs +14 -5
  5. package/capabilities/chat_dom.mjs +1 -0
  6. package/capabilities/chat_screenshot.mjs +1 -0
  7. package/capabilities/chat_text.mjs +1 -0
  8. package/capabilities/clean.mjs +1 -0
  9. package/capabilities/continue.mjs +1 -0
  10. package/capabilities/handoff.mjs +1 -0
  11. package/capabilities/reload.mjs +1 -0
  12. package/capabilities/start.mjs +1 -0
  13. package/capabilities/status.mjs +1 -0
  14. package/extension/actions/common.js +14 -3
  15. package/extension/actions/continue.js +1 -1
  16. package/extension/actions/handoff.js +5 -3
  17. package/extension/actions/index.js +2 -0
  18. package/extension/actions/read-mode.js +9 -0
  19. package/extension/actions/start.js +1 -1
  20. package/extension/background.js +16 -2202
  21. package/extension/loop/action-catalog.generated.js +2 -0
  22. package/extension/loop/api-aspect.generated.js +192 -0
  23. package/extension/loop/core.js +81 -3
  24. package/extension/loop/index.js +34 -0
  25. package/extension/loop/observer-approval.js +227 -0
  26. package/extension/loop/observer-inspect.js +144 -0
  27. package/extension/loop/observer-poll.js +171 -0
  28. package/extension/loop/observer-recovery.js +109 -0
  29. package/extension/loop/observer.js +27 -630
  30. package/extension/loop/resources.js +8 -1
  31. package/extension/manifest.json +6 -2
  32. package/extension/worker/action-result.js +136 -0
  33. package/extension/worker/action-take.js +220 -0
  34. package/extension/worker/admission.js +122 -0
  35. package/extension/worker/adopt-prepare.js +155 -0
  36. package/extension/worker/adopt-recovery.js +185 -0
  37. package/extension/worker/adopt-result.js +120 -0
  38. package/extension/worker/bootstrap.js +172 -0
  39. package/extension/worker/manual.js +165 -0
  40. package/extension/worker/readiness.js +242 -0
  41. package/extension/worker/router.js +150 -0
  42. package/extension/worker/scheduler.js +147 -0
  43. package/extension/worker/turn-failure.js +197 -0
  44. package/extension/worker/turn-finished.js +200 -0
  45. package/index.mjs +62 -0
  46. package/lib/action-routing.mjs +18 -0
  47. package/lib/api-aspect.mjs +190 -0
  48. package/lib/bridge.mjs +26 -7
  49. package/lib/context-binding.mjs +6 -1
  50. package/lib/context-ipc.mjs +44 -2
  51. package/lib/owner-evidence.mjs +67 -0
  52. package/lib/session-file.mjs +20 -8
  53. package/package.json +13 -3
  54. package/scripts/build-actions.mjs +133 -0
package/README.md CHANGED
@@ -1,93 +1,94 @@
1
1
  # @tomflow/chatloop-extension
2
2
 
3
- ## P0 资源生命周期(Extension Worker 唯一仲裁)
4
-
5
- `extension/loop/resources.js` 在既有 Worker 内维护持久资源索引,不引入第二浏览器驱动。正式 Action 同时最多 3 页,已登记执行 Chat 同时最多 2 页(Owner 与 Handoff successor);新建前拒绝超限。已存在的普通 Chat、未知发送、BLOCKED 或带草稿页面不自动关闭。只对精确登记且测试 projectId 为 `cl-intent-e2e-*` 的 DONE Chat 执行空草稿、非激活、URL 未变化的 TTL 回收。用户真实任务的 Chat 不会自动删除;其配额满时安全拒绝新建,需用户确认归属后清理。机器只读 Action 最多 3 分钟后有界回收;写入 Action 仅凭匹配终态与 token 回收。资源创建/关闭/峰值/拒绝写入唯一 `chat-loop.resources.v1` 供 Worker 回溯;未知收据不补发。`ACTION_RESULT_TIMEOUT_UNVERIFIED` 为安全 BLOCKED,不是自动重试。
6
-
7
- **运行状态与手动操作**:首轮发送前新 Chat 未就绪时 Worker 记录安全白名单内的失败码并 BLOCKED,绝不补发未知用户消息。Popup 常规环境检测和用户明确点击 Clean 仍可用,且 Clean 必须经过 Worker 同一个 Action 配额准入。原 `popup.html?audit=1`、`newTest` 与各种隐藏测试清理参数已从运行入口移除;升级时遗留的精确 audit 页仅在非活动且到期后由原有资源管理器清理。
8
-
9
- **0.3.62 Handoff 门禁修复(源码候选,未安装)**:Handoff 新 Chat 的只读编辑器就绪等待从历史最长约 234 秒收紧至最多 100×450ms≈45 秒,避免在前置旧 Chat 核验已耗时的情况下撞上 Worker 330 秒未知结果看门狗。编辑器不就绪会以 `NEW_CHAT_NOT_READY` 提交原 Action 的终态 BLOCKED 回执,不点击发送、不重试、不删除已创建的接班标签。已有 Status 只在原 Native/Worker Owner 精确一致且旧 Handoff BLOCKED 时,额外回报从旧 `chat-loop.resources.v1` **纯只读**匹配的 `diagnostics.handoffTabEvidence`(`tabId/recorded/confirmed=false/pageState/sendReceipt=UNVERIFIED`),不触发资源 reconcile、发送或 Owner 变更。候选通过离线单测不代表旧 `ACTION_RESULT_TIMEOUT_UNVERIFIED` 已得到 `NOT_SENT` 证明,旧版会话不自动恢复。
10
-
11
- **0.3.63 Handoff API 悬挂保护(已发行历史版本)**:即使 `chrome.tabs.get` 或仅用于新 Chat 就绪检查的 `chrome.scripting.executeScript` 永不 settle,现有 `waitForNewChat` 也会对只读 probe 设置有界 Promise 竞争与整体 45 秒墙钟上限;任何无法确认准备完成的路径返回 `NEW_CHAT_NOT_READY`,不触发 composer 写入、发送或第二次建 Chat。和 0.3.62 旧本地候选同为未发布候选,本次以 0.3.63 唯一归档继续验收。
12
-
13
- **0.3.64 Start 只读等待收敛(新增发行候选)**:真实 Chrome 的一次 Start 在先收到失败的替换回执后,Native 却登记了新 Session PENDING、无 Chat ID;后续 330 秒 watchdog 把同一 Start 标成 `ACTION_RESULT_TIMEOUT_UNVERIFIED`。因缺原始用户消息回执,不能断言尚未发送。本版本收敛 Start 新 Chat 的 HOME 检查、编辑器就绪和 Observer 检查:保留超过 35 秒的慢页面能力,整体准备墙钟限约 90 秒;Chrome 只读 Promise 不响应时及时结束为明确故障,严格保留一次建页/一次发送;发送动作及发送后回执仍不自动重试。新增 Chrome 读 API 永不返回的回归反例。此改动不能追认旧 UNKNOWN,也不等于真实 Chrome E2E PASS。
14
-
15
- **0.3.65 Start 只读诊断(源码候选)**:当真实 Chrome Start 创建了首页标签,但返回 `NEW_CHAT_NOT_READY` 时,Status 读取精确 Session 的未确认标签资源;经原 Native Session 一致性校验,仅返回当前 URL 类型、DOM 加载阶段、可见 main 数、输入框数量/可见性/编辑性/空状态及消息节点数量,**不读取消息正文、不点击、不重新发送、不转移 Owner**。此诊断用于区分页面未水合与选择器失效,不能把该状态当作 `NOT_SENT`。专项回归测试对未知 Tab 和跨 Session 标签均拒绝归属。
16
-
17
- **0.3.66 Start/清理动作修复(源码候选)**:真实 Chrome `0.3.65` Status 确认失败 Start 的新首页 `mainCount=1/editorVisible=true/editorEditable=true/messageNodeCount=0`,唯一不满足的是 `editorEmpty=false`。新版 Start 会立即返回 `START_COMPOSER_NOT_EMPTY`,不再等待 90s;原 Clean Action 精确允许 `BLOCKED` Start 所登记的未确认首页,在核实同一 tab ID、失败原因和原首页后只清理输入框(不发送、不清理其他 Chat)。专项负例覆盖外来 tab、非终态、缺少失败原因及导航变更,不能自动重发旧 UNKNOWN。
18
-
19
- **0.3.67 BLOCKED Start 手动发送只读证据**:针对同一 Session 登记的失败 Start 首页,Extension Status 只读返回用户消息 ID、匹配原 Start 提示词的不同消息 ID 数量、助手消息 ID,以及页面节点状态;不返回聊天正文、不点击、不修改 Chrome Owner,也**不把手动点击/DOM 匹配冒充 Native 已确认发送**。新增输入按钮/点击/首条发送回执等精确故障码,专门用于判断未知发送边界。重复匹配消息明确显示数量,不能自动接管或重试。
20
-
21
- **0.3.68 Start 原始提示词指纹验收**:修复 0.3.67 的旧会话误判:Start 在写入结果后会删除一次性提示词,旧 Status 因此总显示匹配 0 条。现在 Start 准备阶段仅保留规范化文本的 SHA-256 指纹、后续删除提示词正文;只读 Status 比较同一未确认测试标签里的消息身份与摘要,返回 `startPromptComparison=AVAILABLE/UNAVAILABLE`。没有历史指纹一律显示 `matchedStartPromptCount=null`,不再把缺少证据解释为不匹配,也不据此确认发送、恢复 Owner 或自动重试。新增 SHA 一致性及历史缺失负例。
22
-
23
- **0.3.70 失败 Start 的只读 Eye 取证(含临时地址严格匹配修正)**:在 `FIRST_SEND_RECEIPT_UNKNOWN` 导致 `BLOCKED` 且 Native 未绑定 Chat Owner 时,原有 `chat_text/chat_dom/chat_screenshot` 只允许检查**同一 Session 资源登记的未确认 Start 标签页**;需原提示词 SHA-256 指纹与恰好一条独立用户消息 ID 匹配,且 DOM 路径和 Chrome 标签 URL 再次一致。其他 Project、未登记资源、重复匹配、页面漂移、来源不符均拒绝。此权限仅用于证据读取,**不更改 Owner、不宣称消息送达、不允许 Continue/Handoff、不重发**。Screenshot Action 会短暂激活该精确标签以取真正的可见 PNG,不新建测试聊天;正式 E2E 必须将页面 Text/DOM/Screenshot 与 Native 和 Trace 一起核对。
24
-
25
- **0.3.71 账号切换故障诊断**:失败 Start 的精确未确认标签页只读检查 ChatGPT 页面显式账号切换错误,返回 `startReadinessEvidence.readiness.uiErrorCode=ACCOUNT_SWITCHED_RETRY_REQUIRED`。该值只代表页面提示(不泄漏用户正文),不能推定是否已送达,不释放 BLOCKED Owner、不重发或点击重试;没有错误或提示仅在用户消息正文时为 `null`。本地源码通过测试后仍须验证已安装 Chrome Worker 的 Status,未部署不得声称实站通过。
26
-
27
- **0.3.72 首轮发送回执窗口(源码候选)**:首次点击只执行一次;随后仅做最多 120 秒、最多 200 次的有界只读检查,允许临时 `local-chatgpt` 地址延迟转成正式 `/c/<Chat ID>`,避免旧 90 次约 38 秒窗口过早将慢成功判为 UNKNOWN。`tabs.get` 和 DOM 读取各自有 1.2 秒超时,整体仍低于原 330 秒 Worker 看门狗。窗口结束仍无匹配的正式 Chat ID 与原用户消息身份,必须保持 `FIRST_SEND_RECEIPT_UNKNOWN/BLOCKED`;不会重发、自动刷新或追认旧 Session。
28
-
29
- **验收边界**:离线源码回归不等于已安装 Chrome 真机通过;正式安装包的 Owner、资源配额及受控发送需要独立实测,不能用旧版证据替代。
30
-
31
- Chrome 扩展(9 个独立 Action,含 Status / Start)及其独立 CLI / Native Messaging Host。执行前先看 Help:
3
+ Chrome MV3 companion for Chat Loop. **Browser Worker is the only Chrome Owner and
4
+ send authority**; Native Messaging is a guarded persistence/IPC boundary,
5
+ not a second browser executor.
6
+
7
+ ## Runtime entrypoints
8
+
9
+ - `index.mjs`: npm SDK with `verifyOrphanOwnerIdle`, `extensionCliApi`,
10
+ `nativeHostApi` — the only three exported functions.
11
+ - `bin/cli.mjs`: the `chatloop-extension` CLI (`npx` after publishing).
12
+ - `bin/native-host.mjs`: private Chrome Native Messaging Host process.
13
+ - `extension/background.js`: MV3 Worker and unique Browser Owner.
14
+ - `extension/actions/*.js`: Action executors; browser APIs are not Node SDKs.
15
+
16
+ ## API invocation logging
17
+
18
+ The public npm SDK, CLI and Native Host functions use a generated, bounded,
19
+ non-blocking API observation slice. The MV3 Worker's formal message dispatch
20
+ records only the allowlisted message type, not payloads or chat text. It
21
+ forwards a separate, best-effort Native observation into the **existing
22
+ Supervisor Trace** when available; an unavailable Native Host or Supervisor
23
+ can drop these observations but cannot change Owner or action receipts.
24
+ Remotely exposed Extension MCP calls are recorded independently by the Tools
25
+ Gateway's single API observation port. No second log service is created.
26
+ Logging cannot authorize sending, change Owner or retry an UNKNOWN action.
27
+
28
+ ## Build-time Action capabilities
29
+
30
+ Each `capabilities/<id>.mjs` owns an Action's name, CLI route, page,
31
+ execution kind, result type and local deadline. No separate API catalog is
32
+ maintained. `npm run build:actions` generates both:
33
+
34
+ - `actions.generated.mjs` — Node CLI/Native SDK action catalog.
35
+ - `extension/loop/action-catalog.generated.js` — browser-only Eye map.
36
+
37
+ New **read-only Eye** actions can declare an additional `chat_*` name,
38
+ their own CLI route, and either the existing `text` or `dom` read mode.
39
+ The builder creates their isolated Action HTML, which uses the same
40
+ `actions/common.js` target/Owner/Native receipt checks and the shared
41
+ `actions/read-mode.js` executor. No existing Action or central CLI/Worker
42
+ dispatch switch needs modification. The builder refuses duplicate names,
43
+ privileged type changes, invalid read modes, missing assets and stale output.
44
+
45
+ **A declaration does not grant sending authority.** Start, Continue, Handoff,
46
+ Clean, Status, screenshot and reload keep their reviewed, explicit Worker
47
+ handlers and existing trust boundaries. New send/Owner/Native mutation
48
+ requires a separate authorized security review and implementation; it cannot
49
+ be enabled by dropping in a capability file. Browser read actions never
50
+ clear an unknown send result or adopt a different Chat Owner.
51
+
52
+ ### Validation
32
53
 
33
54
  ```sh
34
- npx --yes --package=@tomflow/chatloop-extension@latest chatloop-extension --help
55
+ npm run build:actions
56
+ npm run build:actions:check
57
+ npm test
35
58
  ```
36
59
 
60
+ Workspace `npm run check` and npm `pretest`/`prepack` also verify generated
61
+ catalogs. `test/capability-composition.test.mjs` proves isolated addition and
62
+ removal of an Eye action and rejects privileged or duplicate declarations.
63
+ The package build and Chrome manifest versions must match.
64
+
65
+ ## CLI
66
+
37
67
  ```text
38
68
  Usage: chatloop-extension <command> [options]
39
69
  Commands: capabilities, host, extension
40
70
  Run: chatloop-extension <command> --help
41
71
  ```
42
72
 
43
- ```sh
44
- npx --yes --package=@tomflow/chatloop-extension@latest chatloop-extension extension --help
45
- ```
46
-
47
73
  ```text
48
74
  Usage: chatloop-extension extension <command>
49
- Commands: chat text | chat dom | chat screenshot | reload | clean <tab-id> | continue | handoff | status | start
75
+ Commands: chat text | chat dom | chat screenshot | reload | continue | handoff | clean <tab-id> | status | start
50
76
  Run: chatloop-extension extension <command> --help
51
77
  ```
52
78
 
53
- **Chrome 独立运行安装路径:**先用 `npm install --prefix "$HOME/.chat-loop/extension/npm" --save-exact --ignore-scripts @tomflow/chatloop-extension@latest` 下载,再在 `chrome://extensions` 加载该目录下的 `node_modules/@tomflow/chatloop-extension/extension`。改目录会改变扩展 ID,必须通过同一个 npm 包的 `host install <id>` 更新 Native Host。详情见 [Extension 主文档](../../docs/extension.md)。
54
-
55
- **原 Chat 接管候选接口**:用户在同一普通 Chat 完成两轮真实 R/P 确认后,用 `chat_loop_extension__start({projectId,mode:'adopt',confirmed:true})` 申请原地绑定;可选提供规范化的 `chatUrl` 精确限制候选范围,但不可用它代替批准证据。扩展自己核对真实网页 R→user确认→P(引用当前R)→user确认,必须唯一匹配;不新建 Chat、不写输入框、不重发消息。未匹配/多匹配/版本变化一律拒绝;当前代码的正式 Chrome E2E 尚未完成,不能以本机测试替代发布。
56
-
57
- `extension start` 正常只在 `status=IDLE`、用户确认后启动。上一 Session 若是 `BLOCKED`,可在用户**再次明确批准一个不同 projectId 的全新任务**时附上 `replaceBlockedSessionId`(精确 UUID)作为受控替换条件:扩展 Worker 与本机持久指针必须同时指向该 BLOCKED Session,才能允许新 Session;旧执行 Chat 保留审计,旧用户 Turn 永不自动重发。示例只用于说明 JSON 签名,不会自动调用:
58
-
59
- ```json
60
- {"projectId":"new-distinct-test","prompt":"新的独立任务","confirmed":true,"replaceBlockedSessionId":"11111111-1111-4111-a111-111111111111"}
61
- ```
62
-
63
- `PAGE_ERROR` 且无原生 Retry 时,Worker 最多四次只读核实同一用户消息;只有同一 Turn 的错误消失并连续稳定,才恢复观察;仍有错误、身份变化或回执不明时 BLOCKED。`lastFaultProof` 存在当前 Owner 的持久状态中,不会把当前网页错误消失推断成“可以重发”。
64
-
65
- Clean 只清空输入框,不发送,不更改 Owner;必须指定精确标签页 ID 且验证目标。Chrome 已安装扩展不随 npm 包自动安装。本地源码与已发布 npm 版本可能不同,真实结果请看 [CURRENT](../../docs/CONTEXT.md)。
66
-
67
- 详细接口和安全边界统一见 [Extension 产品文档](../../docs/extension.md)。
68
-
69
- **新页准备超时策略(0.3.45)**:Start 新 Chat 编辑器只读等待约 218 秒,Handoff 新 Chat 只读等待约 234 秒,均保持一次新建/一次发送且不跳过 ChatGPT 网页验证。Start CLI 最多等待 310 秒,MCP Tools 转发最多 330 秒;Worker 对 Start/Handoff 的未确认资源等待 330 秒,其它 Action 维持 180 秒。窗口到期仍无确定回执时保留 BLOCKED,禁止自动重发。
70
-
71
- **0.3.46 Chrome pendingUrl 修复**:Worker 创建正式 Action 时,以自己刚发起的受控 Extension URL 与 Chrome 返回的数值 tabId 登记资源,不能依赖 `tabs.create` 立即返回最终 `tab.url`(它可能仅有 `pendingUrl`)。Action 自身仍需验证真实 URL、Owner、token,任何未确认发送都不得重试;代码回归覆盖过渡 tab.url 缺失但单次 Action 正常创建。
72
-
73
- **npm 发行版 0.3.48**:Worker 内正式串行消息类型统一以显式路由表派发,各处理器的来源、一次性凭证和 Owner 身份校验保持不变。此版本已发布到 npm 并安装到本机原扩展目录;Chrome 是否重新载入新代码以及真实 E2E 结果须单独验证,具体以 [CURRENT](../../docs/CONTEXT.md) 为准。
74
-
75
-
76
- **0.3.48 中的源码级熵减**:删除仅用于旧手动验收的 Popup 脚本、Clock Action、计数/模拟墙钟状态及其专属测试。正式 Start、Continue、Handoff 与 Observer/Owner、十分钟真实时钟、错误隔离、配额与已登记测试 Chat 的安全回收保持实现。继续/交接只能由独立 Action 单次发送,用户未发送草稿不允许清除;过往隐藏验收 URL 不再可调用。确切最新测试数量及未验证项只看 [CURRENT](../../docs/CONTEXT.md)。
77
-
78
- **历史 0.3.49 接管候选**:此前用于实现同 Chat adopt;后续版本已演进并发布。最新安装、Owner 与真实验收进度只查 [CURRENT](../../docs/CONTEXT.md),不要沿用历史‘未发布’结论。
79
-
80
-
81
- **可视化消息定位(0.3.58)**:真实 Chat 若因历史片段挂载而无法从当前 DOM 验证最新 BLOCKED Turn,不允许依赖旧消息直接 Continue。正式 Status 仅在真实 Owner tab URL 已核实且为 WAITING_REPLY/BLOCKED 时,于 diagnostics 返回只作定位用的 ownerTabId,绝非发送凭证。只有操作员明确打开原内置 Continue Action 并提供精确 tabId 与 Native 最新 updatedAt(resumeBlockedAt),Worker 才能只读核验原 Session/Chat/generation、BLOCKED 类型、独立故障、精确 tab/URL、正式 Action 来源和 Native CAS;核验通过后**仅由 Action 页**尝试滚动原 Chat 到最新挂载区。不更新 Worker 或 Native 会话状态,不点击提交。随后仍要求原有两次稳定最新 user/assistant 身份、无待审批表单和唯一发送许可;任何滚动/身份/状态不明均 fail-closed。普通 Continue/Handoff 与其它 Chat 不触发此行为,不能以滚动成功宣称业务恢复。
82
-
83
- **终态历史 Chat 的资源配额(0.3.60)**:资源库存保留已结束的 Chat 标签与证据,但 DONE/BLOCKED 的旧 Session 不再占用新任务“活动 Owner + Handoff 继任者”两席配额,不关闭用户 Chat。已从 BLOCKED 受控恢复、仍是同一个活动 Session 的 Chat 必须重新占用活动配额;未知来源首页、未确认发送和未结束 Chat 仍计入限制并安全拒绝。该修正只影响资源准入计数,不改变 Native/Worker Owner、审批或消息发送权限。
84
-
85
- ## 原 Owner 的有界技术恢复
86
-
87
- Worker仍是唯一发送裁决者,Native会话文件只是带身份校验的持久投影。正式Status返回当前Session/Chat及有限diagnostics(版本、失败码、消息身份、恢复预算、执行时钟),不返回发送token或任务正文;终态BLOCKED的Eye可只读检查同一个已确认Owner,不获得发送权。
79
+ For the installed command list, run `chatloop-extension extension --help`.
88
80
 
89
- 已由可信操作者核实修复的可逆工程阻断(不限于历史 Start/adopt 故障),可按实际恢复合同通过原内置 `continue.html?tabId=<原Owner精确tabId>` 申请一次恢复。必须保持Session/project/Chat/generation、两条原消息身份和执行时钟,无待确认表单;未知发送、权限拒绝和页面挑战不自动恢复。恢复预算在后续Continue中继续保留。恢复成功不是业务DONE。
81
+ `extension start` requires the real approved intent; `mode=adopt` does not
82
+ re-send. Continue/Handoff only register intents with one Turn token and never
83
+ silently send or repeat. Clean needs an exact verified tab ID, and Status
84
+ is read-only. IPC messages are one-shot and have durable identity checks.
90
85
 
91
- 仅升级前的0.3.52遗留预留可能需要显式 `&repairLegacyReservation=<Native原updatedAt>`:操作者须先验证保存的旧Native源码确实不能提交BLOCKED→PENDING,且原消息和指针未变。Worker还要求旧恢复来源、旧user未变、没有现代recoveryProtocol;Native在锁内对精确updatedAt做CAS。缺任何证据均禁止使用;此参数不能解锁现代未知发送,也不是自动重试机制。禁止直接编辑active-session.json。
86
+ This package's source version is read from its own `package.json`. Installed
87
+ Tools/Context consumers may pin a different Extension version; updating
88
+ their dependencies is a separate release task. Source tests do not prove
89
+ npm publication, Chrome reload, Native Host installation or Stage 03 E2E.
90
+ Inspect real installed versions, Owner and authoritative receipts first.
92
91
 
93
- Native与Chrome.storage是两个存储,按顺序提交不代表跨存储原子事务;中途崩溃且无法证明发送边界时保持UNVERIFIED/BLOCKED,先查正式回执,不重发。回滚Native/Extension前先核实当前Owner,不把旧代码强行覆盖正在执行的新协议。
92
+ Product-level Extension/Context documents live in the source repository,
93
+ **not in this published npm package**. Its runtime API and security contract
94
+ are described above without requiring that repository.
@@ -0,0 +1,11 @@
1
+ // GENERATED by scripts/build-actions.mjs — do not edit.
2
+ import {capability as a0} from './capabilities/chat_text.mjs';
3
+ import {capability as a1} from './capabilities/chat_dom.mjs';
4
+ import {capability as a2} from './capabilities/chat_screenshot.mjs';
5
+ import {capability as a3} from './capabilities/reload.mjs';
6
+ import {capability as a4} from './capabilities/continue.mjs';
7
+ import {capability as a5} from './capabilities/handoff.mjs';
8
+ import {capability as a6} from './capabilities/clean.mjs';
9
+ import {capability as a7} from './capabilities/status.mjs';
10
+ import {capability as a8} from './capabilities/start.mjs';
11
+ export const actionCapabilities=Object.freeze([a0,a1,a2,a3,a4,a5,a6,a7,a8]);
package/bin/cli.mjs CHANGED
@@ -5,12 +5,17 @@ import {existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync} from 'nod
5
5
  import {homedir} from 'node:os';
6
6
  import {dirname,join,resolve} from 'node:path';
7
7
  import {fileURLToPath} from 'node:url';
8
- import {ACTIONS,HOST_NAME,configFile,prepare,readResult,privateDir,validateExtensionId} from '../lib/bridge.mjs';
8
+ import {extensionCliApi} from '../index.mjs';
9
+ const {ACTIONS,actionCapabilities,matchExtensionAction,HOST_NAME,configFile,prepare,readResult,privateDir,validateExtensionId}=extensionCliApi();
10
+ const actionById=new Map(actionCapabilities.map(cap=>[cap.id,cap]));
11
+ const actionHelp=actionCapabilities.map(cap=>cap.cli.join(' ')+
12
+ (cap.kind==='owner-clean'?' <tab-id>':'')).join(' | ');
9
13
  const contract='chat-loop.extension-cli.v1';
14
+ const providerVersion=JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version;
10
15
  const HELP={
11
16
  '': 'Usage: chatloop-extension <command> [options]\nCommands: capabilities, host, extension\nRun: chatloop-extension <command> --help',
12
17
  host: 'Usage: chatloop-extension host install <extension-id>\nRegisters the local Chrome Native Messaging Host (macOS).',
13
- extension: 'Usage: chatloop-extension extension <command>\nCommands: chat text | chat dom | chat screenshot | reload | clean <tab-id> | continue | handoff | status | start\nRun: chatloop-extension extension <command> --help',
18
+ extension: 'Usage: chatloop-extension extension <command>\nCommands: '+actionHelp+'\nRun: chatloop-extension extension <command> --help',
14
19
  'extension clean':'Usage: chatloop-extension extension clean <tab-id>\nClear only the verified ChatGPT composer. Never send or close a Chat.\nMachine Clean requires the exact tab id of a terminal Chat Loop Owner; popup Clean requires a user-selected ChatGPT tab.',
15
20
  'extension continue':'Usage: chatloop-extension extension continue (JSON intent on stdin)\nSubmit next-turn text or query receipt; does not send directly.',
16
21
  'extension handoff':'Usage: chatloop-extension extension handoff (JSON intent on stdin)\nRequest early handoff or query receipt; does not transfer directly.',
@@ -30,7 +35,7 @@ function helpFor(args){
30
35
  }
31
36
 
32
37
  const wait=ms=>new Promise(r=>setTimeout(r,ms));
33
- const emit=(event,command,fields={})=>process.stdout.write(JSON.stringify({contract,event,command,...fields})+'\n');
38
+ const emit=(event,command,fields={})=>process.stdout.write(JSON.stringify({contract,providerVersion,event,command,...fields})+'\n');
34
39
  const quoted=s=>"'"+s.replaceAll("'","'\\''")+"'";
35
40
  function installHost(extensionId) {
36
41
  validateExtensionId(extensionId);
@@ -64,18 +69,19 @@ function openAction(url) {
64
69
  async function executeAction(action,intent) {
65
70
  if(!ACTIONS.includes(action))throw Object.assign(Error('Unknown action'),{code:'UNKNOWN_ACTION'});
66
71
  const config=configuration(),req=prepare(action,intent);
67
- const page=action==='reload'?'reload.html': ['continue','handoff','clean','start','status'].includes(action)
68
- ? action+'.html':action.slice(5)+'.html';
72
+ const descriptor=actionById.get(action);
73
+ const page=descriptor?.page;
74
+ if(!page)throw Object.assign(Error('Unknown action'),{code:'UNKNOWN_ACTION'});
69
75
  const url='chrome-extension://'+config.extensionId+'/'+page+'?requestId='+req.id;
70
76
  openAction(url);
71
- const until=Date.now()+(action==='start'?310000:27000);
77
+ const until=Date.now()+descriptor.waitMs;
72
78
  while(Date.now()<until){
73
79
  const result=readResult(req.id);
74
80
  if(result){
75
81
  if(result.status!=='OK')throw Object.assign(Error(result.code||'ACTION_FAILED'),{code:result.code||'ACTION_FAILED'});
76
82
  if(!result.verified) return {...result,status:'ACCEPTED_UNVERIFIED'};
77
83
  // The temp file is the canonical artifact. Returning small text is a CLI convenience.
78
- if(['chat_text','chat_dom','continue','handoff','clean','start','status'].includes(action)){
84
+ if(descriptor.textResult){
79
85
  const contents=readFileSync(result.path,'utf8');
80
86
  return {...result,content:contents.length<=500000?contents:undefined,
81
87
  truncated:contents.length>500000};
@@ -90,8 +96,9 @@ async function readIntent() {
90
96
  // Only for model control tools. Read a bounded stdin payload; never embed text in URL/argv.
91
97
  if(process.stdin.isTTY)throw Object.assign(Error('JSON intent required on stdin'),{code:'INVALID_INTENT'});
92
98
  let body='';
99
+ process.stdin.setEncoding('utf8'); // JSON intent may span UTF-8 chunks.
93
100
  for await(const chunk of process.stdin){
94
- body+=chunk.toString();
101
+ body+=chunk;
95
102
  if(body.length>6000)throw Object.assign(Error('Model intent too large'),{code:'INVALID_INTENT'});
96
103
  }
97
104
  try {return JSON.parse(body);}catch{
@@ -101,25 +108,16 @@ async function readIntent() {
101
108
  async function execute(argv) {
102
109
  const cmd=argv.join(' ');
103
110
  if(argv.length===0||cmd==='capabilities'){
104
- return {implemented:['capabilities','host install <extension-id>','extension chat text',
105
- 'extension chat dom','extension chat screenshot','extension reload',
106
- 'extension clean <tab-id>',
107
- 'extension continue (JSON on stdin)','extension handoff (JSON on stdin)',
108
- 'extension status','extension start (JSON on stdin)'],
111
+ return {implemented:['capabilities','host install <extension-id>',
112
+ ...actionCapabilities.map(cap=>'extension '+cap.cli.join(' ')+
113
+ (cap.kind==='owner-clean'?' <tab-id>':
114
+ ['owner-intent','owner-start'].includes(cap.kind)?' (JSON on stdin)':''))],
109
115
  available:existsSync(configFile()),hostConfigured:existsSync(configFile())};
110
116
  }
111
117
  if(argv[0]==='host'&&argv[1]==='install'&&argv.length===3)return installHost(argv[2]);
112
- if(argv[0]==='extension'&&argv[1]==='chat'&&argv.length===3 &&
113
- ['text','dom','screenshot'].includes(argv[2]))
114
- return executeAction('chat_'+argv[2]);
115
- if(cmd==='extension reload')return executeAction('reload');
116
- if(argv.length===3&&argv[0]==='extension'&&argv[1]==='clean'
117
- &&/^[1-9][0-9]*$/.test(argv[2])&&Number.isSafeInteger(Number(argv[2])))
118
- return executeAction('clean',{tabId:Number(argv[2])});
119
- if(cmd==='extension continue')return executeAction('continue',await readIntent());
120
- if(cmd==='extension handoff')return executeAction('handoff',await readIntent());
121
- if(cmd==='extension status')return executeAction('status');
122
- if(cmd==='extension start')return executeAction('start',await readIntent());
118
+ const route=matchExtensionAction(actionCapabilities,argv);
119
+ if(route)return executeAction(route.id,route.needsIntent
120
+ ?await readIntent():route.intent);
123
121
  throw Object.assign(Error('Unknown command'),{code:'INVALID_ARGUMENT'});
124
122
  }
125
123
  const args=process.argv.slice(2),command=args.join(' ')||'capabilities';
@@ -1,9 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // Chrome Native Messaging: one request per process, no persistent server.
3
- import {readRequest, finish} from '../lib/bridge.mjs';
4
- import {readSession,writeSession} from '../lib/session-file.mjs';
5
- import {registeredContext} from '../lib/context-binding.mjs';
6
- import {nativeContextControl} from '../lib/context-ipc.mjs';
3
+ import {nativeHostApi} from '../index.mjs';
4
+ const {readRequest,finish,readSession,writeSession,registeredContext,
5
+ nativeContextControl,nativeApiObservation,observeNativeOperation}=nativeHostApi();
7
6
  const MAX_INPUT=48*1024*1024;
8
7
  const write=obj=>{
9
8
  const b=Buffer.from(JSON.stringify(obj)),len=Buffer.alloc(4);
@@ -20,6 +19,7 @@ process.stdin.on('data',async chunk=>{
20
19
  handled=true;
21
20
  try{
22
21
  const m=JSON.parse(buf.subarray(4,4+n).toString('utf8'));
22
+ const dispatch=async()=>{
23
23
  if(m.op==='acquire'){
24
24
  const r=readRequest(m.id);
25
25
  if(r.action!==m.action)throw Object.assign(Error('Action mismatch'),{code:'REQUEST_MISMATCH'});
@@ -40,7 +40,7 @@ process.stdin.on('data',async chunk=>{
40
40
  throw Object.assign(Error('No Context-managed session'),{code:'CONTEXT_SESSION_UNBOUND'});
41
41
  if(!['permit.consume','run.bind.initial','run.fence','run.bind.handoff',
42
42
  'run.restore-same-owner','run.fence.terminal','run.credential.rotate',
43
- 'run.terminalStatus','run.snapshot'].includes(m.command)
43
+ 'run.terminalStatus','run.reopenStatus','run.snapshot'].includes(m.command)
44
44
  ||!m.args||typeof m.args!=='object'||Array.isArray(m.args))
45
45
  throw Object.assign(Error('Invalid Context command'),{code:'CONTEXT_COMMAND_INVALID'});
46
46
  const own=new Set(['projectId','taskId','sessionId','generation','activeChatId',
@@ -57,9 +57,18 @@ process.stdin.on('data',async chunk=>{
57
57
  args.runRef=session.sessionId+':'+session.taskId+':'+session.generation;
58
58
  const result=await nativeContextControl(m.command,args);
59
59
  write({status:'OK',result});
60
+ }else if(m.op==='api-observation'){
61
+ // Separate request. Observations never delay a business Native reply.
62
+ const recorded=await nativeApiObservation(m.record);
63
+ write({status:recorded?'RECORDED':'DROPPED'});
60
64
  }else if(m.op==='session-sync'){
61
65
  write({status:'OK',session:writeSession(m.session,
62
66
  m.replaceBlockedSessionId,m.resumeBlockedSessionId,m.resumeBlockedUpdatedAt??null)});
63
67
  }else throw Object.assign(Error('Unknown operation'),{code:'INVALID_OPERATION'});
68
+ };
69
+ // The telemetry operation is intentionally excluded from self-recording.
70
+ // Recording it here would recursively spawn more Native log requests.
71
+ if(m.op==='api-observation')await dispatch();
72
+ else await observeNativeOperation(m.op,dispatch);
64
73
  }catch(e){write({status:'FAILED',code:e.code||'NATIVE_HOST_ERROR'});}
65
74
  });
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'chat_dom',page:'dom.html',cli:['chat', 'dom'],kind:'eye-read',waitMs:27000,textResult:true,readMode:'dom',description:'Read verified owner chat DOM'});
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'chat_screenshot',page:'screenshot.html',cli:['chat', 'screenshot'],kind:'eye-screenshot',waitMs:27000,textResult:false,description:'Capture verified owner screenshot'});
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'chat_text',page:'text.html',cli:['chat', 'text'],kind:'eye-read',waitMs:27000,textResult:true,readMode:'text',description:'Read verified owner chat text'});
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'clean',page:'clean.html',cli:['clean'],kind:'owner-clean',waitMs:27000,textResult:true,description:'Clean exact composer without sending'});
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'continue',page:'continue.html',cli:['continue'],kind:'owner-intent',waitMs:27000,textResult:true,description:'Queue Continue intent'});
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'handoff',page:'handoff.html',cli:['handoff'],kind:'owner-intent',waitMs:27000,textResult:true,description:'Queue Handoff intent'});
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'reload',page:'reload.html',cli:['reload'],kind:'eye-reload',waitMs:27000,textResult:false,description:'Request extension reload, unverified'});
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'start',page:'start.html',cli:['start'],kind:'owner-start',waitMs:310000,textResult:true,description:'Start or adopt approved Chat'});
@@ -0,0 +1 @@
1
+ export const capability=Object.freeze({id:'status',page:'status.html',cli:['status'],kind:'owner-status',waitMs:27000,textResult:true,description:'Read unique browser Owner'});
@@ -44,13 +44,22 @@ async function closeAction(ownTab) {
44
44
  await chrome.tabs.remove(ownTab.id);
45
45
  }
46
46
  async function readChat(tab, mode) {
47
+ // Capture the original URL, not the mutable Chrome Tab object. A user may
48
+ // navigate this same tab while a content-script read is in flight.
49
+ const expectedUrl=tab.url;
50
+ const verifyTarget=async()=>{
51
+ const current=await chrome.tabs.get(tab.id).catch(()=>null);
52
+ if(!current || current.url!==expectedUrl)throw Error('TARGET_CHANGED_DURING_READ');
53
+ };
47
54
  const request = () => chrome.tabs.sendMessage(tab.id,
48
55
  {type: "CHAT_LOOP_EYE_READ_V1", mode});
49
56
  let response;
50
57
  try {
51
58
  response = await request();
52
59
  } catch {
53
- // Reload invalidates old content scripts. Reinject only into the selected ChatGPT tab.
60
+ // Reload invalidates old content scripts. Never reinject after a tab has
61
+ // navigated away from the original target during this read.
62
+ await verifyTarget();
54
63
  try {
55
64
  await chrome.scripting.executeScript({target: {tabId: tab.id}, files: ["content.js"]});
56
65
  response = await request();
@@ -62,6 +71,7 @@ async function readChat(tab, mode) {
62
71
  || response?.mode !== mode || typeof response?.value !== "string") {
63
72
  throw Error("INVALID_CONTENT_RESPONSE");
64
73
  }
74
+ await verifyTarget();
65
75
  return response.value;
66
76
  }
67
77
  function copyText(value) {
@@ -136,8 +146,9 @@ function copyText(value) {
136
146
  }
137
147
  // Text and DOM share the same verified read path. Their separate pages
138
148
  // select a fixed mode and clipboard settling delay; no extra executor.
139
- async function runReadAction(mode, clipboardMs) {
140
- const action="chat_"+mode;
149
+ async function runReadAction(mode, clipboardMs, action="chat_"+mode) {
150
+ if(!['text','dom'].includes(mode)||!/^chat_[a-z0-9_]+$/.test(action))
151
+ throw Error('EYE_MODE_UNSUPPORTED');
141
152
  try {
142
153
  const machine=await machineBinding(action);
143
154
  const own=requireOwnTab(await chrome.tabs.getCurrent());
@@ -318,5 +318,5 @@ async function run() {
318
318
  await chrome.tabs.remove(own.id);
319
319
  }
320
320
  (new URLSearchParams(location.search).has("requestId")
321
- ? import(chrome.runtime.getURL("actions/model-intent.js")).then(m => m.queueModelIntent("continue")) : run())
321
+ ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("continue")) : run())
322
322
  .catch(error => show("BLOCKED", error.message || "ACTION_FAILED"));
@@ -212,7 +212,9 @@ async function sendHandoffOnce(tabId, text) {
212
212
  || user.querySelector?.('[data-user-message-bubble="true"]') || user;
213
213
  const canonical = v => String(v || '').replace(/\s+/g, '');
214
214
  return id && id === keys[0]
215
- && canonical(bubble.innerText || bubble.textContent).includes(canonical(expected))
215
+ // A substring match may accept an extra or corrupted user message.
216
+ // The sole successor Turn must contain exactly the sent handoff text.
217
+ && canonical(bubble.innerText || bubble.textContent)===canonical(expected)
216
218
  ? {userKey: 'user:' + id} : null;
217
219
  },args: [text]});
218
220
  if (read?.result?.reason) throw Error(read.result.reason);
@@ -301,7 +303,7 @@ async function run() {
301
303
  {type: "CHAT_LOOP_TURN_OBSERVE_V1"}); } catch { /* Reconnect below. */ }
302
304
  if (observed?.contract !== "chat-loop.turn-observer.v1") {
303
305
  await chrome.scripting.executeScript({target: {tabId: newTab.id},
304
- files: ["content.js", "loop/observer.js"]});
306
+ files: ["content.js", "loop/observer-inspect.js", "loop/observer-poll.js", "loop/observer-recovery.js", "loop/observer-approval.js", "loop/observer.js"]});
305
307
  observed = await chrome.tabs.sendMessage(newTab.id,
306
308
  {type: "CHAT_LOOP_TURN_OBSERVE_V1"});
307
309
  }
@@ -372,5 +374,5 @@ async function run() {
372
374
  await chrome.tabs.remove(own.id);
373
375
  }
374
376
  (new URLSearchParams(location.search).has("requestId")
375
- ? import(chrome.runtime.getURL("actions/model-intent.js")).then(m => m.queueModelIntent("handoff")) : run())
377
+ ? import(chrome.runtime.getURL("actions/index.js")).then(m => m.queueModelIntent("handoff")) : run())
376
378
  .catch(error => show("BLOCKED", error.message || "HANDOFF_ACTION_FAILED"));
@@ -0,0 +1,2 @@
1
+ // Browser Action API root. Actions only import this, not private helpers.
2
+ export {queueModelIntent} from './model-intent.js';
@@ -0,0 +1,9 @@
1
+ // Stateless Eye executor: read only a declared text/DOM mode with the same
2
+ // trusted Owner/Native admission as the two original Eye pages.
3
+ const script=document.currentScript;
4
+ const action=script?.dataset?.action;
5
+ const mode=script?.dataset?.readMode;
6
+ if(!/^chat_[a-z0-9_]+$/.test(action||'')||!['text','dom'].includes(mode))
7
+ throw Error('EYE_CAPABILITY_INVALID');
8
+ void globalThis.ChatLoopActionCommonV1.runReadAction(
9
+ mode,mode==='text'?250:1000,action);
@@ -59,7 +59,7 @@ async function observerReady(id){
59
59
  {type:'CHAT_LOOP_TURN_OBSERVE_V1'}),3000);
60
60
  if(proof?.contract!=='chat-loop.turn-observer.v1'){
61
61
  const injected=await boundedRead(()=>chrome.scripting.executeScript({
62
- target:{tabId:id},files:['content.js','loop/observer.js']}),3000);
62
+ target:{tabId:id},files:['content.js', 'loop/observer-inspect.js', 'loop/observer-poll.js', 'loop/observer-recovery.js', 'loop/observer-approval.js', 'loop/observer.js']}),3000);
63
63
  if(!injected)throw Error('FIRST_TURN_OBSERVER_UNAVAILABLE');
64
64
  proof=await boundedRead(()=>chrome.tabs.sendMessage(id,
65
65
  {type:'CHAT_LOOP_TURN_OBSERVE_V1'}),3000);