@nia-teams/claude-code-plugin 0.2.0 → 0.3.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/AGENTS.md +11 -71
- package/README.md +129 -114
- package/README_CN.md +130 -112
- package/dist/cli.js +3 -7
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +3 -6
- package/dist/index.js +2 -4
- package/dist/index.js.map +1 -1
- package/dist/runner.js +5 -12
- package/dist/runner.js.map +1 -1
- package/docs/SPECIFICATION.md +22 -535
- package/package.json +2 -11
- package/skills/nia-teams-claude-code/SKILL.md +18 -40
- package/.claude-plugin/marketplace.json +0 -20
- package/.claude-plugin/plugin.json +0 -22
- package/.mcp.json +0 -5
- package/CLAUDE.md +0 -71
- package/dist/bridge-client.d.ts +0 -1
- package/dist/bridge-client.js +0 -2
- package/dist/bridge-client.js.map +0 -1
- package/dist/channel-server.d.ts +0 -48
- package/dist/channel-server.js +0 -269
- package/dist/channel-server.js.map +0 -1
- package/dist/crypto.d.ts +0 -1
- package/dist/crypto.js +0 -2
- package/dist/crypto.js.map +0 -1
- package/dist/http.d.ts +0 -1
- package/dist/http.js +0 -2
- package/dist/http.js.map +0 -1
- package/dist/prompt.d.ts +0 -2
- package/dist/prompt.js +0 -4
- package/dist/prompt.js.map +0 -1
- package/dist/publications.d.ts +0 -1
- package/dist/publications.js +0 -2
- package/dist/publications.js.map +0 -1
- package/dist/stdio.d.ts +0 -2
- package/dist/stdio.js +0 -45
- package/dist/stdio.js.map +0 -1
- package/docs/DAEMON.md +0 -15
- package/examples/embedded.mjs +0 -8
package/docs/SPECIFICATION.md
CHANGED
|
@@ -1,555 +1,42 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Claude Code SDK daemon runtime contract
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The adapter supplies a Claude Code runner to core `SessionHost`. Pairing, credentials, signing, WebSocket delivery, state, confirmation verification, and publication retries follow [core Agent Bridge v3](../../core/docs/SPECIFICATION.md).
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## SDK and executable contract
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
The server URL is an HTTP(S) origin without credentials, path, query, or fragment. JSON POST requests use `Content-Type: application/json`; GET requests carry no body. HTTP redirects are rejected. Requests use a 15-second timeout combined with any caller `AbortSignal`; non-2xx responses raise `BridgeHttpError`.
|
|
10
|
-
|
|
11
|
-
### 1.2 Start & Browser Approval
|
|
12
|
-
|
|
13
|
-
The host generates an Ed25519 keypair (SPKI public PEM, PKCS#8 private PEM) and a 32-byte random `registrationNonce` encoded as unpadded `base64url`.
|
|
14
|
-
|
|
15
|
-
`POST /api/agent-bridge/pairing/start`:
|
|
16
|
-
|
|
17
|
-
```json
|
|
18
|
-
{
|
|
19
|
-
"publicKey": "-----BEGIN PUBLIC KEY-----\n<SPKI base64>\n-----END PUBLIC KEY-----",
|
|
20
|
-
"hostLabel": "claude-code@build-server",
|
|
21
|
-
"registrationNonce": "<32 random bytes, base64url>"
|
|
22
|
-
}
|
|
23
|
-
```
|
|
24
|
-
|
|
25
|
-
Response:
|
|
26
|
-
|
|
27
|
-
```json
|
|
28
|
-
{
|
|
29
|
-
"pairingId": "<opaque pairing reference>",
|
|
30
|
-
"pairingCode": "A7F39C2B",
|
|
31
|
-
"verificationUrl": "https://nia-teams.com/bridge/agent-pair/A7F39C2B"
|
|
32
|
-
}
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
The browser route `${origin}/bridge/agent-pair/${pairingCode}` creates and binds a new external Agent in one step (the signed-in creator becomes `owner`, and assigning an organization requires membership in that organization) or rebinds an existing external Agent administered by an `owner` or `admin`. Completing a rebind or unpairing on Nia Teams increments `keyGeneration`, and completing a rebind, unpairing, or archiving closes active connections with WebSocket close code `4401`; cloud native Agents are isolated and cannot be bound.
|
|
36
|
-
|
|
37
|
-
`GET /api/agent-bridge/pairing/status?reference=<URL-encoded pairingId>` returns `status` in `"pending" | "approved" | "paired" | "expired"`:
|
|
38
|
-
|
|
39
|
-
```json
|
|
40
|
-
{
|
|
41
|
-
"status": "approved",
|
|
42
|
-
"pairingId": "<opaque pairing reference>",
|
|
43
|
-
"teamId": "65f000000000000000000002",
|
|
44
|
-
"approvedByUserId": "65f000000000000000000001"
|
|
45
|
-
}
|
|
46
|
-
```
|
|
47
|
-
|
|
48
|
-
While `"pending"`, the client polls every 2s by default (`timeoutMs` defaults to `600000`). `"approved"` supplies the `teamId` and `approvedByUserId` bound in the registration signature; `"paired"` and `"expired"` reject.
|
|
49
|
-
|
|
50
|
-
### 1.3 Registration Proof & Completion
|
|
51
|
-
|
|
52
|
-
The host signs the UTF-8 bytes of the following LF-separated payload (no trailing newline) using raw Ed25519 (`crypto.sign(null, Buffer.from(payload, 'utf8'), privateKeyPem)`) and encodes the signature as standard `base64`:
|
|
53
|
-
|
|
54
|
-
```text
|
|
55
|
-
nia-agent-bridge-register-v1\n${pairingId}\n${teamId}\n${registrationNonce}\n${approvedByUserId}
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
`POST /api/agent-bridge/pairing/complete`:
|
|
59
|
-
|
|
60
|
-
```json
|
|
61
|
-
{
|
|
62
|
-
"pairingReference": "<original pairingId>",
|
|
63
|
-
"signature": "<Ed25519 signature, base64>"
|
|
64
|
-
}
|
|
65
|
-
```
|
|
66
|
-
|
|
67
|
-
Response:
|
|
68
|
-
|
|
69
|
-
```json
|
|
70
|
-
{
|
|
71
|
-
"ok": true,
|
|
72
|
-
"teamId": "65f000000000000000000002",
|
|
73
|
-
"agentSlug": "claude-host",
|
|
74
|
-
"agentName": "claude-host",
|
|
75
|
-
"issuer": "https://nia-teams.com",
|
|
76
|
-
"keyGeneration": 1
|
|
77
|
-
}
|
|
78
|
-
```
|
|
79
|
-
|
|
80
|
-
The client verifies `ok === true` and `completed.teamId === status.teamId` before persisting `credentials.json`.
|
|
81
|
-
|
|
82
|
-
### 1.4 Challenge & Single-Use Lease
|
|
83
|
-
|
|
84
|
-
On each WebSocket connection attempt, the host requests a challenge:
|
|
85
|
-
|
|
86
|
-
`POST /api/agent-bridge/challenge`:
|
|
87
|
-
|
|
88
|
-
```json
|
|
89
|
-
{ "teamId": "65f000000000000000000002" }
|
|
90
|
-
```
|
|
91
|
-
|
|
92
|
-
Response (`Challenge`):
|
|
93
|
-
|
|
94
|
-
```json
|
|
95
|
-
{
|
|
96
|
-
"challengeId": "<opaque challenge ID>",
|
|
97
|
-
"teamId": "65f000000000000000000002",
|
|
98
|
-
"keyGeneration": 1,
|
|
99
|
-
"nonce": "<server nonce>",
|
|
100
|
-
"expiresInSeconds": 120
|
|
101
|
-
}
|
|
102
|
-
```
|
|
103
|
-
|
|
104
|
-
The client checks `teamId` and `keyGeneration` against `credentials.json`, then signs the UTF-8 bytes of the following LF-separated payload (no trailing newline, decimal `keyGeneration`, standard `base64` output):
|
|
105
|
-
|
|
106
|
-
```text
|
|
107
|
-
nia-agent-bridge-auth-v1\n${challengeId}\n${teamId}\n${keyGeneration}\n${nonce}
|
|
108
|
-
```
|
|
109
|
-
|
|
110
|
-
`POST /api/agent-bridge/lease`:
|
|
111
|
-
|
|
112
|
-
```json
|
|
113
|
-
{
|
|
114
|
-
"teamId": "65f000000000000000000002",
|
|
115
|
-
"challengeId": "<opaque challenge ID>",
|
|
116
|
-
"signature": "<Ed25519 signature, base64>"
|
|
117
|
-
}
|
|
118
|
-
```
|
|
119
|
-
|
|
120
|
-
Response (`Lease`):
|
|
121
|
-
|
|
122
|
-
```json
|
|
123
|
-
{
|
|
124
|
-
"lease": "<single-use opaque WebSocket lease>",
|
|
125
|
-
"expiresInSeconds": 60,
|
|
126
|
-
"gatewayUrl": "wss://nia-teams.com/ws/agent-bridge",
|
|
127
|
-
"issuer": "https://nia-teams.com"
|
|
128
|
-
}
|
|
129
|
-
```
|
|
130
|
-
|
|
131
|
-
The client verifies `lease.issuer === credentials.issuer` and checks that `gatewayUrl` uses the paired origin's host, pathname `/ws/agent-bridge`, and matching scheme (`wss:` for `https:`, `ws:` for `http:`) without credentials, query, or fragment.
|
|
132
|
-
|
|
133
|
-
### 1.5 Host Credentials File (`credentials.json`)
|
|
134
|
-
|
|
135
|
-
Default directory precedence: explicit `configDir`, `NIA_CLAUDE_CONFIG_DIR`, `~/.config/nia-teams-claude-code`.
|
|
136
|
-
|
|
137
|
-
```json
|
|
138
|
-
{
|
|
139
|
-
"serverUrl": "https://nia-teams.com",
|
|
140
|
-
"teamId": "65f000000000000000000002",
|
|
141
|
-
"agentSlug": "claude-host",
|
|
142
|
-
"agentName": "claude-host",
|
|
143
|
-
"issuer": "https://nia-teams.com",
|
|
144
|
-
"keyGeneration": 1,
|
|
145
|
-
"hostLabel": "claude-code@build-server",
|
|
146
|
-
"publicKeyPem": "<Ed25519 SPKI PEM>",
|
|
147
|
-
"privateKeyPem": "<Ed25519 PKCS#8 PEM>",
|
|
148
|
-
"pairedAt": "2026-11-03T00:00:00.000Z"
|
|
149
|
-
}
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
`saveCredentials` and `loadCredentials` reject the filesystem root itself as `configDir`; for a path with more than one component, only an existing first component in the case-sensitive set `var`, `tmp`, `etc`, `home`, `Users`, `workspace` can be resolved as the base, and only when it is a non-symlink directory or a symlink with verifiable POSIX `lstat.uid === 0` whose `realpath` target is also a root-owned directory; otherwise traversal starts at the filesystem root, with every subsequent component checked using `lstat` and every symlink rejected. `HOME`/`TMPDIR` never define an exemption. `saveCredentials` creates missing segments individually, requires the requested directory itself to be a regular directory, sets its POSIX mode to `0700`, rejects an existing symlink or non-regular `credentials.json` before writing and immediately before atomic rename, and writes the temporary file exclusively with mode `0600`; `loadCredentials` applies the same path checks without creating or chmodding anything. These portable path checks do not replace OS-level isolation against concurrent directory replacement by an attacker with write access to an ancestor. `loadCredentials` checks `lstat(path).isFile()` (which rejects symlinks and non-regular files) and requires no POSIX group/other permission bits (`(mode & 0o077) === 0`), validates all fields, and verifies that `publicKeyPem` matches the public key derived from `privateKeyPem`.
|
|
153
|
-
|
|
154
|
-
## 2. WebSocket Transport (`/ws/agent-bridge`, `protocolVersion: 2`)
|
|
155
|
-
|
|
156
|
-
### 2.1 Handshake & Heartbeat
|
|
157
|
-
|
|
158
|
-
Immediately after opening `gatewayUrl`, the client sends:
|
|
159
|
-
|
|
160
|
-
```json
|
|
161
|
-
{
|
|
162
|
-
"type": "hello",
|
|
163
|
-
"protocolVersion": 2,
|
|
164
|
-
"teamId": "65f000000000000000000002",
|
|
165
|
-
"lease": "<single-use lease>",
|
|
166
|
-
"hostLabel": "claude-code@build-server"
|
|
167
|
-
}
|
|
168
|
-
```
|
|
169
|
-
|
|
170
|
-
First server frame (`ReadyFrame`):
|
|
171
|
-
|
|
172
|
-
```json
|
|
173
|
-
{
|
|
174
|
-
"type": "ready",
|
|
175
|
-
"protocolVersion": 2,
|
|
176
|
-
"systemPrompt": "Server collaboration policy",
|
|
177
|
-
"tools": [
|
|
178
|
-
{ "name": "send_message", "description": "Publish a reply", "inputSchema": { "type": "object", "properties": { "content": { "type": "string" } }, "required": ["content"] } },
|
|
179
|
-
{ "name": "chat_history", "description": "Read earlier messages", "inputSchema": { "type": "object" } }
|
|
180
|
-
],
|
|
181
|
-
"connectionGeneration": "<opaque connection generation>",
|
|
182
|
-
"agent": {
|
|
183
|
-
"teamId": "65f000000000000000000002",
|
|
184
|
-
"slug": "claude-host",
|
|
185
|
-
"name": "claude-host",
|
|
186
|
-
"orgName": "Acme"
|
|
187
|
-
},
|
|
188
|
-
"issuer": "https://nia-teams.com"
|
|
189
|
-
}
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
`BridgeClient.getContract()` exposes the latest `systemPrompt` and `tools`. The server owns collaboration policy, Rich HTML instructions, tool descriptions/schemas, and prompt formatting.
|
|
193
|
-
|
|
194
|
-
The client validates `protocolVersion === 2`, `agent.teamId === credentials.teamId`, `issuer === credentials.issuer`, and initializes the RS256 confirmation verifier with `${credentials.serverUrl}/oauth2/jwks`.
|
|
195
|
-
|
|
196
|
-
Frames are UTF-8 JSON text objects up to 512 KiB (`512 * 1024` bytes). Handshake and `ready` each enforce a 15s timeout. Once ready, the client sends a heartbeat every 20s and closes the socket if no valid version-2 frame arrives within 60s:
|
|
197
|
-
|
|
198
|
-
```json
|
|
199
|
-
{ "type": "heartbeat", "protocolVersion": 2, "at": 1793664000000 }
|
|
200
|
-
```
|
|
201
|
-
|
|
202
|
-
| Close code | Meaning | Client behavior |
|
|
203
|
-
| --- | --- | --- |
|
|
204
|
-
| `4400` | Invalid frame or protocol violation | Disconnect and reconnect with backoff |
|
|
205
|
-
| `4401` | Unauthorized, key rotated, or unpaired | Disconnect and reconnect with backoff |
|
|
206
|
-
| `4408` | Hello handshake timeout | Disconnect and reconnect with backoff |
|
|
207
|
-
| `4409` | Superseded by a newer host connection | Terminal `close()`; stop reconnecting |
|
|
208
|
-
|
|
209
|
-
Reconnect backoff starts at 1s and doubles up to a 30s base cap with jitter in `[0.75, 1.25)`, resetting upon `ready`.
|
|
210
|
-
|
|
211
|
-
### 2.2 Deterministic Thread Identity
|
|
7
|
+
Inspected npm `@anthropic-ai/claude-agent-sdk@0.3.319`; package metadata is retained in `upstream/`. SDK archive SHA256:
|
|
212
8
|
|
|
213
9
|
```text
|
|
214
|
-
|
|
215
|
-
= "nia-gc-" + base64url(SHA256(UTF8(groupChatId + ":" + teamId))).slice(0, 24)
|
|
216
|
-
```
|
|
217
|
-
|
|
218
|
-
`agentThreadId` identifies the stable bridge thread for `(groupChatId, teamId)`. Nia `sessionId` identifies the current execution segment on Nia Teams; outbound RPCs and publication retries pass `sessionId`. Every inbound push frame must carry `agentThreadId === stableExternalAgentThreadId(groupChatId, teamId)`.
|
|
219
|
-
|
|
220
|
-
## 3. Server-to-Host Push Frames & Delivery Acknowledgment
|
|
221
|
-
|
|
222
|
-
All push frames share `PushBase`:
|
|
223
|
-
|
|
224
|
-
```ts
|
|
225
|
-
interface PushBase {
|
|
226
|
-
protocolVersion: 2;
|
|
227
|
-
deliveryId: string;
|
|
228
|
-
groupChatId: string; // 24-hex
|
|
229
|
-
sessionId: string; // 24-hex Nia session ID
|
|
230
|
-
agentThreadId: string; // stableExternalAgentThreadId(groupChatId, teamId)
|
|
231
|
-
}
|
|
232
|
-
```
|
|
233
|
-
|
|
234
|
-
### 3.1 `thread.message`
|
|
235
|
-
|
|
236
|
-
```ts
|
|
237
|
-
interface ThreadMessage extends PushBase {
|
|
238
|
-
type: 'thread.message';
|
|
239
|
-
prompt?: string; // server-formatted collaboration input
|
|
240
|
-
reason: 'message' | 'joined';
|
|
241
|
-
groupChat: {
|
|
242
|
-
title: string;
|
|
243
|
-
url: string;
|
|
244
|
-
members: Array<{
|
|
245
|
-
kind: 'human' | 'agent'; id: string; name: string; orgName?: string;
|
|
246
|
-
}>;
|
|
247
|
-
};
|
|
248
|
-
invokedBy?: { userId?: string; userName: string };
|
|
249
|
-
triggerMessageId: string;
|
|
250
|
-
messages: Array<{
|
|
251
|
-
id: string;
|
|
252
|
-
kind: 'human' | 'agent' | 'system';
|
|
253
|
-
authorId?: string;
|
|
254
|
-
authorName: string;
|
|
255
|
-
replyToMessageId?: string;
|
|
256
|
-
content: string;
|
|
257
|
-
createdAt: string;
|
|
258
|
-
attachments?: Array<{
|
|
259
|
-
name: string; mimeType: string; size: number; url: string; transcript?: string;
|
|
260
|
-
}>;
|
|
261
|
-
}>;
|
|
262
|
-
}
|
|
10
|
+
6bfb9ccb6a5d15686f5c7dd12d7a7da6d7b486ca6e1331ac8a7ab98a2d302001
|
|
263
11
|
```
|
|
264
12
|
|
|
265
|
-
|
|
13
|
+
`createClaudeRunner({ cwd, model?, fullAuto?, claudeBin? })` calls `query({ prompt, options })`. Executable discovery searches `claude` on PATH and common installation paths; `claudeBin` or `CLAUDE_BIN` selects an explicit path. A locally authenticated Claude Code CLI is required; Nia Teams pairing does not provide model authentication.
|
|
266
14
|
|
|
267
|
-
|
|
15
|
+
- `pathToClaudeCodeExecutable` selects the CLI; `cwd`, `model`, `resume`, and `abortController` configure each query.
|
|
16
|
+
- The SDK launches stream-json input/output with `--verbose`, `--permission-prompt-tool=stdio`, and `--resume=<sessionId>` for resumed queries. Initialize negotiates SDK tool servers and manifests.
|
|
17
|
+
- The SDK recognizes `.js` / `.mjs` entries. For Windows `.cmd` / `.bat` wrappers and `.cjs` entries, the adapter supplies `spawnClaudeCodeProcess`, using core `executableCommand` and Node `spawn` with piped stdio. Prompts stay on SDK stdin, not shell command lines.
|
|
18
|
+
- `settingSources: ['user', 'project', 'local']` retains local settings. `systemPrompt: { type: 'preset', preset: 'claude_code', append: context.systemPrompt }` preserves the Claude Code preset and adds server collaboration instructions.
|
|
19
|
+
- `strictMcpConfig: true` loads only the supplied scoped `nia` tool server. A low-level MCP `Server` serves every `ready.tools` entry with its raw JSON Schema. The SDK connects its `instance` through `.connect(transport)`. Tools without `deferLoading: true` carry `_meta: { "anthropic/alwaysLoad": true }`; deferred entries omit that metadata and use Claude Code native ToolSearch, including its model-dependent full-loading behavior. No custom search or meta-tool is registered. Calls delegate to `context.callTool` and the unified `tool.call` RPC; MCP text uses `result.content` verbatim and preserves `isError`.
|
|
20
|
+
- `permissionMode` is `default`; `fullAuto` selects `bypassPermissions` and `allowDangerouslySkipPermissions: true`. Existing allow rules and hooks may resolve requests before the SDK callback.
|
|
268
21
|
|
|
269
|
-
|
|
270
|
-
interface CardAction extends PushBase {
|
|
271
|
-
type: 'card.action';
|
|
272
|
-
cardId: string; // starts with `agent_bridge:${teamId}:`
|
|
273
|
-
decision: 'approved' | 'canceled';
|
|
274
|
-
clickedBy: {
|
|
275
|
-
userId: string; name: string; teamRole?: 'owner' | 'admin' | 'member';
|
|
276
|
-
};
|
|
277
|
-
_meta?: Record<string, unknown>; // carries nia/confirmationToken when decision === 'approved'
|
|
278
|
-
}
|
|
279
|
-
```
|
|
280
|
-
|
|
281
|
-
### 3.3 `thread.cancel`
|
|
282
|
-
|
|
283
|
-
```ts
|
|
284
|
-
interface ThreadCancel extends PushBase {
|
|
285
|
-
type: 'thread.cancel';
|
|
286
|
-
reason: 'user_aborted' | 'removed_from_group';
|
|
287
|
-
}
|
|
288
|
-
```
|
|
289
|
-
|
|
290
|
-
### 3.4 Delivery Acknowledgment & Deduplication
|
|
291
|
-
|
|
292
|
-
When all registered push handlers for an inbound frame resolve, the client sends:
|
|
293
|
-
|
|
294
|
-
```json
|
|
295
|
-
{
|
|
296
|
-
"type": "ack",
|
|
297
|
-
"protocolVersion": 2,
|
|
298
|
-
"sessionId": "65f000000000000000000003",
|
|
299
|
-
"deliveryId": "<deliveryId>"
|
|
300
|
-
}
|
|
301
|
-
```
|
|
302
|
-
|
|
303
|
-
If no handler is registered for that push type or a handler throws, no `ack` is sent. Accepted deliveries are deduplicated in an insertion-ordered cache of `(sessionId, deliveryId)` (default 2,000 entries); duplicate deliveries already accepted on the process re-send `ack` without re-running handlers.
|
|
304
|
-
|
|
305
|
-
## 4. Host-to-Server RPC
|
|
306
|
-
|
|
307
|
-
### 4.1 Request & Response Envelopes
|
|
308
|
-
|
|
309
|
-
Request (`rpc.request`, default 30s timeout):
|
|
310
|
-
|
|
311
|
-
```json
|
|
312
|
-
{
|
|
313
|
-
"type": "rpc.request",
|
|
314
|
-
"protocolVersion": 2,
|
|
315
|
-
"requestId": "<UUID>",
|
|
316
|
-
"method": "group_chat.history",
|
|
317
|
-
"params": { "sessionId": "65f000000000000000000003", "limit": 50, "offset": 0 }
|
|
318
|
-
}
|
|
319
|
-
```
|
|
320
|
-
|
|
321
|
-
Success response (`rpc.response`):
|
|
322
|
-
|
|
323
|
-
```json
|
|
324
|
-
{
|
|
325
|
-
"type": "rpc.response",
|
|
326
|
-
"protocolVersion": 2,
|
|
327
|
-
"requestId": "<same UUID>",
|
|
328
|
-
"ok": true,
|
|
329
|
-
"result": { "messages": [] }
|
|
330
|
-
}
|
|
331
|
-
```
|
|
332
|
-
|
|
333
|
-
Error response (`rpc.response`, raises `BridgeRpcError(code, message, retryable)`):
|
|
334
|
-
|
|
335
|
-
```json
|
|
336
|
-
{
|
|
337
|
-
"type": "rpc.response",
|
|
338
|
-
"protocolVersion": 2,
|
|
339
|
-
"requestId": "<same UUID>",
|
|
340
|
-
"ok": false,
|
|
341
|
-
"error": { "code": "invalid_request", "message": "Invalid parameters", "retryable": false }
|
|
342
|
-
}
|
|
343
|
-
```
|
|
344
|
-
|
|
345
|
-
Turn completion sends `thread.activity` with `state: 'idle'` and the processed `deliveryId`, without reply content. Model-facing `send_message` and `chat_history` map to transport RPCs `group_chat.send_message` and `group_chat.history`. Terminal output and SDK results are not publications.
|
|
346
|
-
|
|
347
|
-
### 4.2 RPC Methods
|
|
348
|
-
|
|
349
|
-
| Method | Parameters (`params`) | Description |
|
|
350
|
-
| --- | --- | --- |
|
|
351
|
-
| `group_chat.send_message` | `sessionId`, `content: string`, `toolCallId: string` | Publish a message to the GroupChat (`toolCallId` provides server-side idempotency) |
|
|
352
|
-
| `group_chat.history` | `sessionId`, `limit: number` (`1..100`), `offset: number` (`>= 0`) | Read earlier GroupChat messages |
|
|
353
|
-
| `card.upsert` | `sessionId`, `toolCallId`, `cardId`, `title`, `subtitle`, `description?`, `actionLabel: "允许执行"`, `verifyToolName`, `verifyArguments` | Create or update a pending TaskBar confirmation card |
|
|
354
|
-
| `card.cancel` | `sessionId`, `cardId: string` | Cancel a pending TaskBar card |
|
|
355
|
-
| `thread.activity` | `sessionId`, `state: "executing" \| "waiting" \| "idle"`, `label?: string`, `errorMessage?: string`, `deliveryId?: string` | Update live Agent activity status in the GroupChat |
|
|
356
|
-
|
|
357
|
-
Permission card identifiers use the namespace and request binding defined below.
|
|
358
|
-
|
|
359
|
-
- Permission relay uses `verifyToolName: "claude_code.permission"` and exact `verifyArguments` as defined in section 6.
|
|
360
|
-
- `cardId` uses namespace `agent_bridge:${teamId}:${agentThreadId}:perm:${request_id}:${randomUUID().slice(0, 8)}` (maximum 200 characters).
|
|
361
|
-
|
|
362
|
-
### 4.3 Publication Queue
|
|
363
|
-
|
|
364
|
-
The queue buffers explicitly published replies (random UUID `toolCallId`) across transient disconnects: FIFO, at most 256 entries / 16 MiB, rejected before admission if full. Individual frames including envelope overhead must fit 512 KiB. Ready events and 2-second transient-error retries flush the queue. Accepted content is not evicted. Send acknowledgments prevent resending content when only activity synchronization fails. A non-retryable RPC error rejects the entry. This is process-local, not durable storage.
|
|
365
|
-
|
|
366
|
-
## 5. TaskBar Confirmation Token (`_meta["nia/confirmationToken"]`)
|
|
367
|
-
|
|
368
|
-
### 5.1 Verification Rules
|
|
369
|
-
|
|
370
|
-
When a member clicks **允许执行** on a TaskBar card, Nia Teams verifies that the clicker is an active member (`owner`, `admin`, or `member`) of the external Agent, signs an RS256 confirmation JWT, and delivers `card.action` with `decision: "approved"`, `clickedBy: { userId, name, teamRole }`, and `_meta["nia/confirmationToken"]`.
|
|
371
|
-
|
|
372
|
-
The host verifies `_meta` via `verifyHumanActionContext(action._meta, { server: 'agent-bridge', tool: verifyToolName, arguments: verifyArguments, expectedCardId: cardId })` from `@nia-teams/mcp-sdk/auth`:
|
|
373
|
-
|
|
374
|
-
| Claim | Verification rule |
|
|
375
|
-
| --- | --- |
|
|
376
|
-
| `iss` | Matches paired `credentials.issuer` |
|
|
377
|
-
| `aud` | `"nia-teams-workload"` |
|
|
378
|
-
| `sub` | `"nia-teams-platform"` |
|
|
379
|
-
| `principal_type` | `"service"` |
|
|
380
|
-
| `human_confirmed` | `true` |
|
|
381
|
-
| `confirmed_by` | Non-blank 24-hex user ID of the confirming member |
|
|
382
|
-
| `confirmed_by_name` | Non-blank display name of the confirming member |
|
|
383
|
-
| `confirmation_card_id` | Matches pending `cardId` |
|
|
384
|
-
| `context_server` | `"agent-bridge"` |
|
|
385
|
-
| `context_tool` | `"claude_code.permission"` |
|
|
386
|
-
| `context_arguments_sha256` | `canonicalJsonSha256(verifyArguments)` |
|
|
387
|
-
| `iat`, `exp`, `jti` | `iat <= now < exp`, token lifetime and age `<= 300s`, non-blank `jti` |
|
|
388
|
-
|
|
389
|
-
### 5.2 Canonical JSON Digest (`canonicalJsonSha256`)
|
|
390
|
-
|
|
391
|
-
1. Primitives (`string`, `boolean`, `null`, finite `number`) serialize via `JSON.stringify` (`-0` serializes as `"0"`).
|
|
392
|
-
2. Dense arrays serialize in index order.
|
|
393
|
-
3. Plain objects serialize with own enumerable string keys sorted in UTF-16 code-unit order (`Array.prototype.sort()`) with no whitespace.
|
|
394
|
-
4. `undefined`, non-finite numbers, `bigint`, symbols, functions, class instances, sparse arrays, and circular references throw `TypeError`.
|
|
395
|
-
|
|
396
|
-
### 5.3 Approval Outcomes
|
|
397
|
-
|
|
398
|
-
Only a verified approved action allows the pending host request. Canceled or invalid confirmations deny it. Ordinary chat text never authorizes tools. The plugin does not infer approval from `clickedBy` role fields. Nia Teams enforces external Agent membership (`owner` / `admin` / `member`) before issuing confirmation tokens; these human roles are distinct from workload identity `sub`, organization scope, or `role:*` claims.
|
|
399
|
-
|
|
400
|
-
## 6. Claude Code Channel Mapping
|
|
22
|
+
## Sessions, publications, and cancellation
|
|
401
23
|
|
|
402
|
-
|
|
24
|
+
`SessionHost` persists each GroupChat's SDK `session_id` in private `threads.json` and supplies it as `resume` on later turns. Credentials live separately in `credentials.json`. Chats have separate model contexts but share the workspace and local tools. Core serializes turns within a chat and queues incoming messages; session rotation aborts the old query and clears old inputs.
|
|
403
25
|
|
|
404
|
-
|
|
26
|
+
SDK system, assistant, and result events update session state and activity. Success has `type: "result"`, `subtype: "success"`, and `result: string`; errors carry `is_error` and `errors`. Subagent assistant messages and result text are not published as GroupChat replies. Every reply uses explicit `send_message({ content })`; `chat_history({ limit?, offset? })` reads the active chat. The host supplies destination and session context.
|
|
405
27
|
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
```json
|
|
409
|
-
{
|
|
410
|
-
"tools": {},
|
|
411
|
-
"experimental": {
|
|
412
|
-
"claude/channel": {},
|
|
413
|
-
"claude/channel/permission": {}
|
|
414
|
-
}
|
|
415
|
-
}
|
|
416
|
-
```
|
|
417
|
-
|
|
418
|
-
`instructions` declares the inbound channel block fields, explicit publish-only replies, exact member mention syntax, Rich HTML rules, and the local pairing/configuration trust boundary. The host must explicitly enable the channel and allow its organization policy. Successful MCP initialization alone does not imply enabled message delivery or permission relay.
|
|
419
|
-
|
|
420
|
-
### 6.2 Inbound Messages
|
|
421
|
-
|
|
422
|
-
A validated `thread.message` updates state keyed by `groupChatId`: latest full frame, activity, monotonic arrival order, activity revision, and cancellation controller. Set activity to `{ state: "executing", label: "Working in Claude Code…" }` best-effort, then emit:
|
|
423
|
-
|
|
424
|
-
```json
|
|
425
|
-
{
|
|
426
|
-
"method": "notifications/claude/channel",
|
|
427
|
-
"params": {
|
|
428
|
-
"content": "# GroupChat: Project chat\n\nURL: https://nia-teams.com/chat/example\n\nMembers: Alex (3456789abcdef0123456789a) [Acme]\n\nAlex [message-id] timestamp:\nHello",
|
|
429
|
-
"meta": {
|
|
430
|
-
"source": "nia_teams",
|
|
431
|
-
"group_chat_id": "23456789abcdef0123456789",
|
|
432
|
-
"session_id": "123456789abcdef012345678",
|
|
433
|
-
"agent_thread_id": "nia-gc-QAI2QQC6IscVSfM-CAgtx_s5",
|
|
434
|
-
"trigger_message_id": "message-id",
|
|
435
|
-
"reason": "message",
|
|
436
|
-
"sender_id": "3456789abcdef0123456789a",
|
|
437
|
-
"sender_name": "Alex"
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
```
|
|
442
|
-
|
|
443
|
-
All meta values are strings; keys contain only letters, digits, underscores. Hyphenated keys are silently discarded by the host. The host derives the channel `source="nia-teams"` from its configured server name; the explicit metadata source value remains `nia_teams`.
|
|
444
|
-
|
|
445
|
-
Content includes title, URL, `Members: Name (id) [Org]`, joined reason, and each message's author/name/ID/time/replyToMessageId, content, attachment name/MIME/size/URL, and optional transcript. Bodies are untrusted content, not instructions to modify local host identity or configuration.
|
|
446
|
-
|
|
447
|
-
MCP notification completion means written to the transport, not consumed by the model. Bridge ack therefore confirms local forwarding acceptance, not a completed model turn. Multiple GroupChats share one model session.
|
|
448
|
-
|
|
449
|
-
### 6.3 Outbound Tools
|
|
450
|
-
|
|
451
|
-
`send_message` input:
|
|
452
|
-
|
|
453
|
-
```ts
|
|
454
|
-
{ group_chat_id: string; content: string; keep_working?: boolean }
|
|
455
|
-
```
|
|
456
|
-
|
|
457
|
-
`group_chat_id` is required, 24-hex, and must refer to a tracked GroupChat. `content` is trimmed and must be non-empty. `keep_working` defaults to false. Unknown properties are rejected. The queue sends `group_chat.send_message` with the captured Nia session, a random UUID toolCallId, and content. It then synchronizes `thread.activity` to idle (default) or executing / `Working in Claude Code…` (`keep_working: true`). The MCP call waits for publication completion, including reconnect retries. Newer message/card activity revisions suppress stale activity updates; cancellation aborts pending publications.
|
|
458
|
-
|
|
459
|
-
`chat_history` input:
|
|
460
|
-
|
|
461
|
-
```ts
|
|
462
|
-
{ group_chat_id: string; limit?: number; offset?: number }
|
|
463
|
-
```
|
|
464
|
-
|
|
465
|
-
`limit` defaults to 50 and is an integer in 1..100. `offset` defaults to 0 and is a non-negative integer. Calls `group_chat.history` with the current tracked Nia session. Returns result.text if provided, otherwise serialized result JSON. Validation/RPC failures return MCP tool `isError: true` with a text explanation. Terminal assistant text is never automatically published.
|
|
466
|
-
|
|
467
|
-
### 6.4 Permission Requests and Routing
|
|
468
|
-
|
|
469
|
-
Host-to-plugin notification:
|
|
470
|
-
|
|
471
|
-
```json
|
|
472
|
-
{
|
|
473
|
-
"method": "notifications/claude/channel/permission_request",
|
|
474
|
-
"params": {
|
|
475
|
-
"request_id": "abcde",
|
|
476
|
-
"tool_name": "Bash",
|
|
477
|
-
"description": "Run tests",
|
|
478
|
-
"input_preview": "{\"command\":\"npm test\"}"
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
```
|
|
482
|
-
|
|
483
|
-
All fields are strings. `request_id` is trimmed, non-empty, and limited to 128 characters to bound the card identifier (the resulting card ID is separately checked against 200). Hosts typically issue five `[a-km-z]` letters; the bridge does not require that alphabet. Request IDs are processed at most once during the process lifetime. `tool_name` is non-empty. Description and preview are untrusted display strings; preview is not parsed as executable code.
|
|
484
|
-
|
|
485
|
-
There is no GroupChat identifier in this notification. Select the tracked executing thread with greatest inbound arrival order; if none is executing, use the most recently triggered tracked GroupChat. If none exists, log to stderr and skip card creation, leaving the local terminal approval untouched. Routing is a heuristic, not model-session isolation.
|
|
486
|
-
|
|
487
|
-
Capture `(groupChatId, sessionId, agentThreadId, cardId)` before awaiting any RPC. Create:
|
|
488
|
-
|
|
489
|
-
```ts
|
|
490
|
-
const verifyArguments = {
|
|
491
|
-
agentThreadId,
|
|
492
|
-
requestId: request_id,
|
|
493
|
-
toolName: tool_name,
|
|
494
|
-
description,
|
|
495
|
-
inputPreview: input_preview,
|
|
496
|
-
};
|
|
497
|
-
// RPC method: card.upsert
|
|
498
|
-
{
|
|
499
|
-
sessionId,
|
|
500
|
-
toolCallId: `perm:${request_id}`,
|
|
501
|
-
cardId: `agent_bridge:${teamId}:${agentThreadId}:perm:${request_id}:${uuidPrefix}`,
|
|
502
|
-
title: `Allow ${tool_name}?`,
|
|
503
|
-
subtitle: description || `Claude Code requested permission to run ${tool_name}.`,
|
|
504
|
-
// description: input_preview, only when non-empty
|
|
505
|
-
actionLabel: '允许执行',
|
|
506
|
-
verifyToolName: 'claude_code.permission',
|
|
507
|
-
verifyArguments,
|
|
508
|
-
}
|
|
509
|
-
```
|
|
510
|
-
|
|
511
|
-
`uuidPrefix` is the first eight characters of a random UUID. The request upsert has a 5-second local timeout; an uncertain upsert triggers best-effort cancellation and deny. A pending wait is registered before sending, so fast actions are not lost. Pending cards expire after five minutes, cancel remotely and deny. Activity becomes waiting / `等待确认` after upsert unless the wait already settled.
|
|
512
|
-
|
|
513
|
-
### 6.5 Card Verification and Verdicts
|
|
514
|
-
|
|
515
|
-
An action must match all four captured identity fields. A mismatched/unknown action is ignored. For approved actions:
|
|
516
|
-
|
|
517
|
-
```ts
|
|
518
|
-
await bridge.verifyCardApproval(action._meta, {
|
|
519
|
-
server: 'agent-bridge',
|
|
520
|
-
tool: 'claude_code.permission',
|
|
521
|
-
arguments: verifyArguments,
|
|
522
|
-
expectedCardId: cardId,
|
|
523
|
-
});
|
|
524
|
-
```
|
|
525
|
-
|
|
526
|
-
The signed `context_arguments_sha256` is the lowercase hex SHA-256 digest of UTF-8 canonical JSON for the exact five-field `verifyArguments` object above. `context_tool` must be `claude_code.permission`; section 5 defines the remaining RS256/JWT checks. After asynchronous verification, recheck that the same wait is still pending and not canceled before emitting allow.
|
|
527
|
-
|
|
528
|
-
Plugin-to-host verdict:
|
|
529
|
-
|
|
530
|
-
```json
|
|
531
|
-
{
|
|
532
|
-
"method": "notifications/claude/channel/permission",
|
|
533
|
-
"params": { "request_id": "abcde", "behavior": "allow" }
|
|
534
|
-
}
|
|
535
|
-
```
|
|
28
|
+
Cancellation aborts the SDK query and pending permissions. The runner removes its abort listener and closes the in-process tool server in `finally`. Core owns publication retries, atomic state persistence, connection recovery, and macOS sleep prevention. Idle activity identifies the processed delivery; server prompts own reminders for turns without a publication.
|
|
536
29
|
|
|
537
|
-
|
|
30
|
+
## Questions and signed TaskBar permissions
|
|
538
31
|
|
|
539
|
-
|
|
32
|
+
`canUseTool(name, input, detail)` returns `{ behavior: 'allow', updatedInput }` or `{ behavior: 'deny', message }`. All `mcp__nia__` collaboration tools bypass local approval because Nia Teams owns their ACLs and human-confirmation cards; other tool requests call the active `SessionHost` permission handler.
|
|
540
33
|
|
|
541
|
-
|
|
34
|
+
`AskUserQuestion` posts questions to GroupChat and waits for the invoking human. A single question accepts text; multiple questions accept a JSON object keyed by question text. Answers return in `updatedInput.answers`. Timeout or cancellation denies the request.
|
|
542
35
|
|
|
543
|
-
|
|
544
|
-
- Channel notifications cannot forcibly interrupt a local tool. The shared host session and terminal operator retain control.
|
|
545
|
-
- A sessionId rotation aborts old queued publications and permissions before storing the new context.
|
|
546
|
-
- Executing/waiting threads refresh their activity every 30 seconds, and after bridge ready. Idle threads do not renew busy leases.
|
|
547
|
-
- Channel shutdown is idempotent: stop refresh, reject pending queue entries, unsubscribe push listeners, deny and cancel pending cards, idle busy threads, close bridge and MCP. Cleanup RPCs use short AbortSignals (1 second card cancellation, 1.5 seconds activity).
|
|
548
|
-
- The stdio CLI handles stdin end/close, SIGINT, SIGTERM, SIGHUP, MCP transport close, and a 1-second destroyed/readableEnded watchdog. A 2.5-second hard deadline closes the bridge and exits even when the stdio peer disappears during cleanup.
|
|
549
|
-
- Only StdioServerTransport writes stdout. Diagnostics are stderr-only. No lease, private key, or confirmation JWT is printed by the CLI.
|
|
36
|
+
Other tool requests open signed TaskBar cards using tool `claude_code.permission` and server `agent-bridge`. Core verifies RS256 using `${issuer}/oauth2/jwks`, issuer, audience `nia-teams-workload`, lifetime, service identity, and `human_confirmed: true`. It matches `context_server`, `context_tool`, canonical-JSON argument SHA-256 digest, and `confirmation_card_id` to the locally pending card and turn. Missing/invalid tokens, dismissal, expiry, and cancellation deny the request. Chat text is not approval. Nia Teams checks the clicker's active Agent membership (`owner`, `admin`, or `member`) before signing.
|
|
550
37
|
|
|
551
38
|
## GroupChat sender identity and mentions
|
|
552
39
|
|
|
553
|
-
Incoming
|
|
40
|
+
Incoming prompts include chat title, URL, members, sender IDs, messages, reply references, and attachment transcripts. Raw `thread.message` frames use `messages[].authorId`; formatted prompts list `Alice (<userId>)` and member IDs. Generic headers may use `[chat:<chatId>] Alice (<userId>): ...`; structured message payloads may expose `senderId`.
|
|
554
41
|
|
|
555
|
-
|
|
42
|
+
Publish `<mention userId="<userId>" />` using a received sender/member ID for a native Nia Teams notification. Plain `@Name` is text, not a native mention.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nia-teams/claude-code-plugin",
|
|
3
|
-
"version": "0.2
|
|
3
|
+
"version": "0.3.2",
|
|
4
4
|
"description": "Connect Claude Code to Nia Teams GroupChats and TaskBar human approval cards",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -29,13 +29,9 @@
|
|
|
29
29
|
"files": [
|
|
30
30
|
"dist",
|
|
31
31
|
"bin",
|
|
32
|
-
".claude-plugin",
|
|
33
|
-
".mcp.json",
|
|
34
32
|
"skills",
|
|
35
33
|
"AGENTS.md",
|
|
36
|
-
"CLAUDE.md",
|
|
37
34
|
"docs",
|
|
38
|
-
"examples",
|
|
39
35
|
"README.md",
|
|
40
36
|
"README_CN.md",
|
|
41
37
|
"LICENSE"
|
|
@@ -51,16 +47,11 @@
|
|
|
51
47
|
"prepack": "npm run build"
|
|
52
48
|
},
|
|
53
49
|
"dependencies": {
|
|
54
|
-
"@
|
|
55
|
-
"@nia-teams/mcp-sdk": "^0.1.0",
|
|
56
|
-
"ws": "^8.18.0",
|
|
57
|
-
"zod": "^3.25.0 || ^4.0.0",
|
|
58
|
-
"@nia-teams/agent-bridge-core": "^0.2.0",
|
|
50
|
+
"@nia-teams/agent-bridge-core": "^0.3.2",
|
|
59
51
|
"@anthropic-ai/claude-agent-sdk": "0.3.319"
|
|
60
52
|
},
|
|
61
53
|
"devDependencies": {
|
|
62
54
|
"@types/node": "^20.19.0",
|
|
63
|
-
"@types/ws": "^8.18.0",
|
|
64
55
|
"typescript": "^5.9.3"
|
|
65
56
|
}
|
|
66
57
|
}
|