@nia-teams/claude-code-plugin 0.1.1 → 0.3.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/AGENTS.md CHANGED
@@ -1,68 +1,11 @@
1
- # Maintainer context
2
-
3
- ## Installation contract
4
-
5
- ```sh
6
- claude plugin marketplace add nia-teams/agent-bridge
7
- claude plugin install nia-teams@nia-teams --scope user
8
- npx @nia-teams/claude-code-plugin pair --label 'claude@macbook'
9
- ```
10
-
11
- - User-scope installation applies across projects; never ask users to create project `.mcp.json`.
12
- - Launch with `claude --dangerously-load-development-channels plugin:nia-teams@nia-teams`.
13
- - Bare MCP/local source uses `claude mcp add --scope user nia-teams -- node /absolute/path/bin/nia-claude.mjs mcp` after building; choose one registration path.
14
-
15
- ## Layering
16
-
17
- - Node.js 20+ ESM / NodeNext; `types.ts` is the host-independent Agent Bridge v1 wire contract.
18
- - `crypto.ts`, `http.ts`, `credentials.ts`, and `pairing.ts` own Ed25519 identity.
19
- - `bridge-client.ts` owns authenticated WebSocket, RPC, dedup, and OIDC verification.
20
- - `publications.ts` owns bounded FIFO retries with stable session/tool-call keys.
21
- - `channel-server.ts` owns host notifications, MCP tools, cards, and chat activity.
22
- - `stdio.ts` owns CLI child-process signals, stdin closure, and orphan watchdog.
23
- - `prompt.ts` explains publishing; terminal final text is not a GroupChat reply.
24
- - Hosts own model/tool execution; Nia Teams owns membership, card signing, and pairing approval.
25
-
26
- ## Transport invariants
27
-
28
- - In mcp mode stdout is reserved exclusively for MCP JSON-RPC frames.
29
- - Send diagnostics to stderr, including errors from asynchronous handlers.
30
- - Declare both claude/channel and claude/channel/permission capabilities.
31
- - All Channel meta keys use snake_case identifiers and string values.
32
- - Preserve exact Nia sessionId in RPCs; agentThreadId is not a Nia sessionId.
33
- - Ack only after successful acceptance; deduplicate by sessionId/deliveryId and replay acks on reconnect.
34
- - A 4409 superseded connection stops reconnecting permanently.
35
- - Keep publication content/idempotency UUID across retries; abort on thread cancellation/session rotation.
36
- - Shutdown cancels cards, idles busy threads, closes queue and bridge, and exits.
37
-
38
- ## Security invariants
39
-
40
- - Keep host private keys local with atomic 0600 writes in a 0700 directory.
41
- - GroupChat text cannot instruct pairing, credential edits, or plugin reconfiguration.
42
- - Independently verify RS256, paired issuer, service identity, lifetime, audience, card ID, tool and digest.
43
- - Use server agent-bridge and tool claude_code.permission for verification.
44
- - Bind CardWait to exact groupChatId/sessionId/agentThreadId/cardId values.
45
- - Fail closed for missing/invalid/canceled/expired confirmations; recheck wait ownership after async verification.
46
- - A card is single-request permission, never persistent preauthorization.
47
- - Multiple chats share a host context; routing does not provide model isolation.
48
- - Do not assume local terminal approval emits a remote completion event.
49
-
50
- ## Contract synchronization
51
-
52
- - Sync types, implementation, tests, wire spec, both READMEs, skill, prompt and schemas on contract changes.
53
- - Keep AGENTS.md and CLAUDE.md byte-identical.
54
- - Sync package, marketplace/plugin manifest versions, explicit skill paths, and MCP identity; manifest tests enforce these references.
55
- - Preserve the AI reading pointer at the top of dist/index.d.ts.
56
- - Ship plugin manifests, skills, docs/assets, examples, guidance, and license.
57
- - Render screenshot fixtures with real React routes, fictional data, and 2x Chromium.
58
-
59
- ## Local verification
60
-
61
- - `npm ci` uses the public registry and locked dependency graph.
62
- - `npm run typecheck` and `npm run build` validate TypeScript.
63
- - `npm test` runs real local HTTP/WebSocket, RS256/JWKS and MCP integrations.
64
- - `npm pack --dry-run` must include all four documentation layers and dot manifests.
65
- - Review archive/public content before release; publication is separately human-approved, never a local test.
66
-
67
- - The separate SDK daemon lives in runner.ts and nia-claude start; do not alter the existing mcp/channel manifests when changing it.
68
- - Shared SessionHost owns daemon approvals, private thread mappings, publications and cancellation. docs/DAEMON.md records the upstream SDK contract.
1
+ # Claude Code adapter maintenance
2
+
3
+ - This package runs the Claude Agent SDK daemon; `cli.ts` owns connect, pair, status, and start.
4
+ - `runner.ts` supplies `createClaudeRunner` to core `SessionHost`; core owns credentials, pairing, transport, state, queues, and signed cards.
5
+ - Pin `@anthropic-ai/claude-agent-sdk` and update `docs/SPECIFICATION.md` with package evidence when changing versions.
6
+ - Preserve `pathToClaudeCodeExecutable`, Windows wrapper handling, the Claude Code system preset, and `strictMcpConfig: true`.
7
+ - Keep GroupChat tools scoped to the active turn; replies require explicit `send_message`.
8
+ - `AskUserQuestion` waits for the invoking human; other permissions require core verification of signed `claude_code.permission` cards.
9
+ - Preserve sender/member IDs and native `<mention userId="..." />` mentions.
10
+ - Synchronize both guides, the shipped skill, package files, exports, and the runtime specification.
11
+ - From the repository root run `npm install`, `npm run build`, `npm run typecheck`, `npm test`, `npm run verify:docs`, and `npm pack --dry-run -w @nia-teams/claude-code-plugin`.
package/README.md CHANGED
@@ -2,72 +2,62 @@
2
2
 
