wezard 3.0.1 → 3.0.2
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/CLAUDE.md +14 -11
- package/README.md +2 -2
- package/cli/wezard.sh +56 -20
- package/config.example.jsonc +3 -0
- package/dist/cli/audit.js +11 -13
- package/dist/cli/audit.js.map +1 -1
- package/dist/cli/codex-hook.js +20 -17
- package/dist/cli/codex-hook.js.map +1 -1
- package/dist/cli/ext.js +271 -0
- package/dist/cli/ext.js.map +1 -0
- package/dist/cli/init.js +9 -13
- package/dist/cli/init.js.map +1 -1
- package/dist/cli/sync.js +3 -2
- package/dist/cli/sync.js.map +1 -1
- package/dist/cli/wx.js +7 -6
- package/dist/cli/wx.js.map +1 -1
- package/dist/daemon/aibot-media.js +28 -20
- package/dist/daemon/aibot-media.js.map +1 -1
- package/dist/daemon/approval.js +60 -37
- package/dist/daemon/approval.js.map +1 -1
- package/dist/daemon/channel-onboarding.js +61 -0
- package/dist/daemon/channel-onboarding.js.map +1 -0
- package/dist/daemon/channel-posts.js +56 -16
- package/dist/daemon/channel-posts.js.map +1 -1
- package/dist/daemon/channel-rebind.js +100 -0
- package/dist/daemon/channel-rebind.js.map +1 -0
- package/dist/daemon/channel-store.js.map +1 -1
- package/dist/daemon/channel.js +218 -466
- package/dist/daemon/channel.js.map +1 -1
- package/dist/daemon/claim.js +1 -45
- package/dist/daemon/claim.js.map +1 -1
- package/dist/daemon/classes.js +11 -13
- package/dist/daemon/classes.js.map +1 -1
- package/dist/daemon/config-api.js +5 -29
- package/dist/daemon/config-api.js.map +1 -1
- package/dist/daemon/control-socket.js +93 -0
- package/dist/daemon/control-socket.js.map +1 -0
- package/dist/daemon/danger-scrub.js +315 -0
- package/dist/daemon/danger-scrub.js.map +1 -0
- package/dist/daemon/danger.js +146 -16
- package/dist/daemon/danger.js.map +1 -1
- package/dist/daemon/detail.js +37 -15
- package/dist/daemon/detail.js.map +1 -1
- package/dist/daemon/exec-surface.js +108 -0
- package/dist/daemon/exec-surface.js.map +1 -0
- package/dist/daemon/external.js +595 -0
- package/dist/daemon/external.js.map +1 -0
- package/dist/daemon/http.js +97 -16
- package/dist/daemon/http.js.map +1 -1
- package/dist/daemon/inbound.js +91 -80
- package/dist/daemon/inbound.js.map +1 -1
- package/dist/daemon/index.js +1268 -171
- package/dist/daemon/index.js.map +1 -1
- package/dist/daemon/last-response.js +8 -17
- package/dist/daemon/last-response.js.map +1 -1
- package/dist/daemon/legacy-panes.js +67 -0
- package/dist/daemon/legacy-panes.js.map +1 -0
- package/dist/daemon/mcp-http.js.map +1 -1
- package/dist/daemon/me-room.js +137 -0
- package/dist/daemon/me-room.js.map +1 -0
- package/dist/daemon/media.js +14 -0
- package/dist/daemon/media.js.map +1 -1
- package/dist/daemon/message-format.js +5 -0
- package/dist/daemon/message-format.js.map +1 -1
- package/dist/daemon/mirror-bridge.js +77 -26
- package/dist/daemon/mirror-bridge.js.map +1 -1
- package/dist/daemon/notices.js +4 -5
- package/dist/daemon/notices.js.map +1 -1
- package/dist/daemon/onboarding.js +120 -45
- package/dist/daemon/onboarding.js.map +1 -1
- package/dist/daemon/peers.js +2 -2
- package/dist/daemon/peers.js.map +1 -1
- package/dist/daemon/plan-http.js +2 -3
- package/dist/daemon/plan-http.js.map +1 -1
- package/dist/daemon/reach.js +1 -5
- package/dist/daemon/reach.js.map +1 -1
- package/dist/daemon/room-bind.js +297 -0
- package/dist/daemon/room-bind.js.map +1 -0
- package/dist/daemon/room-facts.js +1 -1
- package/dist/daemon/room-facts.js.map +1 -1
- package/dist/daemon/room-hub.js +158 -19
- package/dist/daemon/room-hub.js.map +1 -1
- package/dist/daemon/room-overdue.js +90 -28
- package/dist/daemon/room-overdue.js.map +1 -1
- package/dist/daemon/room-watchdog.js +44 -22
- package/dist/daemon/room-watchdog.js.map +1 -1
- package/dist/daemon/rooms.js +101 -4
- package/dist/daemon/rooms.js.map +1 -1
- package/dist/daemon/session-scan.js +1 -1
- package/dist/daemon/session-scan.js.map +1 -1
- package/dist/daemon/short-id-log.js +43 -0
- package/dist/daemon/short-id-log.js.map +1 -0
- package/dist/daemon/spawn-tmux.js +12 -9
- package/dist/daemon/spawn-tmux.js.map +1 -1
- package/dist/daemon/steward-guard.js +1 -1
- package/dist/daemon/steward-guard.js.map +1 -1
- package/dist/daemon/steward-model.js +17 -3
- package/dist/daemon/steward-model.js.map +1 -1
- package/dist/daemon/steward-repair.js +171 -0
- package/dist/daemon/steward-repair.js.map +1 -0
- package/dist/daemon/steward.js +48 -9
- package/dist/daemon/steward.js.map +1 -1
- package/dist/daemon/tool-face.js +31 -0
- package/dist/daemon/tool-face.js.map +1 -0
- package/dist/daemon/turn-opening.js +8 -3
- package/dist/daemon/turn-opening.js.map +1 -1
- package/dist/daemon/wizard-memory.js +4 -10
- package/dist/daemon/wizard-memory.js.map +1 -1
- package/dist/daemon/wizard.js +153 -73
- package/dist/daemon/wizard.js.map +1 -1
- package/dist/daemon/ws.js +1 -1
- package/dist/daemon/ws.js.map +1 -1
- package/dist/mcp/output.js +27 -5
- package/dist/mcp/output.js.map +1 -1
- package/dist/mcp/relay.js +152 -0
- package/dist/mcp/relay.js.map +1 -0
- package/dist/mcp/tools.js +87 -39
- package/dist/mcp/tools.js.map +1 -1
- package/dist/shared/chat-http.js +65 -48
- package/dist/shared/chat-http.js.map +1 -1
- package/dist/shared/cli-local-status.js +28 -0
- package/dist/shared/cli-local-status.js.map +1 -0
- package/dist/shared/cli-socket.js +14 -0
- package/dist/shared/cli-socket.js.map +1 -0
- package/dist/shared/codex-hooks.js +5 -2
- package/dist/shared/codex-hooks.js.map +1 -1
- package/dist/shared/config.js +45 -45
- package/dist/shared/config.js.map +1 -1
- package/dist/shared/daemon-addr.js +23 -0
- package/dist/shared/daemon-addr.js.map +1 -0
- package/dist/shared/daemon-client.js +41 -0
- package/dist/shared/daemon-client.js.map +1 -0
- package/dist/shared/daemon-token.js +2 -2
- package/dist/shared/daemon-token.js.map +1 -1
- package/dist/shared/external.js +402 -0
- package/dist/shared/external.js.map +1 -0
- package/dist/shared/inject-view.js +48 -10
- package/dist/shared/inject-view.js.map +1 -1
- package/dist/shared/instance-id.js +21 -0
- package/dist/shared/instance-id.js.map +1 -0
- package/dist/shared/message-footer.js +8 -1
- package/dist/shared/message-footer.js.map +1 -1
- package/dist/shared/model-tiers.js +39 -1
- package/dist/shared/model-tiers.js.map +1 -1
- package/dist/shared/ports.js +56 -0
- package/dist/shared/ports.js.map +1 -0
- package/dist/shared/pricing.js +0 -5
- package/dist/shared/pricing.js.map +1 -1
- package/dist/shared/role-render.js +8 -7
- package/dist/shared/role-render.js.map +1 -1
- package/dist/shared/role-view.js +5 -2
- package/dist/shared/role-view.js.map +1 -1
- package/dist/shared/room-overdue.js +84 -12
- package/dist/shared/room-overdue.js.map +1 -1
- package/dist/shared/room-view.js +18 -4
- package/dist/shared/room-view.js.map +1 -1
- package/dist/shared/room.js +245 -28
- package/dist/shared/room.js.map +1 -1
- package/dist/shared/session-label.js +29 -51
- package/dist/shared/session-label.js.map +1 -1
- package/dist/shared/session-mcp.js +35 -57
- package/dist/shared/session-mcp.js.map +1 -1
- package/dist/shared/smarts.js +15 -30
- package/dist/shared/smarts.js.map +1 -1
- package/dist/shared/world.js +1 -1
- package/dist/shared/world.js.map +1 -1
- package/dist/svr/facts-store.js.map +1 -1
- package/dist/svr/index.js +57 -15
- package/dist/svr/index.js.map +1 -1
- package/hooks/pre-tool-use.sh +14 -10
- package/hooks/stop.sh +5 -3
- package/launchd/com.wezard.svr.plist.template +2 -0
- package/package.json +3 -1
- package/scripts/install.sh +12 -0
- package/systemd/wezard-svr.service.template +2 -0
- package/web/chat.js +81 -40
- package/dist/daemon/bot-mux.js +0 -161
- package/dist/daemon/bot-mux.js.map +0 -1
package/CLAUDE.md
CHANGED
|
@@ -7,7 +7,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|
|
7
7
|
`wezard` (CLI `wezard`) bridges agent CLIs (Claude Code / claude-internal / CodeBuddy) and WeCom (企业微信) smart bots:
|
|
8
8
|
- **PreToolUse approval forwarding**: every tool call is gated by a button card pushed to WeCom; clicking ✅/❌/⏱ resolves the long-poll the hook is parked on.
|
|
9
9
|
- **Remote control**: messages sent to the bot drive a local agent CLI — the daemon spawns an interactive session in tmux and mirrors it to the chat. Sessions are opened from the chat side (first inbound, `/new`, `.name`, `switch_claude_session`) or by a wizard (`spawn_wizard` / `clone_wizard` / `delegate`).
|
|
10
|
-
- **MCP server** (`wezard`): the wizard's whole tool surface, each tool one thin POST to the resident daemon over
|
|
10
|
+
- **MCP server** (`wezard`): the wizard's whole tool surface, each tool one thin POST to the resident daemon over its unix socket — rooms (`chat_ask` / `chat_reply` / `chat_say` / `room_*`: the only way wizards talk), delegation (`delegate`, `route_candidates`), spawn / clone / stop (`spawn_wizard`, `clone_wizard`, `stop_wizard`), awareness (`wizard_roster`, `peek_peer`, `pending_items`, `wizard_whoami`), identity and memory (`wizard_identity`, `wizard_remember`), owner-managed plans (`plan_*`), schedules (`schedule_task` / `list_tasks` / `cancel_task`), `handoff`, workspace/model switching, `notify` / `send_file`, config (`config_get` / `config_set`). Human-facing outbound cards (approval / AskUserQuestion) are pushed by the daemon itself, not through MCP.
|
|
11
11
|
|
|
12
12
|
## Build / run
|
|
13
13
|
|
|
@@ -24,7 +24,7 @@ Local dev loop:
|
|
|
24
24
|
```bash
|
|
25
25
|
npm run build && ./cli/wezard.sh reload # rebuild, then bounce the resident daemon
|
|
26
26
|
./cli/wezard.sh logs -f # tail ~/.wezard/daemon.log
|
|
27
|
-
./cli/wezard.sh status #
|
|
27
|
+
./cli/wezard.sh status # GET /status over the control socket — wsConnected, pending count, sourcePath, socket
|
|
28
28
|
```
|
|
29
29
|
|
|
30
30
|
When the user says **"reload"** in this repo, it means exactly: `npm run build && ./cli/wezard.sh reload`. The global `wezard` binary may not be on `$PATH` in dev shells — always invoke `./cli/wezard.sh` from the repo root. After a development unit, build once, reload the daemon, then restart the existing svr service with `launchctl kickstart -k "gui/$(id -u)/com.wezard.svr"` on macOS or `systemctl --user restart wezard-svr.service` on Linux. Operational-only requests keep their requested scope; daemon reload does not restart svr.
|
|
@@ -57,18 +57,21 @@ Every version bump **must** update `CHANGELOG.md` — no release without a chang
|
|
|
57
57
|
|
|
58
58
|
## High-level architecture
|
|
59
59
|
|
|
60
|
-
Three processes, all coordinating via
|
|
60
|
+
Three processes, all coordinating via the daemon's unix control socket (`<stateDir>/run/daemon.sock`) and `~/.wezard/`:
|
|
61
61
|
|
|
62
62
|
```
|
|
63
63
|
WeCom ── WS ──► daemon (resident, launchd/systemd --user)
|
|
64
64
|
│
|
|
65
|
-
├──
|
|
66
|
-
├──
|
|
65
|
+
├── unix socket ───────► hook (pre-tool-use.sh, blocking long-poll)
|
|
66
|
+
├── unix socket ───────► MCP relay (stdio child of claude, mcp/relay.ts)
|
|
67
|
+
├── TCP view port ─────► browser (read-only: rolepage / detail / healthz; everything else 410)
|
|
67
68
|
└── tmux pane running the agent CLI ── mirror bridge (tail jsonl + tmux paste)
|
|
68
69
|
```
|
|
69
70
|
|
|
70
71
|
**daemon** (`daemon/`) is the only process that holds the WeCom WSClient. Everything else is a thin HTTP client of it.
|
|
71
72
|
- `index.ts` wires modules; route handlers are registered onto the http server returned by `startHttp`.
|
|
73
|
+
- **Control plane = unix domain socket** (`daemon/http.ts` + `daemon/control-socket.ts`; path from `shared/daemon-addr.ts`, the only place that derives it: env `WEZARD_DAEMON_SOCK` → `daemon.socket` → `<stateDir>/run/daemon.sock`, ≤103 bytes). The socket's directory is checked (must be a real dir, not a symlink, owned by us) and forced to 0700, the socket itself to 0600 right after `listen`; a live listener is never overwritten (exit 1 — systemd/launchd retry until the other exits), a stale one is unlinked, a non-socket file is left alone, and exit only unlinks our own inode. This is what keeps other uids on the box out and makes the daemon impossible to impersonate in a restart gap — a loopback TCP port did neither. Every route (including `/mcp` and the guarded ones) lives on the socket; the daemon token (`x-wezard-token`) stays for the same-uid case (a model `curl --unix-socket`-ing around an approval card). `daemon.host` / `daemon.port` are now only the **browser view listener**: it mounts nothing but `chatRouteTable` keys + `GET /detail` + `GET /healthz`, every other route answers 410 (`POST /mcp` a JSON-RPC error by request id, so an old http MCP client sees why), a taken port is retried upward (`daemon.portSpan`, `shared/ports.ts`) and the **actual** port goes to `<stateDir>/run/ports.json` — links follow it, never the configured port (no base + no view = no link, not a `:0` dead link); any other listen failure only warns (`view listener disabled`), `daemon.port: 0` turns it off. The svr does the same (`svr.portSpan`, its own `run/ports.json`) but exits 78 when every port is taken (unit has `RestartPreventExitStatus=78`). Residual risk: a squatter on the view port can show a browser a fake page and read the `?id=` ticket (read access) — never the control plane; `detailRemoteBase` + `port: 0` closes that too. Clients: `shared/daemon-client.ts` (`daemonRequest`, node:http `socketPath`) for TS, `curl --unix-socket` for hooks / `wezard.sh`. The daemon sets `process.env.WEZARD_DAEMON_SOCK` itself so the in-process MCP calls the same socket. `wezard.sh reload|stop` only send `/shutdown` when the socket is up — never to TCP (that could be another user's old daemon).
|
|
74
|
+
- `legacy-panes.ts`: after the control-plane upgrade a pane whose CLI argv still carries the TCP-era MCP config (`--mcp-config …/session-mcp.json|session-mcp-http.json`, or codex's `mcp_servers.wezard.env.WEZARD_DAEMON_BASE`) can only get 410s from its MCP; on the watchdog cadence an **idle** one (`!isBusy`) is `sleepPane`d (binding and identity kept, the next injection `--resume`s it on the new launch line), a busy one waits for the next beat, and a pane with no such trace in argv is never touched. Hooks need no recycling — they read the script from disk on every call.
|
|
72
75
|
- `ws.ts` owns the `@wecom/aibot-node-sdk` `WSClient`. Fatal auth/reconnect → `process.exit(1)` (launchd respawns).
|
|
73
76
|
- `approval.ts` builds the button card, parks an HTTP request via `pending.ts`, and resolves it on `event.template_card_event`. Three click outcomes: `allow` / `allow_window` (auto-allow N min for that session) / `deny`. `session-cache.ts` short-circuits repeats.
|
|
74
77
|
- `inbound.ts` routes `message.text` / `message.image` / `message.mixed` → `mirror-bridge.ts`. Gates on `allowFrom`; one-shot exception is the bootstrap claim (see below).
|
|
@@ -78,7 +81,7 @@ Three processes, all coordinating via 127.0.0.1:17890 and `~/.wezard/`:
|
|
|
78
81
|
- `wizard.ts` is the identity layer over those sessions: a target key plus a **globally unique name** — the wizard's only address, written `.name` everywhere a human or model sees it (a chat's default session takes the chat's name, a slot takes its slot id; collisions get `-N` via `pickName`; `settleName` claims lazily, `settleAll` initializes unnamed current identities at boot, default sessions first). The slot id inside the key is NOT the name: a rename never rekeys a session. Plus a one-line responsibility, a long-term `memory` list, and a `parent` link for management ownership. Every collaborative spawn/clone belongs to its caller, including cross-cwd/chat creation and cloning context from another wizard; `forkOf` records a different context source. Horizontal communication does not change parent ownership. Ending an identity is limited to itself or its direct parent; active/paused plans prevent logical retirement, and children must be handled before their parent can be forgotten. Completed work retains wizard identities by default; pane resource eviction keeps identity and binding. The registry is a write-through json (`~/.wezard/wizards.json`, `wrc.mirror.wizardsFile`) bound process-wide via `bindWizardStore` so the IM side can read it too; everything else in the module is a pure renderer. **Identity travels as the first message's preamble, not the system prompt**: `renderCharter` builds the wizard's charter (who it is, its workspace, its clones, its memory, the chat's and the workspace's shared memory (`wizard-memory.ts`: `~/.wezard/memory/{chats,workspaces}/*.md`, human-editable, appended by `wizard_remember({scope})`), the tool roster, the orchestration playbook, how to talk through rooms). `spawn-tmux` only parks it at `charters/<sid>.md` (claude/codebuddy no longer get `--append-system-prompt` — it cost ~1.4s per cold start); the attachment's `charterPending` prepends it as `<system-reminder wezard="charter">` to the pane's first non-slash injection and clears it once that injection is confirmed. It is re-armed on every moment a session has not read it: `/new`, a spare-pool claim, a dead-pane `--resume` respawn (only when the transcript has no charter block since the last `compact_boundary`: `charterInContext`; already owed / unreadable transcript still arm), `/clear` and compaction (`onContextCut` → `armCharter`); a clone's opening line carries the child's charter, superseding the parent's inherited one. Read sides (`stripMeta`, `cleanUserText`, rolepage) strip/collapse the `charter` reminder, so it never becomes a chat ask or a bubble. Codex keeps it in `developer_instructions`. Every spawn path (`/new`, a dead-pane respawn, a clone) pulls it from `MirrorBridge.setCharterProvider`, installed in `index.ts`. Since a running wizard never sees a new charter, `config_set` renders every chartered wizard's charter before and after the change and tells the affected ones (and the caller) to `handoff` — generic over whatever config the charter reads. Backends with no such flag spawn without a charter rather than with a rejected flag.
|
|
79
82
|
- **Cloning is a context fork**: `MirrorBridge.cloneSession` spawns `--resume <parent sid> --fork-session`, so the child starts holding everything the parent had read while the parent is untouched — that is what makes "load the shared material once, then fan out" work. Two invariants: `--fork-session` is mandatory (without it a second pane appends to the parent's jsonl and two chats cross-wire), and the attach waits for the forked transcript (codebuddy 2.167 writes it at process start — a byte copy of the parent plus a `session-meta` row, no API call; older CLIs only on the first message); if it never appears the pane is killed rather than bound to the parent's sid.
|
|
80
83
|
- **Rooms are the only thing wizards talk through** (`shared/room.ts` pure core — row types, fold, `judge`, wake rules, ids; `daemon/rooms.ts` store; `daemon/room-hub.ts` the only append door + wake pump; contract in `docs/room/contract.md`). A WeCom group / DM / channel post is a *bound* room (id = the base principal verbatim); two wizards' conversation is an unbound `dm:<uidA>|<uidB>` room (stable instance uids, never names); 3+ is an `adhoc:<hex>` room opened with `room_open`. A room is one append-only, fsync-per-append jsonl under `<stateDir>/rooms/` (`roomsDirOf` is the single derivation — never `join(…, "rooms")` locally); state is a fold of the rows, a torn tail line is dropped, a corrupt middle line makes that room fail closed (503). Humans (inbound) and wizards (tools) append through the same `judge` (membership, who may write a `status`, dedup, wake targets, budget); a rejected line never becomes a row. **Completion, origin and the right to speak are explicit fields on ledger rows, never inferred from a transcript or a final line**: `chat_ask` opens a *duty* on its `to`; only that holder's `chat_reply` with status `done` / `passed` / `canceled` closes it (`need` / `progress` / `error` don't); `chat_say` / `notify` open nothing. `wakeTargets`: the named, the asker of a `re`, the host for an unaddressed human line in a bound room, and `room_watch` subscribers on human lines / closing replies; host = the earliest-joined wizard member, evaluated on read. A bound room mirrors every `msg` row to WeCom except `origin` inbound/migrate and `trigger` rows (`mirrors()`); dm/adhoc rows live only on the rolepage.
|
|
81
|
-
- **The wake pump keeps no queue** (`room-hub.ts`): who is owed what, and what to show them, is recomputed from the ledger every pass — a row with `wake∋uid` past the member's `seen` cursor is pending. The `seen` row is written only after a confirmed paste; an uncertain paste leaves the cursor and re-delivers the same batch marked "maybe already read", so a reload loses nothing. A target with no session at all (`gone`: its binding was dropped by `stop_wizard` end / `/kill`) is not woken by retrying: each duty it holds in the batch gets one `undelivered` system row to its asker (cursor untouched, so a same-name respawn still reads them); other failures log one warn per state change. A busy live pane waits for its turn to end; `interrupt:true` (direct parent / host / human only, budgeted per room) presses Esc first; a cold wizard is not "busy" — pasting respawns it. A wizard that ends a turn still owing a duty gets one reminder (in-turn via the Stop hook `hooks/stop.sh` for backends that honor `decision:block`, else at turn end), then a system row to the asker. `room-watchdog.ts` writes `canceled` for the duties of a wizard whose pane is truly gone (two confirming scans, never on a failed tmux call). `after` on a `chat_ask` defers the wake until the listed duties are `done`. **Overdue** (`shared/room-overdue.ts` pure, `daemon/room-overdue.ts` scan on the watchdog cadence): an open ask/task/human duty held by a wizard and idle (no non-daemon row touching it) for `rooms.overdue.remindMin` (60) gets a `trigger` row `sys:"overdue-remind"` that wakes the holder; at `groupMin` (120) a non-waking `sys:"overdue-group"` system row lands in the room, and — if the room is unbound — in the holder's (else asker's) home group so a human sees it. A child the holder dispatched also counts as activity: a task/ask row's `for` is its lineage (the msg id of the duty it was dispatched for — defaulted by the daemon, `hub.defaultFor`, to the single duty that woke the caller this turn when `for` is omitted; zero or several → left empty), so the child's own row, any non-daemon row answering it (its `done` closes included) and its descendants' (cross-room, depth ≤ 5) restart the parent's clock. Both hot, 0 = off, ledger-deduped, never auto-`canceled`.
|
|
84
|
+
- **The wake pump keeps no queue** (`room-hub.ts`): who is owed what, and what to show them, is recomputed from the ledger every pass — a row with `wake∋uid` past the member's `seen` cursor is pending. The `seen` row is written only after a confirmed paste; an uncertain paste leaves the cursor and re-delivers the same batch marked "maybe already read", so a reload loses nothing. A target with no session at all (`gone`: its binding was dropped by `stop_wizard` end / `/kill`) is not woken by retrying: each duty it holds in the batch gets one `undelivered` system row to its asker (cursor untouched, so a same-name respawn still reads them); other failures log one warn per state change. A busy live pane waits for its turn to end; `interrupt:true` (direct parent / host / human only, budgeted per room) presses Esc first; a cold wizard is not "busy" — pasting respawns it. A wizard that ends a turn still owing a duty gets one reminder (in-turn via the Stop hook `hooks/stop.sh` for backends that honor `decision:block`, else at turn end), then a system row to the asker. `room-watchdog.ts` writes `canceled` for the duties of a wizard whose pane is truly gone (two confirming scans, never on a failed tmux call). `after` on a `chat_ask` defers the wake until the listed duties are `done`. **Overdue** (`shared/room-overdue.ts` pure, `daemon/room-overdue.ts` scan on the watchdog cadence): an open ask/task/human duty held by a wizard and idle (no non-daemon row touching it) for `rooms.overdue.remindMin` (60) gets a `trigger` row `sys:"overdue-remind"` that wakes the holder; at `groupMin` (120) a non-waking `sys:"overdue-group"` system row lands in the room, and — if the room is unbound — in the holder's (else asker's) home group so a human sees it. A child the holder dispatched also counts as activity: a task/ask row's `for` is its lineage (the msg id of the duty it was dispatched for — defaulted by the daemon, `hub.defaultFor`, to the single duty that woke the caller this turn when `for` is omitted; zero or several → left empty), so the child's own row, any non-daemon row answering it (its `done` closes included) and its descendants' (cross-room, depth ≤ 5) restart the parent's clock. Reminding is **leaf-first**: while a duty still has an open, still-known child duty on its `for` lineage, neither level fires for the parent — the child's holder is the one reminded; once the children close, the closing row restarts the parent's clock and the parent is reminded `remindMin` later (an orphan child whose holder left the roster does not block). And a holder that is **busy** (mid-turn, or parked on an approval card — `MirrorBridge.isBusy`) is skipped for that pass: no row is written, it is judged again once idle. Both hot, 0 = off, ledger-deduped, never auto-`canceled`.
|
|
82
85
|
- **`delegate` / `route_candidates`** (`daemon/route.ts`, the deterministic half of dispatch): candidates are filtered and ordered by evidence (files it read > responsibility > recent asks; same workspace only breaks ties), each with its cost line (cache cold / ctx size → what waking it costs vs. a white-board spawn); `decide` takes the first candidate no veto rejects (weak evidence, busy, not worth it, cold cache with big ctx — `force` crosses only the last) or spawns a white-board wizard at `tierFor`. The product of `delegate` is one `chat_ask`; the caller may override (`to`, `spawn`, `force`, `tier`, `lead`). `lead` is per job: `WizardRecord.leadOf` records the task rows that made it a lead, and the daemon clears `lead` once all of them are closed and it owns no unfinished plan (`leadSettled`, run after every closing row via the hub's `onClosed`, after plan updates, and at boot — where legacy leads without `leadOf` are cleared if no peer-opened duty is still open). In-flight work is the room ledger's open duties (`openDuties` / `dutyFacts` in `shared/room-view.ts`); the old `TurnState` / `WorldFacts.inflight` vocabulary is gone.
|
|
83
86
|
- **Steward hand-brake** (`approval.ts` / `steward-guard.ts`): triggered by role (`isStewardTarget`: the chat's bound steward, else its default session), ahead of every approval path — it may not edit files or open subagents, and caps its own look-commands per turn at `chatPolicy.<chat>.stewardBudget` (reading code — Read/Grep/Glob and read-only shell commands — passes free; the deny reason points at `delegate`). A new group's onboarding guide has no tool surface at all (`onboarding.ts` `guideRefusal`) except `chat_reply` / `chat_say` / `onboard_bind`.
|
|
84
87
|
- **Teams plans** (`shared/plan.ts`, `daemon/plans.ts`, `daemon/plan-http.ts`, `daemon/plan-reminders.ts`): each wizard may own multiple mutable DAG plans. `plan_create/get/list/update` expose explicit owner-managed state; only the owner writes, and `revision` is a compare-and-swap guard. Replacing `tasks` replaces the whole DAG. The store validates dependencies, task/plan states and terminal plans, uses owner-scoped `requestId` creation idempotency, and fsyncs an append-only `wrc.mirror.plansFile` journal (`~/.wezard/plans.jsonl` by default) before publishing changes in memory. Corrupt history or failed IO makes plan operations and retirement checks fail closed with 503 while receiver messaging remains available. The daemon never assigns executors, dispatches ready nodes, accepts plan task completion or advances plan state automatically; the owner thinks, delegates, reviews and updates explicitly. Clear, low-risk coding goes to light; independent reviewers start blank and use a tier appropriate to the review risk.
|
|
@@ -89,7 +92,7 @@ Three processes, all coordinating via 127.0.0.1:17890 and `~/.wezard/`:
|
|
|
89
92
|
- A task is `~/.wezard/tasks/<id>.task.mjs`, an ES module exporting `when` / `gate` / `prompt` / `target`+`fresh` / `owner` (the wizard that scheduled it — its rolepage shows the task under 日程) — **the config is source the wizard edits directly** (hot-reloaded by mtime; a file that fails to load keeps its previous version running and surfaces the reason in `list_tasks`). Source stays source: `lastFired` and the gate's cross-round memo live in `~/.wezard/task-state.json`, so the daemon never writes back over a file a wizard just edited.
|
|
90
93
|
- `shared/trigger.ts` is the trigger AST (Specification + Interpreter). **Clock vs Guard is the whole point**: `every`/`daily`/`at` produce instants and answer "when next", `between`/`onDays`/`not` only veto. `and(clock, …guards)` is their intersection — that's what makes "白天每小时" expressible, and why `nextFire` enumerates clock candidates and picks the first one every guard passes. An AST, not a closure, because it must be renderable (`每 1 小时 · 08:00-21:00`), storable and drawable. `shared/schedule-spec.ts` under it is pure lexer (weekday / time-of-day / interval / window) — it grows with how people speak, the AST grows with how things are computed.
|
|
91
94
|
- `gate` (`task-gate.ts`) runs **in a child process with a timeout**: it is user/wizard-written code that shells out, and a wedged gate must not stall every other schedule — timeout, throw and crash are all the same verdict, *hold fire this round*. Returning `false` costs nothing and says nothing; that is how "only if there's work" stops spending a pane per empty round. A gate **error** posts one bubble (only on the good→bad transition) — a broken gate's silence is indistinguishable from "nothing to do today".
|
|
92
|
-
- **rolepage** (`shared/chat-http.ts` routes, shared verbatim by the daemon and the standalone svr; `shared/room-view.ts` ledger read model, `shared/role-view.ts` / `role-render.ts` turn folding; frontend `web/chat.js`): `GET /role?id=<ticket>&role=<name|target|human:x>` is the SPA shell; data comes from `/api/world` (rooms + wizard/human nodes + genealogy + plans/schedules), `/api/room` (snapshot + history paging), `/api/wizard` (card + "its own + addressed to it" / all messages), `/api/turn` + `/api/tool` (a message's process box; tool bodies fetched on expand), `/api/charter`, `/api/search`. Two sources, neither replaces the other: the room ledger is *what was said* (author / completion / speak-right on the row), the turn store is *how it was done* (tool calls, CLI text, usage). A wizard page is turn-led — a turn folds into an in-message (the asker) and an out-message (the reply) — with ledger rows hung on the turn that produced them. `?id=` is an unguessable record id acting as the capability: any valid ticket may view every role. The standalone svr receives `WorldFacts` (`plans`, `rooms`, `names`, …) by POST; without a room reader it degrades to graph + members. The plan/schedule view is read-only; active/paused plan owners and their registered management ancestors stay visible. The sidebar and relationship cards share one conversation/window/unread implementation.
|
|
95
|
+
- **rolepage** (`shared/chat-http.ts` routes, shared verbatim by the daemon and the standalone svr; `shared/room-view.ts` ledger read model, `shared/role-view.ts` / `role-render.ts` turn folding; frontend `web/chat.js`): `GET /role?id=<ticket>&role=<name|target|human:x>` is the SPA shell; data comes from `/api/world` (rooms + wizard/human nodes + genealogy + plans/schedules), `/api/room` (snapshot + history paging), `/api/wizard` (card + "its own + addressed to it" / all messages), `/api/turn` + `/api/tool` (a message's process box; tool bodies fetched on expand), `/api/charter`, `/api/search`. Two sources, neither replaces the other: the room ledger is *what was said* (author / completion / speak-right on the row), the turn store is *how it was done* (tool calls, CLI text, usage). A wizard page is turn-led — a turn folds into an in-message (the asker) and an out-message (the reply) — with ledger rows hung on the turn that produced them. `?id=` is an unguessable record id acting as the capability: any valid ticket may view every role. The standalone svr receives `WorldFacts` (`plans`, `rooms`, `names`, …) by POST; without a room reader it degrades to graph + members. Several daemons may share one svr (same host): each signs its pushes with `daemonSourceOf(stateDir)` (`shared/instance-id.ts`) and stamps forwarded records with `src`; on the svr a ticket sees only its own `src`'s records and snapshot, and the svr's local ledger (`svr.roomsDir`, default `<daemon.stateDir>/rooms`) serves only the source that reported the same `roomsDir`. Unsigned (old) records/tickets keep the merged view. The plan/schedule view is read-only; active/paused plan owners and their registered management ancestors stay visible. The sidebar and relationship cards share one conversation/window/unread implementation.
|
|
93
96
|
- **Retired** (no compatibility fallback): jobs, workflow runners and the graph executor with their MCP/HTTP entry points and `jobsFile`/`receiptsFile` configuration; the `daemon/router.ts` route ledger, receipts and `tell_peer` / `wait_peer` / `read_chat` / `send_peer` / `dispatch`; the `topOnly` / `speech` chat policy and public→private demotion (noise control is structural now: open a follow-up room, or pull people into the main one); `chatOriginOnly` / `slashAckFirstLine`. Old data is only read by the one-shot migration (`shared/room-migrate.ts`, `shared/legacy-routes.ts`, `cli/migrate-rooms.ts`). Generic idle waiting lives in `daemon/wait-idle.ts`.
|
|
94
97
|
|
|
95
98
|
**Configuration** (`shared/config.ts`):
|
|
@@ -106,21 +109,21 @@ Three processes, all coordinating via 127.0.0.1:17890 and `~/.wezard/`:
|
|
|
106
109
|
|
|
107
110
|
**Hook + sync**:
|
|
108
111
|
- **审批 hook 按会话注入, 不注册到全机**: `shared/session-hooks.ts` 写出 `<stateDir>/session-hooks.json` 和一个只带 hooks 的最小插件目录; spawn 时按其后端加 `--settings <file>` (claude / codebuddy) 或 `--plugin-dir <dir>` (claude-internal 1.x 没有 `--settings`)。同一个 pane 的启动行还带 `WEZARD_MANAGED=1` 与 daemon 地址 —— 它们原先由 sync 写进全机 settings 的 env, 现在只存在于 wezard 自己的进程里。codex 用 `shared/codex-hooks.ts` 的 `-c` 覆盖, 同理。
|
|
109
|
-
- **MCP 也按会话注入**: `shared/session-mcp.ts` 写出 `<stateDir>/session-mcp.json` (
|
|
112
|
+
- **MCP 也按会话注入**: `shared/session-mcp.ts` 写出 `<stateDir>/session-mcp-sock.json` (新文件名 = 「起于 unix socket 控制面」的判据), 内容按 `daemon.mcpTransport` 是 `relay` (缺省, `dist/mcp/relay.js`) 或 `stdio` (全量 `dist/mcp/server.js`, 排障用), 两种都带 `env.WEZARD_DAEMON_SOCK`; spawn 的启动行加 `--mcp-config <file>` (claude / claude-internal / codebuddy 都认, **不加 `--strict-mcp-config`** 否则会连用户自己的 MCP 一起挡掉)。旧的 `session-mcp.json` / `session-mcp-http.json` 不再生成, daemon 启动时 unlink (http 那份里有口令原文); 旧值 `mcpTransport:"http"` 读成 `relay`。没有 `type:"http"` 直连了: 任何留给 MCP 的 TCP 端口都能在 daemon 重启空窗被抢占, 抢占者会收走请求头里的口令。`.claude-plugin/plugin.json` 不再声明 `mcpServers`, 仓库里也没有 `hooks/hooks.json` — 插件只提供 `commands/*`。
|
|
110
113
|
- `cli/sync.ts` 现在**只做清理**: 把老版本写进 `config.sync.targets` 各处的 wezard hook 条目 / `WEZARD_*` env / `mcpServers.wezard` (`~/.codebuddy/mcp.json` 与 `~/.claude-internal/settings.json` 两处) 删掉, 空壳对象一并删 — 重跑幂等, `--remove` 之后机器上不留 wezard 的任何注册。`~/.wezard/sync.lock.json` 只记录还剩哪些目标。 As a safety net the entry points (`hooks/pre-tool-use.sh`, `cli/codex-hook.ts`) still open with an ownership gate — only a CLI process wezard spawned carries `WEZARD_MANAGED=1` (launch line / headless inject env); anything else exits 0 with no output and stays on the CLI's own permission flow, never `allow`, never `ask`. Panes that predate the injection are covered by the `@wezard_managed` pane option the daemon stamps on every binding it attaches (one local `tmux show-options` in the hook, no daemon call). `~/.wezard/state/approval-mode` is the runtime override on top of that registration (`wezard use cli|wecom`): the file holds `cli` (absent = `wecom`), the hook reads it with a bare `cat` **before** it touches jq or the daemon and then exits 0 with no output — the CLI's own permission flow answers — while `daemon/approval.ts`, the picker sentinel and `cli/codex-hook.ts` treat the same file as "no cards, no auto-press". **A hook that cannot reach the daemon answers nothing, never `allow`**: silent auto-allow would hand a pane every permission while the human still believes approval is on. It waits only when the service is still registered (`launchctl print` / systemd `LoadState`), so `wezard stop` degrades to local CLI immediately instead of burning the 60s resume budget.
|
|
111
114
|
|
|
112
|
-
**MCP server** (`mcp/tools.ts` is the tool surface; `mcp/
|
|
115
|
+
**MCP server** (`mcp/tools.ts` is the tool surface; `mcp/relay.ts` is the default per-pane stdio entry — **node builtins only, no SDK / zod** (≈7~9MB per pane vs ≈33MB for the full server): each stdin JSON-RPC line becomes a `POST /mcp` over the socket with `x-wezard-token` (read fresh) / `x-wezard-pane` / `x-wezard-session`, the JSON reply goes back as one stdout line, notifications (202) write nothing, a daemon that is down is retried ~15s (reload gap) and then every request with an id gets a JSON-RPC error instead of hanging; `mcp/server.ts` is the full stdio server kept for `daemon.mcpTransport:"stdio"` — both dist paths are load-bearing, every pane config runs `node dist/mcp/relay.js` or `node dist/mcp/server.js`; `daemon/mcp-http.ts` is the daemon's own stateless StreamableHTTP endpoint that the relay talks to, on the control socket): stateless w.r.t. WeCom, every tool just `POST`s to the daemon. Add a tool in `mcp/tools.ts` AND a route handler in `daemon/`. Rarely used tools (`list_claude_sessions` / `switch_claude_session` / `list_chats`) register only with `WEZARD_MCP_EXTRA=1` — every registered tool costs model context. Collaboration tools (`wizard_whoami` / `wizard_identity` / `wizard_roster` / `spawn_wizard` / `clone_wizard` / `stop_wizard` / `wizard_remember` / `handoff` / `set_model` / `delegate` / `peek_peer`, the `chat_*` / `room_*` family, `plan_create/get/list/update`) resolve the caller through `selfRef()` = `{sessionId, tmuxPane}` (stdio: env; http: per-request `mcpIdentity`) — `daemonPost` attaches it to every POST, `daemonGet` does not so the daemon can resolve *which* session is asking — env sessionId goes stale after a `/clear`, pane id doesn't. Discovery is layered: the charter (`renderCharter`) carries one "when to use" line per tool and is the only part guaranteed in context — Claude Code defers MCP tool schemas behind ToolSearch — while each tool description carries the mechanism and parameters. Keep the two from restating each other. Address parameters are `name` / `names` (`fix` / `.fix`); retired `tag` / `tags` parameters and the `send_peer`, `tell_peer`, `wait_peer`, `read_chat`, `dispatch`, and `wizard_handoff_self` tools are removed. Internal target keys remain current identities, not compatibility addresses.
|
|
113
116
|
|
|
114
117
|
## Important patterns / pitfalls
|
|
115
118
|
|
|
116
119
|
- **PATH for spawn**: anything the daemon spawns must go through `shared/exec-path.ts`'s `augmentedPath(process.env.PATH)` — launchd/systemd start it with a stripped PATH that often lacks nvm/homebrew, so a new spawn ENOENTs in production while working fine under `npm run dev:daemon`. Callers needing more dirs pass them as the second arg (`session-scan` adds `/usr/sbin` for `lsof`).
|
|
117
|
-
- **launchd respawn**: `KeepAlive.SuccessfulExit=false`. `wezard reload` does `POST /shutdown` AND `launchctl kickstart`; just hitting `/shutdown` won't bounce the binary.
|
|
120
|
+
- **launchd respawn**: `KeepAlive.SuccessfulExit=false`. `wezard reload` does `POST /shutdown` (over the control socket, only if it is up) AND `launchctl kickstart`; just hitting `/shutdown` won't bounce the binary. Reloading from an old TCP-era daemon (no socket) only restarts through the service manager, and the old daemon is not drained — hooks parked on an approval card wait for the new daemon and the card is re-pushed.
|
|
118
121
|
- **Uninstall order**: `wezard uninstall` *before* `npm uninstall -g wezard`. Otherwise launchd repeatedly tries to relaunch a deleted binary. State at `~/.wezard/` is intentionally preserved.
|
|
119
122
|
- **Card update has a 5s window**: `client.updateTemplateCard` only works within 5s of the click event — `installApprovalEventListener` does the rewrite synchronously inside the event handler.
|
|
120
123
|
- **Transcripts** live under each backend's own projects root (`~/.claude/projects/`, `~/.claude-internal/projects/`, `~/.codebuddy/projects/`); `backendForPath` in `shared/cli-backends.ts` recovers the backend from a jsonl path.
|
|
121
124
|
- **Long-poll timeouts**: hook curl `--max-time` (`approval.hookTimeoutSec`, default 43210) must be **strictly larger** than `approval.longPollSec` (default 43200 = 12h), or the hook returns `ask` while the daemon is still waiting on a click.
|
|
122
125
|
- **Sensitive arg redaction** (`daemon/redact.ts`) runs before card render when `approval.sensitiveArgRedact=true`. Only the redacted form is shown in WeCom and stored in pending meta.
|
|
123
|
-
- **Daemon fd limit**: the launchd plist MUST set `SoftResourceLimits.NumberOfFiles` (template = 65536). The daemon restores one mirror per active session at boot (jsonl tail + subagent watchers + tmux spawn each), so a few hundred sessions exceed launchd's default 256 soft limit; `spawn` then throws `EBADF`, the process dies before `HTTP listening`, and `KeepAlive` wedges in a crash loop (`status` shows `down`, `launchctl` reports a stale pid). If
|
|
126
|
+
- **Daemon fd limit**: the launchd plist MUST set `SoftResourceLimits.NumberOfFiles` (template = 65536). The daemon restores one mirror per active session at boot (jsonl tail + subagent watchers + tmux spawn each), so a few hundred sessions exceed launchd's default 256 soft limit; `spawn` then throws `EBADF`, the process dies before `HTTP listening`, and `KeepAlive` wedges in a crash loop (`status` shows `down`, `launchctl` reports a stale pid). If the control socket refuses / is absent (`wezard status` says down) while a launchd pid exists and `daemon.stderr.log` shows `spawn EBADF`, this is the cause — never "fix" it by editing the installed plist in `~/Library/LaunchAgents`, since `install.sh` regenerates it from `launchd/com.wezard.daemon.plist.template`; edit the template instead.
|
|
124
127
|
|
|
125
128
|
## Project conventions
|
|
126
129
|
|
package/README.md
CHANGED
|
@@ -131,7 +131,7 @@ wezard init
|
|
|
131
131
|
/clear .docs 只清 docs 的上下文
|
|
132
132
|
```
|
|
133
133
|
|
|
134
|
-
每条 wizard 的回复都带
|
|
134
|
+
每条 wizard 的回复都带 `🧙 name:` 署名头,在群里引用它的气泡就等于跟它说话。句中的 `a.ts`、`.gitignore` 这类不会被当成名字。
|
|
135
135
|
|
|
136
136
|
**管家**
|
|
137
137
|
|
|
@@ -370,7 +370,7 @@ wezard uninstall # 完整卸载(先于 npm uninstall)
|
|
|
370
370
|
## 常见问题
|
|
371
371
|
|
|
372
372
|
**Q: hook 不触发?**
|
|
373
|
-
审批 hook 与 wezard MCP 都是按会话注入的:看那个 CLI 进程的启动行有没有 `--settings …/session-hooks.json` / `--mcp-config …/session-mcp.json`(`ps -o command= -p <pid
|
|
373
|
+
审批 hook 与 wezard MCP 都是按会话注入的:看那个 CLI 进程的启动行有没有 `--settings …/session-hooks.json` / `--mcp-config …/session-mcp-sock.json`(`ps -o command= -p <pid>`)。没有(或还是 `session-mcp.json` / `session-mcp-http.json`)就是升级前起的老 pane,空闲时 daemon 会自动回收、下一句话 `--resume` 重起;全机 settings 里本来就不该有 wezard。
|
|
374
374
|
|
|
375
375
|
**Q: 卡片点了没反应?**
|
|
376
376
|
企业微信卡片就地刷新只有 5 秒窗口,超时不刷新是正常的,决策本身仍然生效。
|
package/cli/wezard.sh
CHANGED
|
@@ -1,12 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env bash
|
|
2
|
-
# wezard CLI — talks to local wezard daemon over
|
|
2
|
+
# wezard CLI — talks to the local wezard daemon over its unix socket and toggles launchd/systemd.
|
|
3
3
|
set -uo pipefail
|
|
4
4
|
|
|
5
|
-
DAEMON_BASE="${WEZARD_DAEMON_BASE:-http://127.0.0.1:17890}"
|
|
6
5
|
LABEL="com.wezard.daemon"
|
|
7
6
|
HOME_DIR="$HOME"
|
|
8
7
|
OS="$(uname -s)"
|
|
9
8
|
|
|
9
|
+
# 控制面 = daemon 的 unix socket (别的 uid 连不上)。路径规则同 shared/daemon-addr.ts:
|
|
10
|
+
# env WEZARD_DAEMON_SOCK → config daemon.socket → ${stateDir}/run/daemon.sock → ~/.wezard/state/run/daemon.sock。
|
|
11
|
+
# 读不到 daemon 时没法问 /status, 所以配置在这里按文本粗读 (只看 "daemon": {…} 块里的键)。
|
|
12
|
+
daemon_conf() {
|
|
13
|
+
local f
|
|
14
|
+
for f in "${WEZARD_CONFIG:-}" "$HOME_DIR/.wezard/config.jsonc" "$HOME_DIR/.wezard/config.json"; do
|
|
15
|
+
[[ -n "$f" && -f "$f" ]] || continue
|
|
16
|
+
sed -e 's|^[[:space:]]*//.*||' -e 's|[[:space:]]//.*$||' "$f" | awk -v k="$1" '
|
|
17
|
+
/"daemon"[[:space:]]*:[[:space:]]*\{/ { on = 1 }
|
|
18
|
+
on && match($0, "\"" k "\"[[:space:]]*:[[:space:]]*\"[^\"]*\"") {
|
|
19
|
+
v = substr($0, RSTART, RLENGTH); sub(/^[^:]*:[[:space:]]*"/, "", v); sub(/"$/, "", v); print v; exit }
|
|
20
|
+
on && /\}/ { exit }'
|
|
21
|
+
return 0
|
|
22
|
+
done
|
|
23
|
+
}
|
|
24
|
+
resolve_sock() {
|
|
25
|
+
local v
|
|
26
|
+
if [[ -n "${WEZARD_DAEMON_SOCK:-}" ]]; then v="$WEZARD_DAEMON_SOCK"
|
|
27
|
+
else
|
|
28
|
+
v="$(daemon_conf socket)"
|
|
29
|
+
if [[ -z "$v" ]]; then
|
|
30
|
+
v="$(daemon_conf stateDir)"; v="${v:-$HOME_DIR/.wezard/state}"; v="${v%/}/run/daemon.sock"
|
|
31
|
+
fi
|
|
32
|
+
fi
|
|
33
|
+
printf '%s' "${v/#\~/$HOME_DIR}"
|
|
34
|
+
}
|
|
35
|
+
SOCK="$(resolve_sock)"
|
|
36
|
+
|
|
10
37
|
# Resolve symlinks so REPO_ROOT points at the real package dir even when this
|
|
11
38
|
# script is invoked via the npm-installed bin symlink (e.g. ~/.npm-global/bin/wezard).
|
|
12
39
|
# macOS ships BSD readlink without -f, so chase the chain by hand.
|
|
@@ -31,7 +58,7 @@ wezard <subcommand>
|
|
|
31
58
|
start load resident daemon (launchd/systemd)
|
|
32
59
|
stop unload resident daemon
|
|
33
60
|
restart stop + start
|
|
34
|
-
reload quick: shutdown via
|
|
61
|
+
reload quick: shutdown via the control socket (if up) + kickstart
|
|
35
62
|
mirror-status show current mirror attachment
|
|
36
63
|
send <chat> <text> proactive markdown message
|
|
37
64
|
pending list outstanding approval req_ids
|
|
@@ -45,6 +72,7 @@ wezard <subcommand>
|
|
|
45
72
|
skills [list|install|remove|pin|unpin|update] [name] [--force]
|
|
46
73
|
bundled skills (e.g. 企微文档套件): show / reinstall / opt out / take over
|
|
47
74
|
audit [tag] token/cost breakdown for current Claude session (main + subagents)
|
|
75
|
+
ext <ask|wait|inbox|ack|cancel|rotate> outward-facing agent bridge (CoC): ask a wizard, collect answers
|
|
48
76
|
update npm i -g wezard@latest + repoint/restart daemon + sync (one command, see /wezard:update)
|
|
49
77
|
uninstall full teardown: stop daemon + unsync + plugin uninstall + remove daemon (run before `npm uninstall -g`)
|
|
50
78
|
add `--purge` to also delete ~/.wezard state
|
|
@@ -53,12 +81,10 @@ wezard <subcommand>
|
|
|
53
81
|
EOF
|
|
54
82
|
}
|
|
55
83
|
|
|
56
|
-
# --
|
|
57
|
-
#
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
http_get() { curl -sS --noproxy '*' --max-time 5 "$DAEMON_BASE$1"; }
|
|
61
|
-
http_post() { curl -sS --noproxy '*' --max-time 5 -X POST -H 'content-type: application/json' -d "${2:-{\}}" "$DAEMON_BASE$1"; }
|
|
84
|
+
# 一律 --unix-socket: 控制面不再有 TCP 端口, 也就没有代理能插进 CLI 与 daemon 之间
|
|
85
|
+
# (--noproxy 保留, 不依赖 curl 对 unix socket 忽略代理这条细则)。
|
|
86
|
+
http_get() { curl -sS --noproxy '*' --unix-socket "$SOCK" --max-time 5 "http://wezard$1"; }
|
|
87
|
+
http_post() { curl -sS --noproxy '*' --unix-socket "$SOCK" --max-time 5 -X POST -H 'content-type: application/json' -d "${2:-{\}}" "http://wezard$1"; }
|
|
62
88
|
|
|
63
89
|
# Run a dist/ entry script, building first when we're sitting in a dev checkout.
|
|
64
90
|
# npm installs ship dist/ in the tarball, so a missing script there means a
|
|
@@ -87,16 +113,16 @@ pkg_version() {
|
|
|
87
113
|
# One launchctl vocabulary, one readiness judge. Every lifecycle command
|
|
88
114
|
# (start/restart/reload) funnels through ensure_up so none can leave the job in
|
|
89
115
|
# a state another can't recover from. Success is judged by the invariant that
|
|
90
|
-
# matters — /status
|
|
116
|
+
# matters — /status answers on the control socket — never by a launchctl exit code, which
|
|
91
117
|
# lies (un-bootstrapped domains, throttle, load/bootstrap semantics clash).
|
|
92
118
|
PLIST="$HOME_DIR/Library/LaunchAgents/${LABEL}.plist"
|
|
93
119
|
|
|
94
120
|
# Fast readiness probe — short per-call timeout so a bound-but-wedged /status
|
|
95
121
|
# (e.g. daemon blocked on WS init) fails the poll in ~1s, not the 5s http_get
|
|
96
122
|
# budget.
|
|
97
|
-
probe() { curl -sS --noproxy '*' --connect-timeout 1 --max-time 1 "
|
|
98
|
-
# 按墙钟收口, 不按次数:
|
|
99
|
-
#
|
|
123
|
+
probe() { curl -sS --noproxy '*' --unix-socket "$SOCK" --connect-timeout 1 --max-time 1 "http://wezard/status" >/dev/null 2>&1; }
|
|
124
|
+
# 按墙钟收口, 不按次数: socket 还没 bind 时 curl 立刻 connection-refused / ENOENT 返回,
|
|
125
|
+
# 30 次循环其实只等了 ~9s —— 而恢复几百个镜像绑定的 boot 要几十秒才 listen, 于是
|
|
100
126
|
# reload 明明成功却报 "not responding"。
|
|
101
127
|
wait_up() { local end=$((SECONDS + 90)); while (( SECONDS < end )); do probe && return 0; sleep 0.3; done; return 1; }
|
|
102
128
|
wait_down() { local end=$((SECONDS + 30)); while (( SECONDS < end )); do probe || return 0; sleep 0.3; done; return 1; }
|
|
@@ -151,11 +177,15 @@ ensure_up() {
|
|
|
151
177
|
esac
|
|
152
178
|
wait_up
|
|
153
179
|
}
|
|
154
|
-
# Guaranteed teardown: drive shutdown through
|
|
155
|
-
# hard-exits (setTimeout process.exit) regardless of in-flight connections.
|
|
180
|
+
# Guaranteed teardown: drive shutdown through POST /shutdown on the control socket,
|
|
181
|
+
# which hard-exits (setTimeout process.exit) regardless of in-flight connections.
|
|
156
182
|
# NEVER SIGTERM a live daemon via bootout — its SIGTERM handler awaits
|
|
157
183
|
# http.close(), which blocks forever on a hung long-poll, wedging launchctl.
|
|
158
|
-
|
|
184
|
+
# socket 不在 = 没有新版 daemon 在听 (已停了, 或还是升级前听 TCP 的旧版): 这里**什么也不发** ——
|
|
185
|
+
# 尤其绝不向 TCP 17890 发 /shutdown, 那可能是同机别的用户的旧 daemon; 旧版由
|
|
186
|
+
# ensure_up 里的 systemctl restart / launchctl kickstart -k 换掉 (那一次不 drain,
|
|
187
|
+
# 挂着的审批 hook 会等新 daemon 回来重新推卡)。
|
|
188
|
+
graceful_stop() { [[ -S "$SOCK" ]] || return 0; http_post /shutdown >/dev/null 2>&1 || true; wait_down; }
|
|
159
189
|
# Remove the job from the domain (so RunAtLoad won't respawn it). Process is
|
|
160
190
|
# already dead from graceful_stop, so bootout is instant — nothing to kill.
|
|
161
191
|
svc_unregister() {
|
|
@@ -180,7 +210,7 @@ case "$cmd" in
|
|
|
180
210
|
# /status unreachable — distinguish "not loaded" from the silent-death case:
|
|
181
211
|
# launchd shows the job loaded but it never bound the port (crash-loop /
|
|
182
212
|
# bad config). Surface that instead of a flat "down".
|
|
183
|
-
echo "daemon: down ($
|
|
213
|
+
echo "daemon: down (socket $SOCK)"
|
|
184
214
|
if [[ "$OS" == "Darwin" ]] && ex=$(launchctl print "gui/$(id -u)/${LABEL}" 2>/dev/null | sed -n 's/.*last exit code = \([0-9-]*\).*/\1/p'); then
|
|
185
215
|
[[ -n "$ex" && "$ex" != "0" ]] \
|
|
186
216
|
&& echo " ↳ launchd job loaded but last exit code = $ex — crash-looping. 'wezard logs' to see why." >&2
|
|
@@ -196,8 +226,8 @@ case "$cmd" in
|
|
|
196
226
|
restart) graceful_stop >/dev/null 2>&1 || true; svc_unregister; ensure_up && echo "daemon: restarted" || { echo "daemon: restart failed — 'wezard logs'" >&2; exit 1; } ;;
|
|
197
227
|
reload)
|
|
198
228
|
# KeepAlive.SuccessfulExit=false, so /shutdown alone won't respawn. Graceful
|
|
199
|
-
# stop WAITS for
|
|
200
|
-
#
|
|
229
|
+
# stop WAITS for the control socket to go away (else the respawn finds a live
|
|
230
|
+
# listener and exits 1 into ThrottleInterval), then converge via the shared primitive.
|
|
201
231
|
graceful_stop >/dev/null 2>&1 || true
|
|
202
232
|
ensure_up && echo "daemon: reloaded" || { echo "daemon: reload issued but /status not responding — 'wezard logs'" >&2; exit 1; }
|
|
203
233
|
;;
|
|
@@ -335,7 +365,7 @@ case "$cmd" in
|
|
|
335
365
|
# preserved unless `--purge` is given.
|
|
336
366
|
purge=0
|
|
337
367
|
[[ "${1:-}" == "--purge" ]] && purge=1
|
|
338
|
-
|
|
368
|
+
graceful_stop >/dev/null 2>&1 || true
|
|
339
369
|
NODE_BIN="$(command -v node)"
|
|
340
370
|
SYNC_SCRIPT="$REPO_ROOT/dist/cli/sync.js"
|
|
341
371
|
[[ -f "$SYNC_SCRIPT" ]] && "$NODE_BIN" "$SYNC_SCRIPT" --remove || true
|
|
@@ -376,6 +406,12 @@ case "$cmd" in
|
|
|
376
406
|
[[ -f "$SCRIPT" ]] || { echo "build first: npm run build"; exit 1; }
|
|
377
407
|
exec "$NODE_BIN" "$SCRIPT" "$@"
|
|
378
408
|
;;
|
|
409
|
+
ext)
|
|
410
|
+
NODE_BIN="$(command -v node)"
|
|
411
|
+
SCRIPT="$REPO_ROOT/dist/cli/ext.js"
|
|
412
|
+
[[ -f "$SCRIPT" ]] || { echo "build first: npm run build"; exit 1; }
|
|
413
|
+
exec "$NODE_BIN" "$SCRIPT" "$@"
|
|
414
|
+
;;
|
|
379
415
|
help|-h|--help) usage ;;
|
|
380
416
|
version|-v|--version)
|
|
381
417
|
[[ -f "$REPO_ROOT/package.json" ]] || { echo "package.json not found at $REPO_ROOT/package.json" >&2; exit 1; }
|
package/config.example.jsonc
CHANGED
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
|
|
18
18
|
// ── Daemon (resident process) ─────────────────────────────────────
|
|
19
19
|
"daemon": {
|
|
20
|
+
// 控制面 = unix socket (hook / MCP / CLI 都走它; 空 = <stateDir>/run/daemon.sock, 路径 ≤103 字节)。
|
|
21
|
+
"socket": "",
|
|
22
|
+
// 浏览器视图 (rolepage / 详情页) 的只读 TCP 监听; port 0 = 不开。控制路由在这上面一律 410。
|
|
20
23
|
"host": "127.0.0.1",
|
|
21
24
|
"port": 17890,
|
|
22
25
|
"stateDir": "~/.wezard/state",
|
package/dist/cli/audit.js
CHANGED
|
@@ -13,7 +13,9 @@ import { readdirSync, statSync, existsSync } from "node:fs";
|
|
|
13
13
|
import { basename, join } from "node:path";
|
|
14
14
|
import { homedir } from "node:os";
|
|
15
15
|
import { computeAuditReport } from "../daemon/audit.js";
|
|
16
|
-
|
|
16
|
+
import { cliSocketPath } from "../shared/cli-socket.js";
|
|
17
|
+
import { daemonRequest } from "../shared/daemon-client.js";
|
|
18
|
+
// daemon 控制面 = unix socket; 连不上 (daemon 没起) 一律当「没有镜像」。
|
|
17
19
|
const PROJECT_BASES = [
|
|
18
20
|
join(homedir(), ".claude-internal", "projects"),
|
|
19
21
|
join(homedir(), ".claude", "projects"),
|
|
@@ -69,10 +71,10 @@ const expandHome = (p) => (p.startsWith("~/") ? join(homedir(), p.slice(2)) : p)
|
|
|
69
71
|
const findMirrorByTag = async (tag) => {
|
|
70
72
|
const wanted = tag.replace(/^#/, "");
|
|
71
73
|
try {
|
|
72
|
-
const res = await
|
|
73
|
-
if (
|
|
74
|
+
const res = await daemonRequest("GET", "/mirror/status", { socketPath: cliSocketPath(), timeoutMs: 2000 });
|
|
75
|
+
if (res.status !== 200)
|
|
74
76
|
return null;
|
|
75
|
-
const status = (
|
|
77
|
+
const status = (res.json ?? {});
|
|
76
78
|
const matches = (status.mirrors ?? []).filter((m) => (m.target.split("#")[1] ?? "") === wanted);
|
|
77
79
|
if (matches.length === 0)
|
|
78
80
|
return null;
|
|
@@ -98,19 +100,15 @@ const findMirrorByTag = async (tag) => {
|
|
|
98
100
|
// when the daemon is down or no mirror is bound — local stdout is enough.
|
|
99
101
|
const pushToWeCom = async (sid, markdown) => {
|
|
100
102
|
try {
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
+
const socketPath = cliSocketPath();
|
|
104
|
+
const statusRes = await daemonRequest("GET", "/mirror/status", { socketPath, timeoutMs: 2000 });
|
|
105
|
+
if (statusRes.status !== 200)
|
|
103
106
|
return;
|
|
104
|
-
const status = (
|
|
107
|
+
const status = (statusRes.json ?? {});
|
|
105
108
|
const target = (status.mirrors ?? []).find((m) => m.sessionId === sid)?.target;
|
|
106
109
|
if (!target)
|
|
107
110
|
return;
|
|
108
|
-
await
|
|
109
|
-
method: "POST",
|
|
110
|
-
headers: { "content-type": "application/json" },
|
|
111
|
-
body: JSON.stringify({ chat: target, markdown }),
|
|
112
|
-
signal: AbortSignal.timeout(5000),
|
|
113
|
-
});
|
|
111
|
+
await daemonRequest("POST", "/message", { socketPath, body: { chat: target, markdown }, timeoutMs: 5000 });
|
|
114
112
|
}
|
|
115
113
|
catch { /* daemon unreachable — local stdout is enough */ }
|
|
116
114
|
};
|
package/dist/cli/audit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"audit.js","sourceRoot":"","sources":["../../cli/audit.ts"],"names":[],"mappings":"AAAA,6CAA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AE,SAAS,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC,CAAC;IACjE,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACpB,MAAM,WAAW,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;AACjC,CAAC,CAAC;AAEF,IAAI,EAAE,CAAC"}
|
package/dist/cli/codex-hook.js
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Codex's supported hook protocol → wezard's shared approval engine.
|
|
3
3
|
import { loadConfig } from "../shared/config.js";
|
|
4
|
+
import { clientSocketPath } from "../shared/daemon-addr.js";
|
|
5
|
+
import { daemonRequest } from "../shared/daemon-client.js";
|
|
4
6
|
import { codexApprovalRequest, codexHookOutput, codexSelfCallBypass } from "../shared/codex-approval.js";
|
|
5
7
|
import { sleep } from "../shared/std.js";
|
|
6
8
|
import { recordCodexPaneSession } from "../shared/codex.js";
|
|
7
9
|
import { readHookMode } from "../shared/hook-mode.js";
|
|
10
|
+
// 每段断连最多等多久 (reload 要恢复几百个镜像, 两三次重试不够); 只给测试缩短用。
|
|
11
|
+
const OUTAGE_MS = Number(process.env.WEZARD_CODEX_OUTAGE_MS) || 60_000;
|
|
8
12
|
const requestApproval = async (input) => {
|
|
9
13
|
const { config: cfg } = loadConfig();
|
|
10
14
|
if (!cfg.approval.enabled)
|
|
@@ -12,24 +16,22 @@ const requestApproval = async (input) => {
|
|
|
12
16
|
// `wezard use cli`: 审批权在本地 CLI, 回 ask 让 codex 弹它自己的原生框。
|
|
13
17
|
if (readHookMode(cfg.daemon.stateDir) === "cli")
|
|
14
18
|
return { decision: "ask", reason: "hook_mode_cli" };
|
|
15
|
-
|
|
16
|
-
//
|
|
17
|
-
const
|
|
18
|
-
if (!["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))
|
|
19
|
-
throw new Error("Codex approval bridge must use loopback");
|
|
19
|
+
// The control plane is the daemon's unix socket: it cannot leave the machine or reach another
|
|
20
|
+
// uid, so there is no URL to vet. env WEZARD_DAEMON_SOCK (set by the spawn line) wins over config.
|
|
21
|
+
const socketPath = clientSocketPath(cfg);
|
|
20
22
|
const deadline = Date.now() + cfg.approval.hookTimeoutSec * 1000;
|
|
21
23
|
let resumeId;
|
|
22
24
|
let outageSince;
|
|
23
25
|
while (Date.now() < deadline) {
|
|
24
26
|
try {
|
|
25
|
-
const resp = await
|
|
26
|
-
|
|
27
|
-
body:
|
|
28
|
-
|
|
27
|
+
const resp = await daemonRequest("POST", "/approve", {
|
|
28
|
+
socketPath,
|
|
29
|
+
body: { ...codexApprovalRequest(input), ...(resumeId ? { resume_req_id: resumeId } : {}) },
|
|
30
|
+
timeoutMs: Math.max(1, deadline - Date.now()),
|
|
29
31
|
});
|
|
30
|
-
if (!resp.
|
|
32
|
+
if (resp.status < 200 || resp.status >= 300 || !resp.json)
|
|
31
33
|
throw new Error(`approval HTTP ${resp.status}`);
|
|
32
|
-
const reply =
|
|
34
|
+
const reply = resp.json;
|
|
33
35
|
outageSince = undefined;
|
|
34
36
|
if (reply.decision !== "retry")
|
|
35
37
|
return reply;
|
|
@@ -40,17 +42,18 @@ const requestApproval = async (input) => {
|
|
|
40
42
|
}
|
|
41
43
|
catch (e) {
|
|
42
44
|
// Restoring hundreds of mirrors can outlast two retries during reload.
|
|
43
|
-
// Keep the pending card id and bound each outage by the hook budget /
|
|
45
|
+
// Keep the pending card id and bound each outage by the hook budget / OUTAGE_MS.
|
|
44
46
|
outageSince ??= Date.now();
|
|
45
|
-
const remaining = Math.min(deadline, outageSince +
|
|
47
|
+
const remaining = Math.min(deadline, outageSince + OUTAGE_MS) - Date.now();
|
|
46
48
|
if (remaining <= 0) {
|
|
47
49
|
const error = e;
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
//
|
|
50
|
+
const why = `bridge unavailable (${socketPath}): ${error.message}${error.code ? `: ${error.code}` : ""}`;
|
|
51
|
+
// Daemon down: fail closed. Codex has no PreToolUse "ask", so an unreachable bridge denies the
|
|
52
|
+
// tool (never allow — that would hand the pane every permission while the human believes
|
|
53
|
+
// approval is on); sandbox escalations (PermissionRequest) fall back to Codex's native prompt.
|
|
51
54
|
return input.hook_event_name === "PermissionRequest"
|
|
52
55
|
? { decision: "ask", reason: why }
|
|
53
|
-
: { decision: "
|
|
56
|
+
: { decision: "deny", reason: why };
|
|
54
57
|
}
|
|
55
58
|
await sleep(Math.min(1000, remaining));
|
|
56
59
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codex-hook.js","sourceRoot":"","sources":["../../cli/codex-hook.ts"],"names":[],"mappings":";AACA,qEAAqE;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACjD,OAAO,EAAE,oBAAoB,EAAE,eAAe,EAAE,mBAAmB,EAAoE,MAAM,6BAA6B,CAAC;AAC3K,OAAO,EAAE,KAAK,EAAE,MAAM,kBAAkB,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAEtD,MAAM,eAAe,GAAG,KAAK,EAAE,KAAyB,EAA0B,EAAE;IAClF,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,GAAG,UAAU,EAAE,CAAC;IACrC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO;QAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,mBAAmB,EAAE,CAAC;IACnF,wDAAwD;IACxD,IAAI,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,KAAK;QAAE,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,CAAC;IACrG,
|
|
1
|
+
{"version":3,"file":"codex-hook.js","sourceRoot":"","sources":["../../cli/codex-hook.ts"],"names":[],"mappings":";AACA,qEAAqE;AACrE,OAAO,EAAE,UAAU,EAAE,MAAM,qBAA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