@christang/keel 5.84.0 → 5.85.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.
package/README.md CHANGED
@@ -76,6 +76,15 @@ keel --version
76
76
  codex plugin add keel@<marketplace> # Codex
77
77
  ```
78
78
 
79
+ For Codex, start a fresh session after updating the plugin and review its current
80
+ hook definitions with `/hooks` in the CLI. Installation does not grant hook trust.
81
+ Bind a mailbox role with `keel mail role --set codex-maint`; trusted hooks announce
82
+ unread mail at session start and the next user input without marking it read.
83
+ If receiving hooks are unavailable, use `keel mail list` and `keel mail read`
84
+ explicitly. Codex idle wake-up and native write-guard enforcement remain unverified.
85
+ See the [Codex acceptance record](docs/codex-validation.md) for versions, runtime
86
+ evidence, limitations and the clean-consumer Full-mode check.
87
+
79
88
  A global `keel` comes first on PATH, ahead of the plugin's copy, so on Claude Code the agent runs
80
89
  it instead. Keep it at the plugin's version or remove it (`npm rm -g @christang/keel`); the
81
90
  session-start line names it whenever the two disagree.
@@ -607,6 +616,10 @@ This changes only what Keel *recommends*. No gate, the write guard, and completi
607
616
  exactly as they would without it, and `keel context --change <paused>` still selects it — you asked
608
617
  for it by name. Keel never pauses a change on its own.
609
618
 
619
+ ## Group chat between sessions
620
+
621
+ Sessions working the same repository — a Claude Code session, a Codex session, an unattended runner, and you — share a work group with `keel chat`. Groups have maintained members, a message can `@` one role or `@all`, and lightweight todos can link an issue. Each member has its own unread state, and history is kept. Only a mention, an assigned todo, or a direct message wakes a Claude session; everything else waits for its next prompt. A message is data from another agent and never authorization. With one Slack app and one bridge process per machine, the same groups reach sessions on other machines and your phone in real time, and an orphan `keel-chat` branch keeps the history past Slack's retention: see [the Slack setup guide](docs/chat-slack-setup.md). The 5.83 `keel mail` commands keep working on direct groups.
622
+
610
623
  ## Commands
611
624
 
612
625
  ```bash
@@ -628,6 +641,15 @@ keel guard clear --json
628
641
  keel lenses list
629
642
  keel lenses add <name> [--force]
630
643
 
644
+ # Group chat between sessions (see docs/chat-slack-setup.md for Slack)
645
+ keel chat role --set <role> [--alias <a>]
646
+ keel chat group create <g> [--member <r>]... | add | remove | archive | list
647
+ keel chat <g> [<text>] [--since 2h] [--follow] # read, or post
648
+ keel chat dm <role> <text> | todo <g> --assignee <r> <text> | todos [--mine]
649
+ keel chat unread | read | notice | search <text>
650
+ keel chat bridge add | install | status | pause <2h> | stop | start | uninstall
651
+ keel chat archive sync | pull
652
+
631
653
  # Unattended triage — may this issue start work without asking?
632
654
  # Keel never fetches the issue; pass what gh returned. At least one of the two.
633
655
  keel triage [--labels <l1,l2>] [--issue <n>] [--json]
package/README.zh-CN.md CHANGED
@@ -170,6 +170,18 @@ keel --uninstall # 当 core.hooksPath 由 Keel 设置时回退
170
170
 
171
171
  `--with-git-hooks` 是显式 opt-in:普通 `keel --install` 绝不碰 git config,且这个覆盖仅限本仓、可逆。
172
172
 