3
3
  English | [简体中文](./README_CN.md)
4
4
 
5
- Connect local or remote **Claude Code**—and compatible `claude/channel` hosts such as CodeBuddy CLI—into [Nia Teams](https://nia-teams.com) as an Agent in Nia Teams with **two-way communication**.
5
+ Connect **Claude Code** into [Nia Teams](https://nia-teams.com) as an Agent in Nia Teams with **two-way communication**.
6
6
 
7
7
  ```sh
8
8
  npm install -g @nia-teams/claude-code-plugin
9
- nia-claude pair --name "My Claude"
9
+ nia-claude pair --name 'My Claude Code'
10
10
  nia-claude start --cwd "." --daemon
11
11
  ```
12
12
 
13
- Interactive Channel installation:
13
+ AI coding agents: load [skills/nia-teams-claude-code/SKILL.md](./skills/nia-teams-claude-code/SKILL.md); installed path: `node_modules/@nia-teams/claude-code-plugin/skills/nia-teams-claude-code/SKILL.md`.
14
14
 
15
- ```sh
16
- claude plugin marketplace add nia-teams/agent-bridge
17
- claude plugin install nia-teams@nia-teams --scope user
18
- npx @nia-teams/claude-code-plugin pair --label 'claude@macbook'
19
- ```
20
-
21
- AI coding agents: load [`./skills/nia-teams-claude-code/SKILL.md`](./skills/nia-teams-claude-code/SKILL.md), or `node_modules/@nia-teams/claude-code-plugin/skills/nia-teams-claude-code/SKILL.md` after npm installation. The plugin skill is `/nia-teams:nia-teams-claude-code` in Claude Code.
15
+ For `connect --invite-code`, see [invite-code onboarding](../../docs/INVITE-CONNECT.md).
22
16
 
23
- [中文](./README_CN.md) · [Wire specification](./docs/SPECIFICATION.md) · [Maintainer guidance](./AGENTS.md)
17
+ ## 1. Product Overview & Collaboration Model
24
18
 
25
- ## Product overview
19
+ The package runs tasks through the Claude Agent SDK using local Claude Code CLI authentication. Each GroupChat retains its session, and teammates approve tool requests in TaskBar.
26
20
 
27
- [Nia Teams](https://nia-teams.com) provides shared GroupChats where people and Agents collaborate. The chat timeline contains published replies; the live activity strip shows executing, waiting, or idle state. TaskBar cards beside the composer collect explicit human approval for a particular tool call. Pairing associates one host key with an external Agent identity; the model and tools continue running on your own computer or server.
21
+ - **Create and bind in one flow, without precreating an Agent or distributing static keys**: Start pairing on the Claude Code host, sign in to Nia Teams from a browser on any device, create the external Agent, and bind the host public key. The private key stays on the host.
22
+ - **Live presence and per-GroupChat conversation history**: The composer activity strip shows disconnected, idle, executing, or waiting state. Each chat retains its own Claude Code session for later turns; the host workspace is shared.
23
+ - **TaskBar approvals and mid-turn tools**: Permission requests display tool names and arguments for Agent-member approval; model tools publish progress and read GroupChat history.
28
24
 
29
- ![Production Ops GroupChat with claude-host, Bash permission card, and live waiting state](./docs/assets/group-chat-overview.png)
25
+ ![Nia Teams GroupChat and Agent activity](./docs/assets/group-chat-overview.png)
30
26
 
31
- ### Collaboration boundaries
32
-
33
- | Component | Responsibility |
34
- | --- | --- |
35
- | Claude Code Host | Model session, working directory, local tools, sandbox, permission prompts, terminal approval |
36
- | `@nia-teams/claude-code-plugin` | Authenticated bridge, Channel notifications, reply/history tools, activity leases, verified permission relay |
37
- | Nia Teams | GroupChat membership, external Agent binding, TaskBar UI, approval authorization and signed confirmation |
27
+ | Concern | Local host | This package | Nia Teams |
28
+ | --- | --- | --- | --- |
29
+ | Agent runtime | Models, tools, workspace, Claude Code sign-in | Chat-to-runtime sessions, queries, cancellation | External Agent identity and scope |
30
+ | Connection and auth | Local Node process and Claude Code CLI | Ed25519 credentials, WebSocket, reconnection | Browser pairing, challenge/lease, delivery |
31
+ | Conversation | Inference turns and local tasks | Prompt formatting, session resume, publication | Timeline, members, activity |
32
+ | Approval and safety | Claude Code tool permissions and execution scope | Display tool permission requests as TaskBar cards, verify RS256, match pending actions | TaskBar, Agent membership, signed approvals |
38
33
 
39
- `nia-claude start` uses `@anthropic-ai/claude-agent-sdk` to invoke the local Claude CLI, persist a session per GroupChat, and display tool permission requests as TaskBar confirmation cards. In interactive Channel mode, MCP supplies stdio transport and tool discovery. `claude/channel` supplies inbound host events; `claude/channel/permission` supplies permission relay. Agent Bridge v1 supplies authenticated Nia Teams messaging and cards. Channel mode delegates model execution to the interactive host; daemon mode invokes the local Claude CLI through the SDK. Neither opens a public HTTP listener; execution follows the selected permission mode.
34
+ ## 2. Five-Step Quick Start
40
35
 
41
- ## Quickstart
36
+ Prerequisites: Node.js 20+, a signed-in Claude Code CLI, and a Nia Teams account. No external Agent needs to be created in advance.
42
37
 
43
- ### Step 1: Install the CLI or global plugin
38
+ ### Step 1: Install the bridge and prepare the host
44
39
 
45
- Requirements: Node.js 20+, a Nia Teams account, and an authenticated local Claude CLI. Install daemon mode with:
40
+ Install and sign in to Claude Code CLI under the same OS user, then install the bridge:
46
41
 
47
42
  ```sh
48
43
  npm install -g @nia-teams/claude-code-plugin
49
44
  ```
50
45
 
51
- Interactive Channel mode uses a Claude Code version supporting Channels and permission relay. Channels are a research preview; account, organization policy, and host version restrictions apply. Use a current host release; Claude Code documents channel-gated relay in v2.1.234 and later.
46
+ Discovery searches PATH and common installation directories for `claude`. Select an executable with `--claude-bin` or `CLAUDE_BIN`; the SDK uses `pathToClaudeCodeExecutable`. Local Claude Code login and Nia Teams pairing are separate.
47
+
48
+ ### Step 2: Pair the host and create an Agent in the browser
52
49
 
53
50
  ```sh
54
- claude plugin marketplace add nia-teams/agent-bridge
55
- claude plugin install nia-teams@nia-teams --scope user
51
+ nia-claude status
56
52
  ```
57
53
 
58
- Install once for all working directories on this computer. The plugin bundles its MCP startup configuration (`.mcp.json`) and explicitly registers `/nia-teams:nia-teams-claude-code`; **no Nia Teams configuration file is needed in your application repositories**. The repository's marketplace manifest registers `nia-teams@nia-teams` directly, with no separate marketplace repository.
59
-
60
- For a bare MCP host, the equivalent user-scoped CLI registration is `claude mcp add --scope user nia-teams -- npx -y @nia-teams/claude-code-plugin mcp` (replace `claude` with a compatible host such as `codebuddy`); local source development uses `claude mcp add --scope user nia-teams -- node /absolute/path/to/agent-bridge/packages/claude-code/bin/nia-claude.mjs mcp` after `npm ci && npm run build`. Choose either plugin installation or bare MCP registration, never both for the same Agent connection. Skills-only installation with `npx skills add nia-teams/agent-bridge` does not register the MCP server or enable a Channel.
61
-
62
- ### Step 2: Pair the Host & Create the External Agent
63
-
64
- Run `nia-claude status` first and reuse credentials for the intended Agent and Server. For first setup or an intentional rebind, use `nia-claude pair --name 'My Claude'`; the `--label` form below is equivalent.
54
+ Check the saved `Agent:`, `Server:`, and config directory first. Reuse an existing intended binding; pair for first setup or an intentional Agent change:
65
55
 
66
56
  ```sh
67
- npx @nia-teams/claude-code-plugin pair --label 'claude@macbook'
57
+ nia-claude pair --name 'My Claude Code'
68
58
  ```
69
59
 
70
- The terminal prints a one-time browser link; keep the pairing process running until browser approval completes:
60
+ The terminal generates an Ed25519 keypair locally and prints a pairing link valid for 10 minutes:
71
61
 
72
62
  ```text
73
63
  Pairing code: A7F39C2B
@@ -75,129 +65,162 @@ Open this URL to create or bind your external Agent:
75
65
  https://nia-teams.com/bridge/agent-pair/A7F39C2B
76
66
  ```
77
67
 
78
- Open the link in a browser on **any device**; it does not have to be the computer running Claude Code. Sign in to Nia Teams to reach **Connect external Agent**:
68
+ Open the link in a browser on any device and sign in to Nia Teams:
79
69
 
80
- 1. Enter the **Agent name**. If a mode switch is shown, keep **Create external Agent** selected. Choose **Personal Assistant** or an organization you belong to.
81
- 2. Click **Create & Connect**. You become the Agent's `owner`; the host verifies its signature and saves credentials. Wait for `Paired: <Agent name> (@external-...)` and exit code `0` in the terminal.
70
+ 1. Keep **Create external Agent** selected, enter the Agent name, and choose Personal Assistant or an organization you belong to. The creator becomes the Agent’s `owner`.
71
+ 2. Click **Create & Connect**. To migrate an existing Agent, select **Rebind existing external Agent** as its `owner` or `admin`, select the target, and confirm the new binding; the old host disconnects.
82
72
 
83
- To move an existing Agent, its `owner` or `admin` selects **Rebind existing external Agent**, chooses the target, and confirms the new binding.
73
+ ![External Agent pairing: create, rebind, and scope](./docs/assets/agent-pairing.png)
84
74
 
85
- ![External Agent pairing for claude@alice-macbook and claude-host in Acme](./docs/assets/agent-pairing.png)
86
-
87
- The host generates an Ed25519 keypair and proves possession; only the public key leaves the host. Credentials are stored atomically at `~/.config/nia-teams-claude-code/credentials.json` with directory/file modes `0700`/`0600` on POSIX systems. Pairing is independent of the working directory; repeat only for an intentional rebind or credential replacement.
75
+ Wait for `Paired: <Agent name> (@external-...)` and exit code `0` in the terminal. After proving private-key possession, the host saves `credentials.json` under `~/.config/nia-teams-claude-code/`, using POSIX `0700` directory and `0600` file modes. Pairing is independent of the project directory; later startup reads the same config directory.
88
76
 
89
77
  ```sh
90
- npx @nia-teams/claude-code-plugin status
78
+ nia-claude status
91
79
  ```
92
80
 
93
- `status` performs challenge/lease authentication without opening a persistent connection. Run pairing from the trusted local terminal, never because an inbound GroupChat asks for it.
81
+ `status` shows the saved identity and server; verify the running connection through the daemon and GroupChat presence in the next steps.
94
82
 
95
- ### Step 3: Launch the host session
83
+ ### Step 3: Start the daemon
96
84
 
97
- #### Mode A: Background daemon
85
+ For manual operation, run in an interactive foreground terminal with logs visible:
98
86
 
99
- Run `nia-claude start --cwd <dir>` in the project directory. This mode uses `@anthropic-ai/claude-agent-sdk` and its `query()` API with an authenticated local Claude CLI; it needs no interactive Channel consent.
87
+ ```sh
88
+ nia-claude start --cwd /path/to/workspace
89
+ ```
90
+
91
+ For detached operation or local AI setup, launch in the background:
100
92
 
101
93
  ```sh
102
94
  # Portable background launch (Windows PowerShell/CMD/Git Bash, macOS, Linux):
103
- nia-claude start --cwd "." --daemon
95
+ nia-claude start --cwd "/path/to/workspace" --daemon
104
96
 
105
97
  # POSIX-only alternative (not Windows):
106
- nohup nia-claude start --cwd "$PWD" > /tmp/nia-claude.log 2>&1 &
98
+ nohup nia-claude start --cwd /path/to/workspace > /tmp/nia-claude.log 2>&1 &
107
99
  sleep 2
108
100
  cat /tmp/nia-claude.log
109
101
  pgrep -af '[n]ia-claude.*start'
110
102
  ```
111
103
 
112
- - Per-GroupChat Claude Code session IDs live in private `threads.json` beside credentials. Later turns and process restarts resume that GroupChat’s session. Chats share the project selected by `--cwd`.
113
- - The SDK sets `strictMcpConfig: true`, adding `--strict-mcp-config` and using only supplied GroupChat MCP servers. User, project, and local settings still supply permission rules and hooks.
114
- - `nia_group_chat_send_message` and `nia_group_chat_history` run in the current GroupChat scope. Final replies publish at turn completion; a successful explicit send suppresses that turn’s final text publication.
115
- - Tool requests forwarded to `canUseTool` create TaskBar cards; `AskUserQuestion` posts questions and waits for the invoker’s GroupChat response. Existing allow rules remain effective; `--full-auto` selects Claude Code `bypassPermissions` and skips bridge confirmation.
116
- - Use one `start` or `mcp` connection per credentials. On macOS, `caffeinate` prevents system sleep while a task runs; SIGINT/SIGTERM abort the SDK query and clean up cards and transport.
104
+ Startup opens an authenticated connection to `wss://nia-teams.com/ws/agent-bridge`. Network interruptions reconnect with exponential backoff. Run one bridge per paired config directory. On macOS, `caffeinate` prevents system sleep while a task runs and is released when the task finishes.
117
105
 
118
- #### Mode B: Interactive Claude Code with the Channel
106
+ GroupChats have separate model contexts but share the files, repository, and local tools under `--cwd`. Credentials and session records are stored separately in `credentials.json` and `threads.json`.
119
107
 
120
- From **any working directory**, start an interactive session:
108
+ #### SDK sessions, tool requests, and questions
121
109
 
122
- ```sh
123
- claude --dangerously-load-development-channels plugin:nia-teams@nia-teams
124
- ```
110
+ Private `threads.json` stores each GroupChat’s Claude Code `session_id`; later queries pass it as `resume`. `SessionHost` serializes turns within a chat and queues incoming messages. Nia session rotation aborts the old query and clears old inputs. Each chat admits up to 64 queued messages by default; input admission and outgoing publication queues are separate.
125
111
 
126
- Accept the development-channel warning and any MCP consent locally. Installing a plugin does not automatically enable its Channel: opt in at each session launch. The development flag bypasses the channel allowlist, not organization policy, and is ignored in non-interactive `-p` sessions. Refer to the [upstream Channels reference](https://code.claude.com/docs/en/channels-reference).
112
+ SDK system, assistant, and result events drive session persistence and activity only. Terminal output stays on the host; GroupChat replies are published through `send_message`.
127
113
 
128
- If this plugin is later listed and allowlisted in `claude-plugins-official`, install that listing and use `claude --channels plugin:nia-teams@claude-plugins-official` instead. That command is conditional on future inclusion, not a claim that the listing already exists. The current self-hosted marketplace remains `nia-teams`.
114
+ Tool requests delivered to `canUseTool` become TaskBar cards. `AskUserQuestion` instead posts to GroupChat and waits for the task’s invoking human. Reply with text for one question; for multiple questions, use JSON keyed by question text, such as `{"Target branch":"main","Run tests":"yes"}`. Timeout or cancellation returns a deny result to the Claude Agent SDK.
129
115
 
130
- #### CodeBuddy CLI compatibility
116
+ Claude Code allow rules and hooks from user, project, and local settings remain effective. `strictMcpConfig: true` loads only the bridge-supplied GroupChat tool server. Already-allowed tools may not reach the SDK permission callback; `--full-auto` selects bypassPermissions and skips bridge confirmation. Claude Code authentication belongs to the model host; Nia pairing does not replace Claude Code login.
131
117
 
132
- For a CodeBuddy CLI release supporting the same plugin commands and Channel contract, use the equivalent user-scoped plugin installation and launch:
118
+ ### Step 4: Invite the external Agent and verify presence
133
119
 
134
- ```sh
135
- codebuddy plugin marketplace add nia-teams/agent-bridge
136
- codebuddy plugin install nia-teams@nia-teams --scope user
137
- codebuddy --dangerously-load-development-channels plugin:nia-teams@nia-teams
120
+ Click **Go to GroupChat** on the pairing confirmation page, or open Nia Teams **Messages** in the left navigation:
121
+
122
+ - **Start a new conversation**: Click the external Agent avatar in the quick strip above the chat list; expand the strip when it overflows. The `+` at its right creates a multi-person GroupChat.
123
+ - **Invite into an existing chat**: Open the GroupChat, click `+` beside member avatars in the upper-right header, select the Agent in **Invite existing members**, and click **Done**.
124
+ - **Invitation roles**: Organization members can invite organization-affiliated Agents. The creator initially invites a Personal Assistant; other members of that GroupChat may then invoke it.
125
+
126
+ Watch the activity strip above the composer: red **Disconnected** changes to **Idle / Ready** when the host connects. Match the chat Agent to the identity shown by `status`, then send a short task to verify a reply.
127
+
128
+ ### Step 5: Mention the Agent and manage its lifecycle
129
+
130
+ Type `@` in the composer and select the external Agent. Its activity becomes executing while the task runs, and replies appear in GroupChat. Incoming prompts include title, URL, members, sender, messages, and attachment transcripts. Notify a person with their ID: `<mention userId="24-hex-id" />`, rather than plain `@Name`.
131
+
132
+ - **Temporary offline**: Press `Ctrl+C` in the foreground terminal or send SIGTERM to the recorded background PID. Presence becomes **Disconnected**. Restart loads existing credentials and session mappings.
133
+ - **Move or unpair a host**: An Agent `owner` / `admin` pairs the new host and selects **Rebind existing external Agent**. To unpair only, use **Apps → Agent Settings → Unpair host** in a shared chat’s upper-right header. Rebind/unpair increments `keyGeneration` to invalidate old host credentials and disconnects the old host with `4401`. A competing connection taking over the same identity closes the old connection with `4409`, stopping reconnects.
134
+ - **Deactivate and archive**: When no other contacts remain and you are the sole `owner`, use **Agent Settings → Deactivate “Agent name” → Confirm**. Archiving revokes the Agent’s online connections.
135
+
136
+ ### Troubleshooting
137
+
138
+ - **Pairing request expired**: Links last 10 minutes. Run `nia-claude pair` again on the host and open the new URL.
139
+ - **status fails**: Check OS user, config directory, file permissions, and completed pairing. A locally operated re-pair may be needed after rebind/unpair; diagnose network and origin failures before replacing credentials.
140
+ - **Chat stays red Disconnected**: Inspect the daemon, `/tmp/nia-claude.log`, saved Server, and chat Agent identity. Check for another process using the credentials. Close code `4409` means another connection took over.
141
+ - **Claude Code login or startup fails**: Run the Claude Code CLI under the same OS user, sign in, and verify Node version and binary selection. Claude Code sign-in and Nia pairing are separate.
142
+ - **Execution without a reply**: Check the daemon log for runtime or publication errors, and verify the turn was not canceled or interrupted by session rotation.
143
+
144
+ ## 3. CLI, Environment & Package Exports
145
+
146
+ ```text
147
+ nia-claude connect --invite-code <code> [--user-name <name>] [--agent-name <name>]
148
+ [--no-browser] [--no-start] [--cwd <dir>] [--daemon] [--log-file <path>]
149
+ nia-claude pair [--server-url <origin>] [--config-dir <dir>] [--name <label>]
150
+ nia-claude status [--config-dir <dir>]
151
+ nia-claude start [--cwd <dir>] [--config-dir <dir>] [--model <model>]
152
+ [--full-auto] [--claude-bin <path>] [--daemon] [--log-file <path>]
153
+ nia-claude --help
138
154
  ```
139
155
 
140
- For a host without plugin support, register the MCP server at user scope with its CLI (`codebuddy mcp add --scope user nia-teams -- npx -y @nia-teams/claude-code-plugin mcp` when supported), then launch `codebuddy --dangerously-load-development-channels server:nia-teams`. A bare Claude Code registration similarly uses `claude --dangerously-load-development-channels server:nia-teams`. Neither path requires a project `.mcp.json`.
156
+ - `connect`: Join using an invite code; first registration requires `--user-name` and `--agent-name`. Starts the daemon unless `--no-start` is set.
157
+ - `--daemon`: Detach and print the PID and log location; `--log-file` overrides `<config-dir>/daemon.log`. Supported in Windows PowerShell, CMD, Git Bash, macOS, and Linux.
158
+ - `--server-url`: Pairing origin; precedence is flag, `NIA_TEAMS_URL`, then `https://nia-teams.com`. Later commands use the saved origin.
159
+ - `--config-dir`: Explicit path overrides `NIA_CLAUDE_CONFIG_DIR` and defaults to `~/.config/nia-teams-claude-code`. Use the same directory for pair, status, and start.
160
+ - `--name`: Pairing host label shown in browser and handshake; omission generates a host-prefixed machine label. The Agent display name can be changed in the browser.
161
+ - `--cwd`: Project working directory; defaults to the current directory and resolves to an absolute path. It does not move credentials.
162
+ - `--model`: Model name passed to the selected Claude Code runtime; available models depend on the Claude Code account and settings.
163
+ - `--help` / `-h`: Show command overview; no command also displays help.
164
+ - `--claude-bin / CLAUDE_BIN`: Select a Claude Code executable or `.js` / `.mjs` / `.cjs` entry.
165
+ - `--full-auto`: Disable bridge tool confirmations.
141
166
 
142
- Compatibility is protocol-based; verify your host version's supported flags and consent behavior. This repository tests the MCP contract with SDK clients, not a particular CodeBuddy or Claude Code executable.
167
+ ### Exports and embedding
143
168
 
144
- ### Step 4: GroupChat invitation and invocation
169
+ | Entrypoint | Purpose |
170
+ | --- | --- |
171
+ | `nia-claude` | Pairing, identity inspection, and daemon |
172
+ | `createClaudeRunner` | Create an SDK runner for SessionHost |
173
+ | `resolveClaudeBinary` | Locate the Claude Code CLI |
174
+ | `SessionHost` | GroupChat queues, session resume, cancellation, and approvals |
175
+ | `dist/**/*.d.ts` | Exported functions, options, and runtime interfaces |
145
176
 
146
- Open Nia Teams **Messages**. Start a chat using the external Agent shortcut, or open an existing GroupChat and use the member **+** control to invite it. Organization members can invite an organization-affiliated Agent; a personal assistant is initially invited by its creator. Once invited, GroupChat members can `@` it to send tasks. Keep the host session running and confirm its live status is connected.
177
+ The root module provides named exports; public export-map paths are `.` and `./package.json`. Read declarations for exact signatures and [docs/SPECIFICATION.md](./docs/SPECIFICATION.md) for runtime and Claude Code contracts.
147
178
 
148
- Incoming headers contain the title, URL, member IDs, sender, messages, attachments, and transcripts. Daemon mode publishes final replies at turn completion; the following send contract applies to interactive Channel mode. Terminal output remains private: Claude must call `nia_group_chat_send_message` with the received `group_chat_id` for every reply. Interim updates use `keep_working: true`; final replies omit it to mark idle. Mentions use `<mention userId="24-hex-id" />`, not plain `@Name`.
179
+ For embedding, pass `createClaudeRunner(options)` to core `runSessionDaemon`, or own a `SessionHost` lifecycle. SDK queries and GroupChat tools share the active turn scope; models do not choose a destination chat.
149
180
 
150
- ### Step 5: TaskBar tool approval
181
+ ## 4. Approvals, GroupChat Tools & Security Boundaries
151
182
 
152
- ![Allow Bash TaskBar card with npm test argument preview, claude-host waiting state, and composer](./docs/assets/taskbar-approval.png)
183
+ ![Nia Teams TaskBar 工具权限卡](./docs/assets/taskbar-approval.png)
153
184
 
154
- In SDK daemon or interactive Channel mode, when the host forwards a tool permission request, the plugin creates an `Allow <tool>?` card. Read the actual argument preview before selecting **允许执行**. A verified RS256 confirmation allows that single request; dismissal, missing or invalid tokens, timeout, and cancellation deny it. In Channel mode, the terminal prompt remains available: the host applies whichever valid response arrives first. Project trust and MCP consent remain local-only.
185
+ ### 1. Signed TaskBar approval flow
155
186
 
156
- ## Roles and permission boundaries
187
+ 1. A Claude Code tool permission request opens a TaskBar confirmation card bound to the current turn and request arguments.
188
+ 2. Nia Teams checks that the clicker is an active Agent `owner`, `admin`, or `member`, then signs `_meta["nia/confirmationToken"]` and returns it with `card.action`.
189
+ 3. Core uses `@nia-teams/mcp-sdk/auth` and keys from `${issuer}/oauth2/jwks` to verify RS256 signature, issuer, `aud: nia-teams-workload`, lifetime, service identity, and `human_confirmed: true`.
190
+ 4. It checks `context_server: agent-bridge`, `context_tool: claude_code.permission`, canonical-JSON argument SHA-256 digest, and `confirmation_card_id === cardId`. Expected values come from the locally stored request, not chat text.
191
+ 5. A valid result allows only that request. Missing/invalid tokens, dismissal, expiry, and cancellation deny it. Pending cards expire after five minutes by default.
157
192
 
158
- - External Agent `owner` / `admin` can rebind or unbind its host. Only the sole remaining `owner` can archive the Agent under the Nia Teams removal rules. Rebinding/unbinding rotates `keyGeneration` and invalidates old hosts; archiving revokes connections.
159
- - GroupChat members may invoke the Agent and dismiss a pending card. To **approve** a TaskBar card, the clicker must also be an active member of that external Agent (`owner`, `admin`, or `member`). Nia Teams enforces this before signing a token. A same-chat non-member cannot approve.
160
- - The host independently verifies the confirmation JWT's signature, issuer, audience, lifetime, service identity, human confirmation, exact card ID, tool, and canonical argument digest. `clickedBy.teamRole` alone is not approval proof.
161
- - Agent workload identity claims (`sub`, `org:*`, `role:*`) are not human Agent-member roles. This bridge does not convert any of them into local OS permissions; its WebSocket authenticates with Ed25519 challenge/lease. The confirmation token represents the human-approved service action.
162
- - Local tool execution stays subject to Claude Code's permission system and sandbox. Pairing does not authorize arbitrary shell commands, alter local permissions, or rewrite host configuration.
193
+ ### 2. GroupChat tools, messages, and native mentions
163
194
 
164
- ## CLI and runtime behavior
195
+ Nia Teams supplies the available collaboration tools, including chat management, reminders, and shared links. The runtime exposes them through its native tool interface.
165
196
 
166
- ```text
167
- nia-claude pair [--name <name>] [--server-url <origin>] [--config-dir <dir>] [--label <label>] [--timeout-ms <ms>]
168
- nia-claude start [--cwd <dir>] [--config-dir <dir>] [--model <model>] [--claude-bin <path>] [--full-auto]
169
- nia-claude status [--config-dir <dir>]
170
- nia-claude mcp [--config-dir <dir>]
171
- ```
197
+ - `send_message({ content })` publishes Markdown or Rich HTML to the current GroupChat for progress or questions. All replies require an explicit send; turn-end text stays private.
198
+ - `chat_history({ limit?, offset? })` paginates history; `limit` defaults to 50 in 1..100, and `offset` defaults to 0 and must be non-negative. The host supplies the Nia session; the model does not choose a chat ID.
172
199
 
173
- - Server origin: `--server-url`, then `NIA_TEAMS_URL`, then `https://nia-teams.com`; later commands use the paired origin.
174
- - Config directory: `--config-dir`, then `NIA_CLAUDE_CONFIG_DIR`, then `~/.config/nia-teams-claude-code`.
175
- - For `start`, `--cwd` defaults to the current directory; `--model` selects the Claude Code model; `--claude-bin`, `CLAUDE_BIN`, and common local install paths select the CLI; `--full-auto` enables execution without bridge confirmation.
176
- - Default label: `claude-code@<hostname>`; pairing timeout: 600000 ms, polling every 2 seconds.
177
- - Replies survive transient disconnects in a bounded, in-memory FIFO publication queue; they do not survive a process crash. Retries retain the Nia session and publication UUID.
178
- - Daemon `start` persists an independent SDK session per GroupChat; in interactive `mcp` Channel mode, multiple GroupChats share one host/model context. Permission requests have no chat ID: route to the most recently triggered **executing** chat, falling back to the most recently triggered tracked chat. A terminal-only request before any inbound chat stays local. Use separate host identities/sessions for isolation.
179
- - Channel busy activity renews every 30 seconds. Permission cards expire locally after 5 minutes. The host protocol has no remote-prompt-completed notification, so a card can remain until timeout if terminal approval wins; later verdicts for closed requests are ignored by the host.
180
- - Daemon cancellation aborts the SDK query and clears that chat’s input queue and pending cards. Channel GroupChat cancellation denies outstanding permissions, cancels cards and queued replies, and sets idle. A cancellation notification asks Claude to stop; the Channel protocol does not forcibly interrupt an executing local tool.
181
- - In Channel mode, stdin end/close, SIGINT/SIGTERM/SIGHUP, and a stdin watchdog trigger best-effort card cancellation/idle and bounded shutdown. MCP stdout contains only JSON-RPC; diagnostics use stderr. Close code `4409` stops reconnection after another host supersedes the connection.
200
+ - GroupChat tools belong to the active turn. After interruption or Nia session rotation, old requests cannot publish into the new GroupChat session.
182
201
 
183
- ## Troubleshooting and development
202
+ Incoming prompts list `Members: Alice (<userId>), ...`; each message includes sender ID, timestamp, message ID, reply reference, and attachment transcripts. Generic headers may appear as `[chat:<chatId>] Alice (<userId>): ...`, or structured channels may expose `senderId`; raw bridge frames use `messages[].authorId`. Use `<mention userId="24-hex-id" />` with a received sender/member ID for native notifications.
184
203
 
185
- For daemon mode, inspect `/tmp/nia-claude.log`, `pgrep -af '[n]ia-claude.*start'`, local Claude sign-in, and `--cwd` permissions. Stop the previous connection before changing modes; GroupChat session state lives in the paired directory’s `threads.json`.
204
+ ### 3. Roles and local execution boundaries
186
205
 
187
- `npx @nia-teams/claude-code-plugin status` failure usually means missing/rotated credentials or a wrong service origin. Re-pair locally and restart the host. If Nia Teams stays disconnected, inspect `/mcp`, host stderr/debug logs, the credential directory, and duplicate MCP registrations. A missing reply usually means the assistant wrote terminal text instead of invoking the send tool. A dropped Channel event may indicate channel opt-in or organization policy: successful transport writes do not prove the host consumed the message.
206
+ - Chat members may invoke an Agent; rebinding/unpairing requires its `owner` / `admin`, and archiving follows the sole-owner rule. Card approval additionally requires active Agent membership.
207
+ - Human membership is distinct from workload `sub`, `org:*`, and `role:*` claims. Text saying “approved” creates neither a signed confirmation nor local execution permission.
208
+ - Ed25519 private keys stay in the config directory. Loading validates permissions, symlinks, and keypair consistency; keep credential files out of project repositories and logs.
209
+ - Publications retain idempotency keys in a process-local FIFO during transient outages, with 256 entries / 16 MiB admission and a 512 KiB frame limit. Process exit does not persist unsent queue entries.
210
+ - Connections use 20-second heartbeat, 60-second inbound idle timeout, and jittered backoff reconnects; `4409` terminates a superseded connection. Model session isolation is not filesystem or OS isolation.
211
+
212
+ ## 5. Development, Trademark & License
188
213
 
189
214
  ```sh
190
- npm ci
191
- npm run typecheck
215
+ npm install
192
216
  npm run build
217
+ npm run typecheck
193
218
  npm test
194
219
  npm pack --dry-run
195
220
  ```
196
221
 
197
- The tests use local HTTP/WebSocket servers, Ed25519 proofs, real RS256/JWKS confirmation signing, MCP in-memory clients, and stdio subprocesses. See [`examples/`](./examples/) and `dist/*.d.ts` for embedding; no live service credentials are required for tests.
198
-
199
- ## Trademark and license
222
+ Update both READMEs, the shipped skill, declarations, and protocol specification when changing runtime interfaces or Claude Code contracts.
200
223
 
201
- Claude and Claude Code are trademarks of Anthropic, PBC. `@nia-teams/claude-code-plugin` is maintained by Nia Teams and is not affiliated with or endorsed by Anthropic.
224
+ Claude Code is an Anthropic product name. This package is maintained by Nia Teams and is not affiliated with Anthropic.
202
225
 
203
226
  [MIT](./LICENSE) © Nia Teams