173
+ ## 会话之间的群聊
174
+
175
+ 在同一个仓库里干活的各个会话——Claude Code、Codex、无人值守的执行器,还有你——用 `keel chat` 组成一个工作群:
176
+ - 群成员可以增删维护;
177
+ - 消息可以 @ 某个角色,也可以 @all;
178
+ - 可以挂轻量待办,并关联 issue;
179
+ - 每个成员有各自的未读状态,历史全部保留。
180
+
181
+ 只有被 @、分到待办或收到私聊时才会唤醒 Claude 会话,其余消息等下一次对话时再提示。消息只是另一个 agent 发来的数据,不代表授权。
182
+
183
+ 每台电脑配一个 Slack App、跑一个桥接程序,同一批群就能实时连到其他电脑上的会话和你的手机。聊天记录同时存在孤儿分支 `keel-chat` 上,不受 Slack 保留期限制。配置方法见 [Slack 配置说明](docs/chat-slack-setup.zh-CN.md)。5.83 的 `keel mail` 命令继续可用,消息存在私聊群里。
184
+
173
185
  ## 命令参考
174
186
 
175
187
  ```bash
@@ -190,6 +202,15 @@ keel guard clear --json
190
202
  keel project tasks --target claude [--change <c>] [--json]
191
203
  keel project --target codex --event compaction --json
192
204
 
205
+ # 会话之间的群聊(接 Slack 见 docs/chat-slack-setup.zh-CN.md)
206
+ keel chat role --set <角色> [--alias <简写>]
207
+ keel chat group create <群> [--member <角色>]... | add | remove | archive | list
208
+ keel chat <群> [<消息>] [--since 2h] [--follow] # 查看,或发言
209
+ keel chat dm <角色> <消息> | todo <群> --assignee <角色> <内容> | todos [--mine]
210
+ keel chat unread | read | notice | search <文本>
211
+ keel chat bridge add | install | status | pause <2h> | stop | start | uninstall
212
+ keel chat archive sync | pull
213
+
193
214
  # 安装 / 维护
194
215
  keel --init | --install | --check | --doctor | --uninstall [--target <t>] [--dry-run]
195
216
  keel --update [--dry-run]
@@ -1,4 +1,4 @@
1
- <!-- keel:start version=5.84.0 -->
1
+ <!-- keel:start version=5.85.0 -->
2
2
  ## Keel Bootstrap
3
3
 
4
4
  - Start every session with `keel context`; OpenSpec artifacts and Git are the only durable authority — never native memory, goals, or transcripts.
package/bin/keel.js CHANGED
@@ -102,6 +102,7 @@ Usage:
102
102
  keel gate change-close [repo] [--change name] --action sync|archive [--base git-ref] [--json]
103
103
  keel guard start|status|clear [repo] [--change name] [--task id] [--force] [--json]
104
104
  keel lenses list|add [name] [repo] [--force]
105
+ keel chat role|group|post|dm|unread|read|show|<group> ... [--repo path] (group chat between sessions; see keel chat help)
105
106
  keel mail role|send|list|read|hook [repo] ... (cross-host mailbox; see keel mail help)
106
107
  keel triage [repo] [--labels <l1,l2>] [--issue <n>] [--json]
107
108
  keel openspec [args...]
@@ -2596,6 +2597,10 @@ function main() {
2596
2597
  if (process.argv[2] === "mail") {
2597
2598
  return require("../src/core/mail").runMail(process.argv.slice(3));
2598
2599
  }
2600
+ // `keel chat` likewise: the group chat between sessions (#187).
2601
+ if (process.argv[2] === "chat") {
2602
+ return require("../src/core/chat/cli").runChat(process.argv.slice(3));
2603
+ }
2599
2604
  const options = parseArgs(process.argv.slice(2));
2600
2605
  if (options.help || (!options.action && !options.version)) {
2601
2606
  printHelp();
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@christang/keel",
3
- "version": "5.84.0",
3
+ "version": "5.85.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@christang/keel",
9
- "version": "5.84.0",
9
+ "version": "5.85.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@fission-ai/openspec": "^1.4.1"
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@christang/keel",
3
3
  "displayName": "Keel",
4
4
  "description": "Keel OpenSpec execution discipline CLI for Claude Code, Codex, and OpenCode.",
5
- "version": "5.84.0",
5
+ "version": "5.85.0",
6
6
  "license": "MIT",
7
7
  "repository": {
8
8
  "type": "git",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.84.0",
3
+ "version": "5.85.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "keel",
3
- "version": "5.84.0",
3
+ "version": "5.85.0",
4
4
  "description": "Keel OpenSpec execution discipline: stateless continuity, task capsules, deterministic gates, and expectation alignment for Codex and Claude Code.",
5
5
  "author": {
6
6
  "name": "TanglmChris",
@@ -15,6 +15,7 @@
15
15
  "discipline"
16
16
  ],
17
17
  "skills": "./skills/",
18
+ "hooks": "./hooks/codex.json",
18
19
  "agents": "./agents/",
19
20
  "interface": {
20
21
  "displayName": "Keel",
@@ -0,0 +1,44 @@
1
+ {
2
+ "description": "Codex lifecycle hooks. Review their current definitions in /hooks before use; mailbox notices never consume messages or grant authority.",
3
+ "hooks": {
4
+ "SessionStart": [
5
+ {
6
+ "hooks": [
7
+ {
8
+ "type": "command",
9
+ "command": "node \"${PLUGIN_ROOT}/scripts/session-start.js\"",
10
+ "timeout": 15
11
+ },
12
+ {
13
+ "type": "command",
14
+ "command": "node \"${PLUGIN_ROOT}/scripts/codex-mail-hook.js\" session-start",
15
+ "timeout": 10
16
+ }
17
+ ]
18
+ }
19
+ ],
20
+ "PreToolUse": [
21
+ {
22
+ "matcher": "Edit|Write|NotebookEdit",
23
+ "hooks": [
24
+ {
25
+ "type": "command",
26
+ "command": "node \"${PLUGIN_ROOT}/scripts/pretooluse-guard.js\"",
27
+ "timeout": 10
28
+ }
29
+ ]
30
+ }
31
+ ],
32
+ "UserPromptSubmit": [
33
+ {
34
+ "hooks": [
35
+ {
36
+ "type": "command",
37
+ "command": "node \"${PLUGIN_ROOT}/scripts/codex-mail-hook.js\" user-prompt-submit",
38
+ "timeout": 10
39
+ }
40
+ ]
41
+ }
42
+ ]
43
+ }
44
+ }
@@ -0,0 +1,75 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ // Codex's receiving adapter (#183). Use the existing compatibility notice
5
+ // provider, then emit only Codex's documented additionalContext contract.
6
+ // Neither read nor Claude's watchPaths/exit-2 wake signal belongs here.
7
+ const fs = require("fs");
8
+ const path = require("path");
9
+ const { spawnSync } = require("child_process");
10
+
11
+ const EVENTS = {
12
+ "session-start": "SessionStart",
13
+ "user-prompt-submit": "UserPromptSubmit",
14
+ };
15
+ const configuredTimeout = Number(process.env.KEEL_HOOK_TIMEOUT_MS);
16
+ const timeout = Number.isFinite(configuredTimeout) && configuredTimeout > 0
17
+ ? Math.min(configuredTimeout, 8000) : 8000;
18
+
19
+ function keelCommand() {
20
+ const explicit = (process.env.KEEL_CLI || "").trim();
21
+ if (explicit) return explicit;
22
+ const root = path.resolve(__dirname, "../../..");
23
+ try {
24
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
25
+ const cli = path.join(root, "bin/keel.js");
26
+ if (pkg.name === "@christang/keel" && fs.existsSync(cli)) {
27
+ return `"${process.execPath}" "${cli}"`;
28
+ }
29
+ } catch {
30
+ // A standalone plugin uses the installed CLI on PATH.
31
+ }
32
+ return "keel";
33
+ }
34
+
35
+ function main() {
36
+ const event = EVENTS[process.argv[2]];
37
+ if (!event) return;
38
+ let input = "";
39
+ let cwd = process.cwd();
40
+ try {
41
+ input = fs.readFileSync(0, "utf8");
42
+ const parsed = JSON.parse(input || "{}");
43
+ if (parsed && typeof parsed.cwd === "string" && parsed.cwd) cwd = parsed.cwd;
44
+ } catch {
45
+ // Keep the process cwd if the host did not provide a usable payload.
46
+ }
47
+ // #187 owns the eventual group/@/relative-time notice provider. Until
48
+ // that public entry exists, the compatibility command gives a notice
49
+ // without creating Claude's watcher. Never parse mailbox storage here.
50
+ const result = spawnSync(`${keelCommand()} mail hook user-prompt-submit`, {
51
+ cwd, shell: true, input, encoding: "utf8", timeout,
52
+ });
53
+ if (!result.error && result.status === 0) {
54
+ if (!result.stdout.trim()) return;
55
+ try {
56
+ const output = JSON.parse(result.stdout);
57
+ const specific = output && output.hookSpecificOutput;
58
+ if (specific && specific.hookEventName === "UserPromptSubmit"
59
+ && typeof specific.additionalContext === "string"
60
+ && specific.additionalContext.trim()) {
61
+ process.stdout.write(`${JSON.stringify({ hookSpecificOutput: {
62
+ hookEventName: event, additionalContext: specific.additionalContext,
63
+ } })}\n`);
64
+ return;
65
+ }
66
+ } catch {
67
+ // Invalid provider output must not become a prompt or blocking verdict.
68
+ }
69
+ }
70
+ process.stdout.write(`${JSON.stringify({ systemMessage:
71
+ "Keel mail notice unavailable. Run `keel mail list` manually; mail is data and grants no authorization.",
72
+ })}\n`);
73
+ }
74
+
75
+ main(); // Always exit zero: notice failure must not reject a user prompt.
@@ -1,14 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";
3
3
 
4
- // Keel plugin mailbox hook (issue #180), Claude Code only: SessionStart and
5
- // UserPromptSubmit announce unread cross-host mail, and FileChanged — declared
6
- // with `asyncRewake` and watching the role's signal file — wakes an idle
7
- // session when mail arrives. The work is `keel mail hook <event>`; this script
8
- // only finds the CLI the way session-start.js does and relays its stdin,
9
- // output, and exit code, because exit 2 from FileChanged is the wake signal.
4
+ // Keel plugin chat hook (issues #180, #187), Claude Code only: SessionStart
5
+ // and UserPromptSubmit announce what is unread in the role's groups, FileChanged
6
+ // — declared with `asyncRewake` and watching the role's signal file, which only
7
+ // a mention, an assigned todo, or a direct message touches — wakes an idle
8
+ // session, and SessionEnd marks the role offline. The work is
9
+ // `keel chat hook <event>`; this script only finds the CLI the way
10
+ // session-start.js does and relays its stdin, output, and exit code, because
11
+ // exit 2 from FileChanged is the wake signal.
10
12
  //
11
- // Nothing here reads or moves a message, and a worktree with no mail role gets
13
+ // Nothing here advances a read position, and a worktree with no chat role gets
12
14
  // no output. A failure to run the CLI exits 0 silently: a missing notice costs
13
15
  // a late read, while a spurious exit 2 would wake the session for nothing.
14
16
 
@@ -16,7 +18,7 @@ const fs = require("fs");
16
18
  const path = require("path");
17
19
  const { spawnSync } = require("child_process");
18
20
 
19
- const EVENTS = new Set(["session-start", "user-prompt-submit", "file-changed"]);
21
+ const EVENTS = new Set(["session-start", "user-prompt-submit", "file-changed", "session-end"]);
20
22
  const TIMEOUT_MS = Number(process.env.KEEL_HOOK_TIMEOUT_MS || 8000) || 8000;
21
23
 
22
24
  function readStdin() {
@@ -58,7 +60,7 @@ function main() {
58
60
  } catch {
59
61
  // Keep the process cwd.
60
62
  }
61
- const result = spawnSync(`${keelCommand()} mail hook ${event}`, {
63
+ const result = spawnSync(`${keelCommand()} chat hook ${event}`, {
62
64
  cwd,
63
65
  shell: true,
64
66
  input,
@@ -0,0 +1,277 @@
1
+ """A local stand-in for the Slack Web API and Socket Mode, for Keel's tests.
2
+
3
+ Issue #187: `keel chat bridge` talks to Slack. Its validation scenarios run
4
+ against this server instead, so they need no workspace, no token, and no
5
+ network — the mock sits at the system boundary, and Keel's own modules run
6
+ for real. It models only what the bridge uses, with the shapes Slack's public
7
+ documentation gives (design A2): a real run is the evidence that Slack agrees.
8
+
9
+ Web API: `POST /api/<method>` with a JSON or form body answers `ok: true` and
10
+ records the call. `chat.postMessage` assigns increasing `ts` values and keeps
11
+ the message, with its metadata, for `conversations.history`.
12
+ `apps.connections.open` returns a `ws://` URL served by the same process.
13
+
14
+ Socket Mode: the server speaks just enough RFC 6455 to push envelopes to a
15
+ connected client and collect its acknowledgements.
16
+
17
+ Tests drive the server through methods on `FakeSlack`, not over HTTP.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import base64
23
+ import hashlib
24
+ import json
25
+ import socket
26
+ import struct
27
+ import threading
28
+ import time
29
+ import urllib.parse
30
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
31
+
32
+ WS_MAGIC = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
33
+
34
+
35
+ def ws_frame(text: str) -> bytes:
36
+ data = text.encode("utf-8")
37
+ header = bytearray([0x81])
38
+ if len(data) < 126:
39
+ header.append(len(data))
40
+ elif len(data) < 65536:
41
+ header.append(126)
42
+ header += struct.pack(">H", len(data))
43
+ else:
44
+ header.append(127)
45
+ header += struct.pack(">Q", len(data))
46
+ return bytes(header) + data
47
+
48
+
49
+ class FakeSlack:
50
+ def __init__(self) -> None:
51
+ self.calls: list[dict] = []
52
+ self.messages: dict[str, list[dict]] = {}
53
+ self.rate_limit_next: list[tuple[str, int]] = []
54
+ self.lock = threading.Lock()
55
+ # Later than any `ts` a test writes by hand, so what this server assigns
56
+ # always sorts after the events a test pushed itself.
57
+ self.next_ts = 1_900_000_000
58
+ self.sockets: list[socket.socket] = []
59
+ self.acks: list[str] = []
60
+ self.connections_opened = 0
61
+ self.server = ThreadingHTTPServer(("127.0.0.1", 0), self._handler())
62
+ self.port = self.server.server_address[1]
63
+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
64
+
65
+ # --- lifecycle -----------------------------------------------------------
66
+
67
+ def __enter__(self) -> "FakeSlack":
68
+ self.thread.start()
69
+ return self
70
+
71
+ def __exit__(self, *exc: object) -> None:
72
+ self.drop_connections()
73
+ self.server.shutdown()
74
+ self.server.server_close()
75
+
76
+ @property
77
+ def api_base(self) -> str:
78
+ return f"http://127.0.0.1:{self.port}/api"
79
+
80
+ # --- test controls -------------------------------------------------------
81
+
82
+ def rate_limit(self, method: str, retry_after: int) -> None:
83
+ """Answer the next call of `method` with HTTP 429 and Retry-After."""
84
+ with self.lock:
85
+ self.rate_limit_next.append((method, retry_after))
86
+
87
+ def calls_to(self, method: str) -> list[dict]:
88
+ with self.lock:
89
+ return [call for call in self.calls if call["method"] == method and not call.get("rate_limited")]
90
+
91
+ def add_history(self, channel: str, message: dict) -> dict:
92
+ """A message Slack holds that the bridge has not been told about."""
93
+ with self.lock:
94
+ stored = {"ts": self._ts(), "type": "message", **message}
95
+ self.messages.setdefault(channel, []).append(stored)
96
+ return stored
97
+
98
+ def push(self, payload: dict, kind: str = "events_api") -> str:
99
+ """Send one Socket Mode envelope to every connected client."""
100
+ with self.lock:
101
+ envelope_id = f"env-{self._ts()}"
102
+ self._broadcast(json.dumps({"envelope_id": envelope_id, "type": kind, "payload": payload, "accepts_response_payload": False}))
103
+ return envelope_id
104
+
105
+ def push_raw(self, message: dict) -> None:
106
+ self._broadcast(json.dumps(message))
107
+
108
+ def drop_connections(self) -> None:
109
+ for sock in list(self.sockets):
110
+ try:
111
+ sock.shutdown(socket.SHUT_RDWR)
112
+ except OSError:
113
+ pass
114
+ try:
115
+ sock.close()
116
+ except OSError:
117
+ pass
118
+ self.sockets.clear()
119
+
120
+ @staticmethod
121
+ def wait_for(predicate, timeout: float = 10.0) -> bool:
122
+ deadline = time.time() + timeout
123
+ while time.time() < deadline:
124
+ if predicate():
125
+ return True
126
+ time.sleep(0.05)
127
+ return bool(predicate())
128
+
129
+ # --- internals -----------------------------------------------------------
130
+
131
+ def _ts(self) -> str:
132
+ self.next_ts += 1
133
+ return f"{self.next_ts}.000100"
134
+
135
+ def _broadcast(self, text: str) -> None:
136
+ frame = ws_frame(text)
137
+ for sock in list(self.sockets):
138
+ try:
139
+ sock.sendall(frame)
140
+ except OSError:
141
+ pass
142
+
143
+ def _answer(self, method: str, params: dict) -> tuple[int, dict, dict]:
144
+ with self.lock:
145
+ for index, (limited, retry_after) in enumerate(self.rate_limit_next):
146
+ if limited == method:
147
+ del self.rate_limit_next[index]
148
+ self.calls.append({"method": method, "params": params, "rate_limited": True, "at": time.time()})
149
+ return 429, {"Retry-After": str(retry_after)}, {"ok": False, "error": "ratelimited"}
150
+ self.calls.append({"method": method, "params": params, "at": time.time()})
151
+ if method == "auth.test":
152
+ return 200, {}, {"ok": True, "user_id": "UBOT", "bot_id": "BBOT", "team_id": "T1"}
153
+ if method == "apps.connections.open":
154
+ self.connections_opened += 1
155
+ return 200, {}, {"ok": True, "url": f"ws://127.0.0.1:{self.port}/socket"}
156
+ if method == "chat.postMessage":
157
+ metadata = params.get("metadata")
158
+ if isinstance(metadata, str):
159
+ metadata = json.loads(metadata)
160
+ message = {
161
+ "ts": self._ts(),
162
+ "type": "message",
163
+ "text": params.get("text", ""),
164
+ "username": params.get("username"),
165
+ "bot_id": "BBOT",
166
+ "metadata": metadata,
167
+ }
168
+ if params.get("thread_ts"):
169
+ message["thread_ts"] = params["thread_ts"]
170
+ self.messages.setdefault(params.get("channel", ""), []).append(message)
171
+ return 200, {}, {"ok": True, "channel": params.get("channel"), "ts": message["ts"], "message": message}
172
+ if method in ("conversations.history", "conversations.replies"):
173
+ channel = params.get("channel", "")
174
+ oldest = float(params.get("oldest") or 0)
175
+ found = [m for m in self.messages.get(channel, []) if float(m["ts"]) > oldest]
176
+ if method == "conversations.replies":
177
+ root = params.get("ts")
178
+ found = [m for m in self.messages.get(channel, []) if m.get("thread_ts") == root or m["ts"] == root]
179
+ if params.get("latest"):
180
+ latest = float(params["latest"])
181
+ inclusive = str(params.get("inclusive", "")).lower() in ("1", "true")
182
+ found = [m for m in found if float(m["ts"]) < latest or (inclusive and float(m["ts"]) == latest)]
183
+ include = str(params.get("include_all_metadata", "")).lower() in ("1", "true")
184
+ shown = [m if include else {k: v for k, v in m.items() if k != "metadata"} for m in found]
185
+ return 200, {}, {"ok": True, "messages": list(reversed(shown)), "has_more": False}
186
+ return 200, {}, {"ok": True}
187
+
188
+ def _handler(self):
189
+ fake = self
190
+
191
+ class Handler(BaseHTTPRequestHandler):
192
+ protocol_version = "HTTP/1.1"
193
+
194
+ def log_message(self, *args: object) -> None:
195
+ return
196
+
197
+ def do_GET(self) -> None: # noqa: N802 - http.server API
198
+ if self.path.startswith("/socket"):
199
+ self._upgrade()
200
+ return
201
+ query = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
202
+ self._api({k: v[0] for k, v in query.items()})
203
+
204
+ def do_POST(self) -> None: # noqa: N802 - http.server API
205
+ length = int(self.headers.get("Content-Length") or 0)
206
+ raw = self.rfile.read(length).decode("utf-8")
207
+ if "json" in (self.headers.get("Content-Type") or ""):
208
+ params = json.loads(raw or "{}")
209
+ else:
210
+ params = {k: v[0] for k, v in urllib.parse.parse_qs(raw).items()}
211
+ self._api(params)
212
+
213
+ def _api(self, params: dict) -> None:
214
+ method = urllib.parse.urlparse(self.path).path.rsplit("/", 1)[-1]
215
+ params["_auth"] = self.headers.get("Authorization", "")
216
+ status, headers, body = fake._answer(method, params)
217
+ data = json.dumps(body).encode("utf-8")
218
+ self.send_response(status)
219
+ self.send_header("Content-Type", "application/json")
220
+ self.send_header("Content-Length", str(len(data)))
221
+ for key, value in headers.items():
222
+ self.send_header(key, value)
223
+ self.end_headers()
224
+ self.wfile.write(data)
225
+
226
+ def _upgrade(self) -> None:
227
+ key = self.headers.get("Sec-WebSocket-Key", "")
228
+ accept = base64.b64encode(hashlib.sha1((key + WS_MAGIC).encode()).digest()).decode()
229
+ self.send_response(101, "Switching Protocols")
230
+ self.send_header("Upgrade", "websocket")
231
+ self.send_header("Connection", "Upgrade")
232
+ self.send_header("Sec-WebSocket-Accept", accept)
233
+ self.end_headers()
234
+ self.wfile.flush()
235
+ sock = self.connection
236
+ try:
237
+ sock.sendall(ws_frame(json.dumps({"type": "hello", "num_connections": len(fake.sockets) + 1})))
238
+ except OSError:
239
+ return
240
+ fake.sockets.append(sock)
241
+ self.close_connection = True
242
+ self._read_frames(sock)
243
+
244
+ def _read_frames(self, sock: socket.socket) -> None:
245
+ stream = self.rfile
246
+ while True:
247
+ try:
248
+ head = stream.read(2)
249
+ if not head or len(head) < 2:
250
+ break
251
+ opcode = head[0] & 0x0F
252
+ length = head[1] & 0x7F
253
+ if length == 126:
254
+ length = struct.unpack(">H", stream.read(2))[0]
255
+ elif length == 127:
256
+ length = struct.unpack(">Q", stream.read(8))[0]
257
+ mask = stream.read(4) if head[1] & 0x80 else b"\0\0\0\0"
258
+ data = bytearray(stream.read(length))
259
+ except (OSError, ValueError, struct.error):
260
+ break
261
+ for index in range(len(data)):
262
+ data[index] ^= mask[index % 4]
263
+ if opcode == 0x8:
264
+ break
265
+ if opcode != 0x1:
266
+ continue
267
+ try:
268
+ message = json.loads(data.decode("utf-8"))
269
+ except (UnicodeDecodeError, json.JSONDecodeError):
270
+ continue
271
+ if isinstance(message, dict) and message.get("envelope_id"):
272
+ with fake.lock:
273
+ fake.acks.append(message["envelope_id"])
274
+ if sock in fake.sockets:
275
+ fake.sockets.remove(sock)
276
+
277
+ return Handler