@sleep2agi/commhub-server 0.6.0 → 0.7.0-preview.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/LICENSE +202 -0
- package/README.md +5 -5
- package/bin/commhub.ts +11 -2
- package/package.json +9 -3
- package/src/db-adapter.ts +7 -9
- package/src/db.ts +79 -2
- package/src/index.ts +118 -34
- package/src/push.ts +17 -19
- package/src/tools.ts +77 -34
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
CommHub: MCP Streamable HTTP + SSE push + REST API for an AI agent network. Single-process Bun server, SQLite-backed, zero config.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
The supported path is to install the `anet` CLI (`@sleep2agi/agent-network` 2.1.0) and run `anet hub start`, which wires up port, the server token, the default account, and local config for you.
|
|
6
6
|
|
|
7
7
|
## Quick start (verified)
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
10
|
# Recommended — through the anet CLI
|
|
11
|
-
npm install -g @sleep2agi/agent-network
|
|
11
|
+
npm install -g @sleep2agi/agent-network
|
|
12
12
|
anet hub start
|
|
13
13
|
# • http://127.0.0.1:9200 by default
|
|
14
14
|
# • SQLite at ~/.commhub/commhub.db
|
|
@@ -35,9 +35,9 @@ Once running:
|
|
|
35
35
|
|
|
36
36
|
| Package | Version |
|
|
37
37
|
|---|---|
|
|
38
|
-
| [`@sleep2agi/agent-network`](https://www.npmjs.com/package/@sleep2agi/agent-network) | 2.0
|
|
39
|
-
| [`@sleep2agi/agent-network-dashboard`](https://www.npmjs.com/package/@sleep2agi/agent-network-dashboard) | 0.
|
|
40
|
-
| [`@sleep2agi/agent-node`](https://www.npmjs.com/package/@sleep2agi/agent-node) | 2.
|
|
38
|
+
| [`@sleep2agi/agent-network`](https://www.npmjs.com/package/@sleep2agi/agent-network) | 2.1.0 |
|
|
39
|
+
| [`@sleep2agi/agent-network-dashboard`](https://www.npmjs.com/package/@sleep2agi/agent-network-dashboard) | 0.3.0 |
|
|
40
|
+
| [`@sleep2agi/agent-node`](https://www.npmjs.com/package/@sleep2agi/agent-node) | 2.3.0 |
|
|
41
41
|
|
|
42
42
|
## MCP tools (18)
|
|
43
43
|
|
package/bin/commhub.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* npx @sleep2agi/commhub-server
|
|
7
7
|
* npx @sleep2agi/commhub-server --port 9200
|
|
8
8
|
* npx @sleep2agi/commhub-server --port 9200 --token my-secret
|
|
9
|
+
* npx @sleep2agi/commhub-server --dev-open
|
|
9
10
|
* npx @sleep2agi/commhub-server --db ~/.commhub/commhub.db
|
|
10
11
|
*/
|
|
11
12
|
|
|
@@ -13,9 +14,11 @@ const args = process.argv.slice(2);
|
|
|
13
14
|
|
|
14
15
|
for (let i = 0; i < args.length; i++) {
|
|
15
16
|
if (args[i] === "--port" || args[i] === "-p") process.env.PORT = args[++i];
|
|
17
|
+
if (args[i] === "--host") process.env.HOST = args[++i];
|
|
16
18
|
if (args[i] === "--token" || args[i] === "-t") process.env.COMMHUB_AUTH_TOKEN = args[++i];
|
|
17
19
|
if (args[i] === "--db") process.env.COMMHUB_DB = args[++i];
|
|
18
20
|
if (args[i] === "--cors") process.env.COMMHUB_CORS_ORIGINS = args[++i];
|
|
21
|
+
if (args[i] === "--dev-open") process.env.COMMHUB_DEV_OPEN = "1";
|
|
19
22
|
if (args[i] === "--help" || args[i] === "-h") {
|
|
20
23
|
console.log(`
|
|
21
24
|
CommHub MCP Server — AI Agent 通信中枢
|
|
@@ -25,20 +28,26 @@ Usage:
|
|
|
25
28
|
|
|
26
29
|
Options:
|
|
27
30
|
--port, -p <port> Port to listen on (default: 9200, env: PORT)
|
|
31
|
+
--host <host> Host to bind (default: 127.0.0.1, env: HOST)
|
|
28
32
|
--token, -t <token> Auth token (env: COMMHUB_AUTH_TOKEN)
|
|
29
33
|
--db <path> SQLite database path (default: ~/.commhub/commhub.db, env: COMMHUB_DB)
|
|
30
34
|
--cors <origins> CORS origins, comma-separated (env: COMMHUB_CORS_ORIGINS)
|
|
35
|
+
--dev-open Explicit unauthenticated local development mode
|
|
31
36
|
--help, -h Show this help
|
|
32
37
|
|
|
33
38
|
Environment Variables:
|
|
34
39
|
PORT Server port (default: 9200)
|
|
35
|
-
|
|
40
|
+
HOST Bind address (default: 127.0.0.1)
|
|
41
|
+
COMMHUB_AUTH_TOKEN Bearer token for authentication (required unless --dev-open)
|
|
42
|
+
COMMHUB_DEV_OPEN Set to 1 to allow unauthenticated dev mode
|
|
36
43
|
COMMHUB_DB SQLite database file path
|
|
37
44
|
COMMHUB_CORS_ORIGINS Allowed CORS origins (comma-separated)
|
|
45
|
+
COMMHUB_ENABLE_TMUX Set to 1 to enable tmux HTTP/WebSocket endpoints
|
|
46
|
+
COMMHUB_TMUX_ALLOWLIST Additional comma-separated client IPs allowed for tmux
|
|
38
47
|
|
|
39
48
|
Examples:
|
|
40
|
-
commhub-server --port 9200
|
|
41
49
|
commhub-server --port 9200 --token my-secret-token
|
|
50
|
+
commhub-server --port 9200 --dev-open
|
|
42
51
|
PORT=9200 COMMHUB_AUTH_TOKEN=secret commhub-server
|
|
43
52
|
`);
|
|
44
53
|
process.exit(0);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sleep2agi/commhub-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0-preview.0",
|
|
4
4
|
"description": "CommHub Server — AI Agent communication hub with MCP protocol, multi-network isolation, user auth, and 18 MCP tools.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "src/index.ts",
|
|
@@ -28,13 +28,19 @@
|
|
|
28
28
|
"license"
|
|
29
29
|
],
|
|
30
30
|
"author": "sleep2agi",
|
|
31
|
-
"license": "
|
|
32
|
-
"homepage": "https://anet.
|
|
31
|
+
"license": "Apache-2.0",
|
|
32
|
+
"homepage": "https://anet.sh",
|
|
33
33
|
"repository": {
|
|
34
34
|
"type": "git",
|
|
35
35
|
"url": "https://github.com/sleep2agi/agent-network",
|
|
36
36
|
"directory": "server"
|
|
37
37
|
},
|
|
38
|
+
"publishConfig": {
|
|
39
|
+
"access": "public"
|
|
40
|
+
},
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/sleep2agi/agent-network/issues"
|
|
43
|
+
},
|
|
38
44
|
"engines": {
|
|
39
45
|
"bun": ">=1.2.0"
|
|
40
46
|
},
|
package/src/db-adapter.ts
CHANGED
|
@@ -110,16 +110,13 @@ export function sqliteToPostgres(sql: string): string {
|
|
|
110
110
|
}
|
|
111
111
|
|
|
112
112
|
/**
|
|
113
|
-
* PostgreSQL adapter using a
|
|
113
|
+
* PostgreSQL adapter using a synchronous subprocess bridge.
|
|
114
114
|
*
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
120
|
-
* For full production use, the adapter interface should be async.
|
|
121
|
-
* This sync bridge works because all MCP handlers are async —
|
|
122
|
-
* the future migration is adding `await` before db calls.
|
|
115
|
+
* TODO(P0-4): this is not transaction-safe. querySync currently starts a
|
|
116
|
+
* fresh `node -e` process for every statement, so BEGIN/COMMIT/ROLLBACK do
|
|
117
|
+
* not share one backend connection. PostgreSQL support is demoted behind
|
|
118
|
+
* SQLite for now; before advertising it as production-ready, replace this
|
|
119
|
+
* bridge with a long-lived worker or make DbAdapter async and use pg directly.
|
|
123
120
|
*/
|
|
124
121
|
export class PgAdapter implements DbAdapter {
|
|
125
122
|
readonly dialect = "postgres" as const;
|
|
@@ -196,6 +193,7 @@ export class PgAdapter implements DbAdapter {
|
|
|
196
193
|
}
|
|
197
194
|
|
|
198
195
|
transaction<T>(fn: () => T): T {
|
|
196
|
+
// Not atomic for PostgreSQL until P0-4 is implemented; see class TODO.
|
|
199
197
|
this.querySync("BEGIN");
|
|
200
198
|
try {
|
|
201
199
|
const result = fn();
|
package/src/db.ts
CHANGED
|
@@ -6,7 +6,7 @@ export const db: DbAdapter = createAdapter();
|
|
|
6
6
|
db.exec(`
|
|
7
7
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
8
8
|
resume_id TEXT PRIMARY KEY,
|
|
9
|
-
alias TEXT
|
|
9
|
+
alias TEXT,
|
|
10
10
|
tmux_name TEXT,
|
|
11
11
|
server TEXT DEFAULT 'unknown',
|
|
12
12
|
ip TEXT,
|
|
@@ -19,8 +19,10 @@ db.exec(`
|
|
|
19
19
|
output TEXT,
|
|
20
20
|
progress INTEGER DEFAULT 0,
|
|
21
21
|
score REAL,
|
|
22
|
+
network_id TEXT NOT NULL DEFAULT 'default',
|
|
22
23
|
registered_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
23
|
-
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
24
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
25
|
+
UNIQUE (network_id, alias)
|
|
24
26
|
);
|
|
25
27
|
|
|
26
28
|
CREATE TABLE IF NOT EXISTS inbox (
|
|
@@ -300,7 +302,82 @@ try {
|
|
|
300
302
|
for (const table of ["sessions", "nodes", "tasks", "inbox", "task_events", "completions"]) {
|
|
301
303
|
try { db.exec(`ALTER TABLE ${table} ADD COLUMN network_id TEXT`); } catch {}
|
|
302
304
|
}
|
|
305
|
+
|
|
306
|
+
// ── P0: sessions alias uniqueness is network-scoped.
|
|
307
|
+
// Older SQLite databases created `alias TEXT UNIQUE`, which prevents the same
|
|
308
|
+
// agent alias from existing in two networks. SQLite cannot drop a UNIQUE
|
|
309
|
+
// constraint in place, so rebuild the table once with UNIQUE(network_id, alias).
|
|
310
|
+
function migrateSessionsNetworkAliasUnique() {
|
|
311
|
+
try {
|
|
312
|
+
db.run("UPDATE sessions SET network_id = 'default' WHERE network_id IS NULL OR network_id = ''");
|
|
313
|
+
} catch {}
|
|
314
|
+
|
|
315
|
+
if (db.dialect === "postgres") {
|
|
316
|
+
try { db.exec("ALTER TABLE sessions ALTER COLUMN network_id SET DEFAULT 'default'"); } catch {}
|
|
317
|
+
try { db.exec("UPDATE sessions SET network_id = 'default' WHERE network_id IS NULL OR network_id = ''"); } catch {}
|
|
318
|
+
try { db.exec("ALTER TABLE sessions DROP CONSTRAINT IF EXISTS sessions_alias_key"); } catch {}
|
|
319
|
+
try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_network_alias_unique ON sessions(network_id, alias)"); } catch {}
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
let needsRebuild = true;
|
|
324
|
+
try {
|
|
325
|
+
const createSql = db.get<{ sql: string }>("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'sessions'");
|
|
326
|
+
needsRebuild = !!createSql?.sql && !/UNIQUE\s*\(\s*network_id\s*,\s*alias\s*\)/i.test(createSql.sql);
|
|
327
|
+
} catch {}
|
|
328
|
+
if (!needsRebuild) return;
|
|
329
|
+
|
|
330
|
+
db.transaction(() => {
|
|
331
|
+
db.exec("DROP TABLE IF EXISTS sessions_migrated");
|
|
332
|
+
db.exec(`
|
|
333
|
+
CREATE TABLE sessions_migrated (
|
|
334
|
+
resume_id TEXT PRIMARY KEY,
|
|
335
|
+
alias TEXT,
|
|
336
|
+
tmux_name TEXT,
|
|
337
|
+
server TEXT DEFAULT 'unknown',
|
|
338
|
+
ip TEXT,
|
|
339
|
+
hostname TEXT,
|
|
340
|
+
agent TEXT,
|
|
341
|
+
project_dir TEXT,
|
|
342
|
+
version TEXT,
|
|
343
|
+
status TEXT DEFAULT 'offline',
|
|
344
|
+
task TEXT,
|
|
345
|
+
output TEXT,
|
|
346
|
+
progress INTEGER DEFAULT 0,
|
|
347
|
+
score REAL,
|
|
348
|
+
registered_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
349
|
+
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
350
|
+
node_id TEXT,
|
|
351
|
+
session_id TEXT,
|
|
352
|
+
config_path TEXT,
|
|
353
|
+
channels TEXT,
|
|
354
|
+
last_seen_at TEXT,
|
|
355
|
+
network_id TEXT NOT NULL DEFAULT 'default',
|
|
356
|
+
UNIQUE (network_id, alias)
|
|
357
|
+
)
|
|
358
|
+
`);
|
|
359
|
+
db.exec(`
|
|
360
|
+
INSERT OR REPLACE INTO sessions_migrated (
|
|
361
|
+
resume_id, alias, tmux_name, server, ip, hostname, agent, project_dir, version,
|
|
362
|
+
status, task, output, progress, score, registered_at, updated_at, node_id,
|
|
363
|
+
session_id, config_path, channels, last_seen_at, network_id
|
|
364
|
+
)
|
|
365
|
+
SELECT
|
|
366
|
+
resume_id, alias, tmux_name, server, ip, hostname, agent, project_dir, version,
|
|
367
|
+
status, task, output, progress, score, registered_at, updated_at, node_id,
|
|
368
|
+
session_id, config_path, channels, last_seen_at,
|
|
369
|
+
COALESCE(NULLIF(network_id, ''), 'default')
|
|
370
|
+
FROM sessions
|
|
371
|
+
ORDER BY updated_at
|
|
372
|
+
`);
|
|
373
|
+
db.exec("DROP TABLE sessions");
|
|
374
|
+
db.exec("ALTER TABLE sessions_migrated RENAME TO sessions");
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
migrateSessionsNetworkAliasUnique();
|
|
378
|
+
|
|
303
379
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_sessions_network ON sessions(network_id)"); } catch {}
|
|
380
|
+
try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_sessions_network_alias_unique ON sessions(network_id, alias)"); } catch {}
|
|
304
381
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_tasks_network ON tasks(network_id)"); } catch {}
|
|
305
382
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_nodes_network ON nodes(network_id)"); } catch {}
|
|
306
383
|
try { db.exec("CREATE INDEX IF NOT EXISTS idx_inbox_network ON inbox(network_id)"); } catch {}
|
package/src/index.ts
CHANGED
|
@@ -3,12 +3,26 @@ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/
|
|
|
3
3
|
import { z } from "zod/v4";
|
|
4
4
|
import { registerTools } from "./tools.js";
|
|
5
5
|
import { db, logTaskEvent, logAudit } from "./db.js";
|
|
6
|
-
import { createSSEStream, pushEvent,
|
|
6
|
+
import { createSSEStream, pushEvent, getSSEStats } from "./push.js";
|
|
7
7
|
import { register, login, resolveToken, getUserNetworks, getUserAllNetworks, createNetwork, deleteNetwork, renameNetwork, changePassword, listTokens, createToken, revokeToken, getNetworkMembers, getUserNetworkRole, addNetworkMember, updateMemberRole, removeNetworkMember, createInvite, joinByInvite, createNetworkTokenForNode, type AuthUser } from "./auth.js";
|
|
8
8
|
|
|
9
9
|
const PORT = Number(process.env.PORT) || 9200;
|
|
10
|
-
const HOST = process.env.HOST || "
|
|
10
|
+
const HOST = process.env.HOST || "127.0.0.1";
|
|
11
11
|
const AUTH_TOKEN = process.env.COMMHUB_AUTH_TOKEN;
|
|
12
|
+
const DEV_OPEN = process.argv.includes("--dev-open") || process.env.COMMHUB_DEV_OPEN === "1";
|
|
13
|
+
const TMUX_ENABLED = process.env.COMMHUB_ENABLE_TMUX === "1";
|
|
14
|
+
const SECURITY_LABEL = AUTH_TOKEN ? "🔒 secured" : "⚠️ DEV OPEN MODE";
|
|
15
|
+
const TMUX_ALLOWLIST = new Set(
|
|
16
|
+
(process.env.COMMHUB_TMUX_ALLOWLIST || "")
|
|
17
|
+
.split(",")
|
|
18
|
+
.map((s) => s.trim())
|
|
19
|
+
.filter(Boolean)
|
|
20
|
+
);
|
|
21
|
+
|
|
22
|
+
if (!AUTH_TOKEN && !DEV_OPEN) {
|
|
23
|
+
console.error("[commhub] refusing to start without COMMHUB_AUTH_TOKEN. Use --dev-open or COMMHUB_DEV_OPEN=1 for local-only development.");
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
12
26
|
|
|
13
27
|
// Read version from package.json so banners and /health stay in sync.
|
|
14
28
|
const SERVER_VERSION = (() => {
|
|
@@ -70,10 +84,19 @@ function createServer(clientIP?: string, enforceNetworkId?: string | null, enfor
|
|
|
70
84
|
}
|
|
71
85
|
|
|
72
86
|
// ── Auth helper ─────────────────────────────────────
|
|
73
|
-
function
|
|
87
|
+
function requestToken(req: Request): string {
|
|
74
88
|
const header = req.headers.get("Authorization")?.replace("Bearer ", "");
|
|
75
89
|
const url = new URL(req.url);
|
|
76
|
-
|
|
90
|
+
return header || url.searchParams.get("token") || "";
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function isLegacyAuthToken(req: Request): boolean {
|
|
94
|
+
const token = requestToken(req);
|
|
95
|
+
return !!AUTH_TOKEN && token === AUTH_TOKEN;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function requireAuth(req: Request): Response | null {
|
|
99
|
+
const token = requestToken(req);
|
|
77
100
|
|
|
78
101
|
// V3: check api_tokens first
|
|
79
102
|
if (token) {
|
|
@@ -82,17 +105,46 @@ function requireAuth(req: Request): Response | null {
|
|
|
82
105
|
}
|
|
83
106
|
|
|
84
107
|
// Legacy: check global COMMHUB_AUTH_TOKEN
|
|
85
|
-
if (!AUTH_TOKEN) return null; //
|
|
108
|
+
if (!AUTH_TOKEN && DEV_OPEN) return null; // explicit local/dev open mode
|
|
86
109
|
if (token === AUTH_TOKEN) return null;
|
|
87
110
|
|
|
88
111
|
return Response.json({ error: "unauthorized" }, { status: 401 });
|
|
89
112
|
}
|
|
90
113
|
|
|
114
|
+
function getClientIP(req: Request, server?: any): string {
|
|
115
|
+
const direct = server?.requestIP?.(req)?.address;
|
|
116
|
+
if (direct) return direct;
|
|
117
|
+
const fwd = req.headers.get("x-forwarded-for");
|
|
118
|
+
return fwd ? fwd.split(",")[0].trim() : (req.headers.get("x-real-ip") ?? "unknown");
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function isLocalhostIP(ip: string): boolean {
|
|
122
|
+
return ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1" || ip === "localhost";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function isTmuxAllowedIP(ip: string): boolean {
|
|
126
|
+
return isLocalhostIP(ip) || TMUX_ALLOWLIST.has(ip);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function requireAdminAuth(req: Request): Response | null {
|
|
130
|
+
const token = requestToken(req);
|
|
131
|
+
if (!token) return Response.json({ ok: false, error: "auth required" }, { status: 401 });
|
|
132
|
+
const resolved = resolveToken(token);
|
|
133
|
+
if (!resolved) return Response.json({ ok: false, error: "invalid token" }, { status: 401 });
|
|
134
|
+
if (resolved.user.role !== "admin") return Response.json({ ok: false, error: "admin required" }, { status: 403 });
|
|
135
|
+
return null;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function requireTmuxAccess(req: Request, server?: any): Response | null {
|
|
139
|
+
if (!TMUX_ENABLED) return Response.json({ ok: false, error: "tmux disabled" }, { status: 404 });
|
|
140
|
+
const ip = getClientIP(req, server);
|
|
141
|
+
if (!isTmuxAllowedIP(ip)) return Response.json({ ok: false, error: "tmux access denied from this ip" }, { status: 403 });
|
|
142
|
+
return requireAdminAuth(req);
|
|
143
|
+
}
|
|
144
|
+
|
|
91
145
|
// Extract user + network + token-binding identity from request token.
|
|
92
146
|
function resolveRequestAuth(req: Request): { userId: string; networkId: string | null; username: string; tokenName: string | null } | null {
|
|
93
|
-
const
|
|
94
|
-
const url = new URL(req.url);
|
|
95
|
-
const token = header || url.searchParams.get("token") || "";
|
|
147
|
+
const token = requestToken(req);
|
|
96
148
|
if (!token) return null;
|
|
97
149
|
const resolved = resolveToken(token);
|
|
98
150
|
if (!resolved) return null;
|
|
@@ -243,17 +295,16 @@ Bun.serve({
|
|
|
243
295
|
// ── WebSocket: tmux terminal ──
|
|
244
296
|
const wsMatch = url.pathname.match(/^\/ws\/tmux\/([a-zA-Z0-9_-]+)$/);
|
|
245
297
|
if (wsMatch) {
|
|
246
|
-
const
|
|
247
|
-
if (
|
|
248
|
-
if (server.upgrade(req, { data: { tmuxName: wsMatch[1] } })) return;
|
|
298
|
+
const tmuxErr = requireTmuxAccess(req, server);
|
|
299
|
+
if (tmuxErr) return withCors(req, tmuxErr);
|
|
300
|
+
if (server.upgrade(req, { data: { tmuxName: wsMatch[1] } } as any)) return;
|
|
249
301
|
}
|
|
250
302
|
|
|
251
303
|
// ── MCP Streamable HTTP endpoint ──
|
|
252
304
|
if (url.pathname === "/mcp") {
|
|
253
305
|
const authErr = requireAuth(req);
|
|
254
306
|
if (authErr) return withCors(req, authErr);
|
|
255
|
-
const
|
|
256
|
-
const clientIP = fwd ? fwd.split(",")[0].trim() : (req.headers.get("x-real-ip") ?? "unknown");
|
|
307
|
+
const clientIP = getClientIP(req, server);
|
|
257
308
|
// V3: resolve token → enforce network_id in all MCP tools.
|
|
258
309
|
// utok_ (user token, not network-bound) is allowed — the tool layer
|
|
259
310
|
// scopes to the user's accessible networks. Without this Dashboard
|
|
@@ -268,11 +319,11 @@ Bun.serve({
|
|
|
268
319
|
const transport = new WebStandardStreamableHTTPServerTransport({
|
|
269
320
|
sessionIdGenerator: undefined,
|
|
270
321
|
});
|
|
271
|
-
const
|
|
272
|
-
await
|
|
322
|
+
const mcpServer = createServer(clientIP, enforceNetId, authCtx?.userId || null, callerAlias);
|
|
323
|
+
await mcpServer.connect(transport);
|
|
273
324
|
const response = await transport.handleRequest(req);
|
|
274
325
|
// Disconnect after response to prevent McpServer leak
|
|
275
|
-
setImmediate(() =>
|
|
326
|
+
setImmediate(() => mcpServer.close().catch(() => {}));
|
|
276
327
|
return response;
|
|
277
328
|
}
|
|
278
329
|
|
|
@@ -283,7 +334,31 @@ Bun.serve({
|
|
|
283
334
|
const authErr = requireAuth(req);
|
|
284
335
|
if (authErr) return authErr;
|
|
285
336
|
const sessionName = decodeURIComponent(eventsMatch[1]);
|
|
286
|
-
|
|
337
|
+
const authCtx = resolveRequestAuth(req);
|
|
338
|
+
const scopedNetId = authCtx?.networkId || url.searchParams.get("network_id");
|
|
339
|
+
if (!authCtx && isLegacyAuthToken(req)) {
|
|
340
|
+
if (scopedNetId) {
|
|
341
|
+
const session = db.get<any>(
|
|
342
|
+
"SELECT 1 FROM sessions WHERE alias = ?1 AND network_id = ?2",
|
|
343
|
+
sessionName, scopedNetId
|
|
344
|
+
);
|
|
345
|
+
if (!session) return withCors(req, Response.json({ ok: false, error: "session not in requested network" }, { status: 403 }));
|
|
346
|
+
}
|
|
347
|
+
return createSSEStream(sessionName, scopedNetId);
|
|
348
|
+
}
|
|
349
|
+
if (!authCtx || !scopedNetId) {
|
|
350
|
+
return withCors(req, Response.json({ ok: false, error: "network-scoped token required for SSE" }, { status: 403 }));
|
|
351
|
+
}
|
|
352
|
+
const role = getUserNetworkRole(authCtx.userId, scopedNetId);
|
|
353
|
+
if (!role) return withCors(req, Response.json({ ok: false, error: "not a member of this network" }, { status: 403 }));
|
|
354
|
+
const session = db.get<any>(
|
|
355
|
+
"SELECT 1 FROM sessions WHERE alias = ?1 AND network_id = ?2",
|
|
356
|
+
sessionName, scopedNetId
|
|
357
|
+
);
|
|
358
|
+
if (!session && authCtx.networkId !== scopedNetId) {
|
|
359
|
+
return withCors(req, Response.json({ ok: false, error: "session not in requested network" }, { status: 403 }));
|
|
360
|
+
}
|
|
361
|
+
return createSSEStream(sessionName, scopedNetId);
|
|
287
362
|
}
|
|
288
363
|
|
|
289
364
|
// ── V3: License endpoints ──
|
|
@@ -343,14 +418,14 @@ Bun.serve({
|
|
|
343
418
|
if (url.pathname === "/api/auth/login" && req.method === "POST") {
|
|
344
419
|
const clientIP = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";
|
|
345
420
|
if (!checkRateLimit(clientIP, 10)) {
|
|
346
|
-
logAudit(null, null, "login_rate_limited", "auth",
|
|
421
|
+
logAudit(null, null, "login_rate_limited", "auth", undefined, clientIP);
|
|
347
422
|
return withCors(req, Response.json({ ok: false, error: "too many attempts, try again later" }, { status: 429 }));
|
|
348
423
|
}
|
|
349
424
|
try {
|
|
350
425
|
const body = await req.json() as any;
|
|
351
426
|
const result = login(body.username, body.password);
|
|
352
427
|
if (result.ok) logAudit(result.user!.user_id, body.username, "login", "user", result.user!.user_id);
|
|
353
|
-
else logAudit(null, body.username, "login_failed", "user",
|
|
428
|
+
else logAudit(null, body.username, "login_failed", "user", undefined, "invalid credentials");
|
|
354
429
|
return withCors(req, Response.json(result, { status: result.ok ? 200 : 401 }));
|
|
355
430
|
} catch (e: any) {
|
|
356
431
|
return withCors(req, Response.json({ ok: false, error: e.message }, { status: 400 }));
|
|
@@ -631,7 +706,9 @@ Bun.serve({
|
|
|
631
706
|
sessions_count: count?.cnt ?? 0,
|
|
632
707
|
sse_connections: sse.total,
|
|
633
708
|
sse_sessions: sse.sessions,
|
|
634
|
-
auth: AUTH_TOKEN ? "enabled" : "
|
|
709
|
+
auth: AUTH_TOKEN ? "enabled" : "dev-open",
|
|
710
|
+
security: AUTH_TOKEN ? "secured" : "dev-open",
|
|
711
|
+
tmux: TMUX_ENABLED ? "enabled" : "disabled",
|
|
635
712
|
v3_auth: true,
|
|
636
713
|
multi_network: true,
|
|
637
714
|
license: license?.type || "none",
|
|
@@ -734,7 +811,7 @@ Bun.serve({
|
|
|
734
811
|
let sessionSql = "SELECT 1 FROM sessions WHERE alias = ?1";
|
|
735
812
|
if (taskNetId) { sessionSql += " AND network_id = ?2"; sessionParams.push(taskNetId); }
|
|
736
813
|
const targetSession = db.get<any>(sessionSql, ...sessionParams);
|
|
737
|
-
if (targetSession) pushEvent(body.alias, { type: "new_task", inbox_count: pending?.cnt ?? 1, priority: body.priority, from: fromSession });
|
|
814
|
+
if (targetSession) pushEvent(body.alias, { type: "new_task", inbox_count: pending?.cnt ?? 1, priority: body.priority, from: fromSession }, taskNetId);
|
|
738
815
|
return withCors(req, Response.json({ ok: true, message_id: id }));
|
|
739
816
|
}
|
|
740
817
|
|
|
@@ -773,13 +850,17 @@ Bun.serve({
|
|
|
773
850
|
);
|
|
774
851
|
ids.push(id);
|
|
775
852
|
}
|
|
776
|
-
|
|
853
|
+
for (const t of targets) {
|
|
854
|
+
pushEvent(t.alias, { type: "broadcast", inbox_count: 1 }, t.network_id);
|
|
855
|
+
}
|
|
777
856
|
return withCors(req, Response.json({ ok: true, recipients: targets.length, message_ids: ids }));
|
|
778
857
|
}
|
|
779
858
|
|
|
780
859
|
// ── REST: tmux capture-pane ──
|
|
781
860
|
const tmuxCapture = url.pathname.match(/^\/api\/tmux\/([a-zA-Z0-9_-]+)$/);
|
|
782
861
|
if (tmuxCapture && req.method === "GET") {
|
|
862
|
+
const tmuxErr = requireTmuxAccess(req, server);
|
|
863
|
+
if (tmuxErr) return withCors(req, tmuxErr);
|
|
783
864
|
const name = tmuxCapture[1];
|
|
784
865
|
const lines = Number(url.searchParams.get("lines")) || 30;
|
|
785
866
|
try {
|
|
@@ -802,6 +883,8 @@ Bun.serve({
|
|
|
802
883
|
// ── REST: tmux send-keys ──
|
|
803
884
|
const tmuxSend = url.pathname.match(/^\/api\/tmux\/([a-zA-Z0-9_-]+)\/send$/);
|
|
804
885
|
if (tmuxSend && req.method === "POST") {
|
|
886
|
+
const tmuxErr = requireTmuxAccess(req, server);
|
|
887
|
+
if (tmuxErr) return withCors(req, tmuxErr);
|
|
805
888
|
const name = tmuxSend[1];
|
|
806
889
|
let body: { text?: string; enter?: boolean };
|
|
807
890
|
try { body = await req.json(); } catch {
|
|
@@ -988,14 +1071,14 @@ Endpoints:
|
|
|
988
1071
|
POST /mcp - MCP Streamable HTTP (for Claude Code / Codex)
|
|
989
1072
|
GET /events/:session - SSE realtime push (Agent subscribes here)
|
|
990
1073
|
GET /health - Health check
|
|
991
|
-
GET /api/status - All sessions
|
|
992
|
-
POST /api/task - Send task via REST
|
|
993
|
-
GET /api/tasks - Tasks table (V2)
|
|
994
|
-
GET /api/completions - Recent completions
|
|
995
|
-
GET /api/tmux/:name - Capture tmux pane output ${
|
|
996
|
-
POST /api/tmux/:name/send - Send keys to tmux ${
|
|
997
|
-
|
|
998
|
-
|
|
1074
|
+
GET /api/status - All sessions (auth required)
|
|
1075
|
+
POST /api/task - Send task via REST (auth required)
|
|
1076
|
+
GET /api/tasks - Tasks table (V2) (auth required)
|
|
1077
|
+
GET /api/completions - Recent completions (auth required)
|
|
1078
|
+
GET /api/tmux/:name - Capture tmux pane output (${TMUX_ENABLED ? "admin + localhost/allowlist required" : "disabled"})
|
|
1079
|
+
POST /api/tmux/:name/send - Send keys to tmux (${TMUX_ENABLED ? "admin + localhost/allowlist required" : "disabled"})
|
|
1080
|
+
|
|
1081
|
+
Security: ${SECURITY_LABEL}
|
|
999
1082
|
`,
|
|
1000
1083
|
{ status: 200, headers: { "Content-Type": "text/plain" } }
|
|
1001
1084
|
));
|
|
@@ -1004,7 +1087,7 @@ Auth: ${AUTH_TOKEN ? "Bearer token enabled (set COMMHUB_AUTH_TOKEN)" : "disabled
|
|
|
1004
1087
|
// ── WebSocket handler for tmux terminal streaming ──
|
|
1005
1088
|
websocket: {
|
|
1006
1089
|
open(ws) {
|
|
1007
|
-
const { tmuxName } = ws.data as { tmuxName: string };
|
|
1090
|
+
const { tmuxName } = ws.data as unknown as { tmuxName: string };
|
|
1008
1091
|
console.log(`[ws] tmux terminal opened: ${tmuxName}`);
|
|
1009
1092
|
let lastOutput = "";
|
|
1010
1093
|
|
|
@@ -1049,7 +1132,7 @@ Auth: ${AUTH_TOKEN ? "Bearer token enabled (set COMMHUB_AUTH_TOKEN)" : "disabled
|
|
|
1049
1132
|
},
|
|
1050
1133
|
|
|
1051
1134
|
async message(ws, message) {
|
|
1052
|
-
const { tmuxName } = ws.data as { tmuxName: string };
|
|
1135
|
+
const { tmuxName } = ws.data as unknown as { tmuxName: string };
|
|
1053
1136
|
try {
|
|
1054
1137
|
const msg = JSON.parse(typeof message === "string" ? message : new TextDecoder().decode(message));
|
|
1055
1138
|
|
|
@@ -1075,7 +1158,7 @@ Auth: ${AUTH_TOKEN ? "Bearer token enabled (set COMMHUB_AUTH_TOKEN)" : "disabled
|
|
|
1075
1158
|
},
|
|
1076
1159
|
|
|
1077
1160
|
close(ws) {
|
|
1078
|
-
const { tmuxName } = ws.data as { tmuxName: string };
|
|
1161
|
+
const { tmuxName } = ws.data as unknown as { tmuxName: string };
|
|
1079
1162
|
console.log(`[ws] tmux terminal closed: ${tmuxName}`);
|
|
1080
1163
|
const interval = wsTmuxIntervals.get(ws);
|
|
1081
1164
|
if (interval) { clearInterval(interval); wsTmuxIntervals.delete(ws); }
|
|
@@ -1096,7 +1179,8 @@ console.log(`
|
|
|
1096
1179
|
╔══════════════════════════════════════════════════╗
|
|
1097
1180
|
║ CommHub MCP Server v${SERVER_VERSION} ║
|
|
1098
1181
|
║ Transport: Streamable HTTP (Bun native) ║
|
|
1099
|
-
║
|
|
1182
|
+
║ Security: ${SECURITY_LABEL}${" ".repeat(Math.max(0, 33 - SECURITY_LABEL.length))}║
|
|
1183
|
+
║ Tmux: ${TMUX_ENABLED ? "ENABLED (admin + localhost/allowlist)" : "DISABLED (set COMMHUB_ENABLE_TMUX=1)"}${" ".repeat(Math.max(0, TMUX_ENABLED ? 0 : 2))}║
|
|
1100
1184
|
║ ║
|
|
1101
1185
|
║ MCP: http://${HOST}:${PORT}/mcp ║
|
|
1102
1186
|
║ REST: http://${HOST}:${PORT}/api ║
|
package/src/push.ts
CHANGED
|
@@ -15,23 +15,24 @@ function ts(): string {
|
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
/** 创建 SSE Response 并注册到 clients map */
|
|
18
|
-
export function createSSEStream(sessionName: string): Response {
|
|
18
|
+
export function createSSEStream(sessionName: string, networkId?: string | null): Response {
|
|
19
19
|
const encoder = new TextEncoder();
|
|
20
20
|
let ctrl: ReadableStreamDefaultController;
|
|
21
|
+
const key = clientKey(sessionName, networkId);
|
|
21
22
|
|
|
22
23
|
const stream = new ReadableStream({
|
|
23
24
|
start(controller) {
|
|
24
25
|
ctrl = controller;
|
|
25
26
|
const client: SSEClient = { controller, encoder };
|
|
26
27
|
|
|
27
|
-
if (!clients.has(
|
|
28
|
-
clients.set(
|
|
28
|
+
if (!clients.has(key)) {
|
|
29
|
+
clients.set(key, []);
|
|
29
30
|
}
|
|
30
|
-
clients.get(
|
|
31
|
-
console.log(`[${ts()}] SSE ← ${
|
|
31
|
+
clients.get(key)!.push(client);
|
|
32
|
+
console.log(`[${ts()}] SSE ← ${key} connected (${clients.get(key)!.length} clients)`);
|
|
32
33
|
|
|
33
34
|
// 发送初始心跳
|
|
34
|
-
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: "connected", session: sessionName })}\n\n`));
|
|
35
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify({ type: "connected", session: sessionName, network_id: networkId ?? null })}\n\n`));
|
|
35
36
|
|
|
36
37
|
// Periodic keepalive every 30s to prevent proxy/LB idle timeout
|
|
37
38
|
const keepalive = setInterval(() => {
|
|
@@ -45,15 +46,15 @@ export function createSSEStream(sessionName: string): Response {
|
|
|
45
46
|
},
|
|
46
47
|
cancel() {
|
|
47
48
|
// 断线清理
|
|
48
|
-
const arr = clients.get(
|
|
49
|
+
const arr = clients.get(key);
|
|
49
50
|
if (arr) {
|
|
50
51
|
const idx = arr.findIndex(c => c.controller === ctrl);
|
|
51
52
|
if (idx !== -1) {
|
|
52
53
|
clearInterval((arr[idx] as any)._keepalive);
|
|
53
54
|
arr.splice(idx, 1);
|
|
54
55
|
}
|
|
55
|
-
if (arr.length === 0) clients.delete(
|
|
56
|
-
console.log(`[${ts()}] SSE ✕ ${
|
|
56
|
+
if (arr.length === 0) clients.delete(key);
|
|
57
|
+
console.log(`[${ts()}] SSE ✕ ${key} disconnected (${arr.length} remaining)`);
|
|
57
58
|
}
|
|
58
59
|
},
|
|
59
60
|
});
|
|
@@ -67,9 +68,13 @@ export function createSSEStream(sessionName: string): Response {
|
|
|
67
68
|
});
|
|
68
69
|
}
|
|
69
70
|
|
|
71
|
+
function clientKey(sessionName: string, networkId?: string | null): string {
|
|
72
|
+
return `${networkId || "global"}:${sessionName}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
70
75
|
/** 推送事件给指定 session 的所有 SSE 连接 */
|
|
71
|
-
export function pushEvent(sessionName: string, event: Record<string, unknown
|
|
72
|
-
const arr = clients.get(sessionName);
|
|
76
|
+
export function pushEvent(sessionName: string, event: Record<string, unknown>, networkId?: string | null): void {
|
|
77
|
+
const arr = clients.get(clientKey(sessionName, networkId ?? (event.network_id as string | null | undefined)));
|
|
73
78
|
if (!arr || arr.length === 0) return;
|
|
74
79
|
|
|
75
80
|
const data = `data: ${JSON.stringify(event)}\n\n`;
|
|
@@ -87,14 +92,7 @@ export function pushEvent(sessionName: string, event: Record<string, unknown>):
|
|
|
87
92
|
for (let i = dead.length - 1; i >= 0; i--) {
|
|
88
93
|
arr.splice(dead[i], 1);
|
|
89
94
|
}
|
|
90
|
-
if (arr.length === 0) clients.delete(sessionName);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** 广播给多个 session */
|
|
94
|
-
export function pushBroadcast(sessionNames: string[], event: Record<string, unknown>): void {
|
|
95
|
-
for (const name of sessionNames) {
|
|
96
|
-
pushEvent(name, event);
|
|
97
|
-
}
|
|
95
|
+
if (arr.length === 0) clients.delete(clientKey(sessionName, networkId ?? (event.network_id as string | null | undefined)));
|
|
98
96
|
}
|
|
99
97
|
|
|
100
98
|
/** 获取当前 SSE 连接统计 */
|
package/src/tools.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
2
|
import { z } from "zod/v4";
|
|
3
3
|
import { db, uuidv4, logTaskEvent, chainReplyToParent } from "./db.js";
|
|
4
|
-
import { pushEvent
|
|
4
|
+
import { pushEvent } from "./push.js";
|
|
5
5
|
import { getUserNetworkRole } from "./auth.js";
|
|
6
6
|
|
|
7
7
|
function ts(): string {
|
|
@@ -36,6 +36,44 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
36
36
|
return sql;
|
|
37
37
|
};
|
|
38
38
|
|
|
39
|
+
type ReadScope = { networkId?: string | null; networkIds?: string[] | null; denied?: string };
|
|
40
|
+
|
|
41
|
+
const getReadableNetworkIds = (): string[] => {
|
|
42
|
+
if (!enforceUserId) return [];
|
|
43
|
+
return db.all<{ network_id: string }>(
|
|
44
|
+
"SELECT network_id FROM network_members WHERE user_id = ?1",
|
|
45
|
+
enforceUserId
|
|
46
|
+
).map((row) => row.network_id);
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const resolveReadScope = (clientNetId?: string | null): ReadScope => {
|
|
50
|
+
if (!enforceUserId) return { networkId: clientNetId ?? null, networkIds: null };
|
|
51
|
+
if (enforceNetworkId) {
|
|
52
|
+
const role = getUserNetworkRole(enforceUserId, enforceNetworkId);
|
|
53
|
+
return role ? { networkId: enforceNetworkId, networkIds: null } : { denied: "not a member of token network" };
|
|
54
|
+
}
|
|
55
|
+
if (clientNetId) {
|
|
56
|
+
const role = getUserNetworkRole(enforceUserId, clientNetId);
|
|
57
|
+
return role ? { networkId: clientNetId, networkIds: null } : { denied: "access denied to requested network" };
|
|
58
|
+
}
|
|
59
|
+
return { networkId: null, networkIds: getReadableNetworkIds() };
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
const addReadScope = (sql: string, params: any[], scope: ReadScope, column = "network_id"): string => {
|
|
63
|
+
if (scope.networkId) {
|
|
64
|
+
sql += ` AND ${column} = ?${params.length + 1}`;
|
|
65
|
+
params.push(scope.networkId);
|
|
66
|
+
return sql;
|
|
67
|
+
}
|
|
68
|
+
if (scope.networkIds) {
|
|
69
|
+
if (scope.networkIds.length === 0) return `${sql} AND 1=0`;
|
|
70
|
+
const placeholders = scope.networkIds.map((_, i) => `?${params.length + i + 1}`).join(", ");
|
|
71
|
+
sql += ` AND ${column} IN (${placeholders})`;
|
|
72
|
+
params.push(...scope.networkIds);
|
|
73
|
+
}
|
|
74
|
+
return sql;
|
|
75
|
+
};
|
|
76
|
+
|
|
39
77
|
const scopedSessionStatus = (alias: string, networkId?: string | null) => {
|
|
40
78
|
const params: any[] = [alias];
|
|
41
79
|
let sql = "SELECT status FROM sessions WHERE alias = ?1";
|
|
@@ -74,6 +112,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
74
112
|
},
|
|
75
113
|
async ({ resume_id, alias, status, task, output, score, progress, server: srv, hostname: hn, agent: ag, project_dir: pd, version: ver, tmux_name: tmux, node_id, session_id, config_path, channels, model: mdl, node_name: nn, network_id: netId }) => {
|
|
76
114
|
const effectiveNetId = getNetworkId(netId);
|
|
115
|
+
const sessionNetId = effectiveNetId ?? "default";
|
|
77
116
|
if (!canWrite(effectiveNetId)) {
|
|
78
117
|
return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: "permission_denied" }) }] };
|
|
79
118
|
}
|
|
@@ -82,11 +121,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
82
121
|
|
|
83
122
|
db.transaction(() => {
|
|
84
123
|
// Only delete same-alias sessions within the same network
|
|
85
|
-
|
|
86
|
-
db.run("DELETE FROM sessions WHERE alias = ?1 AND resume_id != ?2 AND network_id = ?3", [alias, resume_id, effectiveNetId]);
|
|
87
|
-
} else {
|
|
88
|
-
db.run("DELETE FROM sessions WHERE alias = ?1 AND resume_id != ?2", [alias, resume_id]);
|
|
89
|
-
}
|
|
124
|
+
db.run("DELETE FROM sessions WHERE alias = ?1 AND resume_id != ?2 AND network_id = ?3", [alias, resume_id, sessionNetId]);
|
|
90
125
|
db.run(
|
|
91
126
|
`INSERT INTO sessions (resume_id, alias, tmux_name, server, ip, hostname, agent, project_dir, version, status, task, output, progress, score, node_id, session_id, config_path, channels, network_id, last_seen_at, updated_at)
|
|
92
127
|
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, ?19, datetime('now'), datetime('now'))
|
|
@@ -101,7 +136,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
101
136
|
session_id = COALESCE(?16, sessions.session_id), config_path = COALESCE(?17, sessions.config_path),
|
|
102
137
|
channels = COALESCE(?18, sessions.channels), network_id = COALESCE(?19, sessions.network_id),
|
|
103
138
|
last_seen_at = datetime('now'), updated_at = datetime('now')`,
|
|
104
|
-
[resume_id, alias, tmux ?? null, srv ?? null, clientIP ?? null, hn ?? null, ag ?? null, pd ?? null, ver ?? null, status, task ?? null, trimmedOutput ?? null, progress ?? null, score ?? null, node_id ?? null, session_id ?? null, config_path ?? null, channels ?? null,
|
|
139
|
+
[resume_id, alias, tmux ?? null, srv ?? null, clientIP ?? null, hn ?? null, ag ?? null, pd ?? null, ver ?? null, status, task ?? null, trimmedOutput ?? null, progress ?? null, score ?? null, node_id ?? null, session_id ?? null, config_path ?? null, channels ?? null, sessionNetId]
|
|
105
140
|
);
|
|
106
141
|
});
|
|
107
142
|
|
|
@@ -244,7 +279,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
244
279
|
[parentChain.parent_task_id]
|
|
245
280
|
);
|
|
246
281
|
if (parent?.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
|
|
247
|
-
pushEvent(parent.from_name, { type: "chained_reply", parent_task_id: parent.task_id, child_task_id: updatedTaskId, child_alias: alias });
|
|
282
|
+
pushEvent(parent.from_name, { type: "chained_reply", parent_task_id: parent.task_id, child_task_id: updatedTaskId, child_alias: alias }, effectiveNetId);
|
|
248
283
|
}
|
|
249
284
|
}
|
|
250
285
|
} catch (e: any) {
|
|
@@ -266,16 +301,17 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
266
301
|
limit: z.number().min(1).max(100).optional().default(10),
|
|
267
302
|
},
|
|
268
303
|
async ({ alias, limit }) => {
|
|
269
|
-
const
|
|
304
|
+
const readScope = resolveReadScope(null);
|
|
305
|
+
if (readScope.denied) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
|
|
270
306
|
const countParams: any[] = [alias];
|
|
271
307
|
let countSql = "SELECT COUNT(*) as cnt FROM inbox WHERE session_name = ?1 AND acked = 0";
|
|
272
|
-
countSql =
|
|
308
|
+
countSql = addReadScope(countSql, countParams, readScope);
|
|
273
309
|
const rows0 = db.get<{ cnt: number }>(countSql, ...countParams);
|
|
274
310
|
console.log(`[${ts()}] ${alias} → get_inbox: ${rows0?.cnt ?? 0} pending messages`);
|
|
275
311
|
const rowsParams: any[] = [alias];
|
|
276
312
|
let rowsSql = `SELECT id, type, priority, content, context, from_session, created_at, network_id
|
|
277
313
|
FROM inbox WHERE session_name = ?1 AND acked = 0`;
|
|
278
|
-
rowsSql =
|
|
314
|
+
rowsSql = addReadScope(rowsSql, rowsParams, readScope);
|
|
279
315
|
rowsSql += ` ORDER BY CASE priority WHEN 'high' THEN 0 WHEN 'normal' THEN 1 ELSE 2 END, created_at
|
|
280
316
|
LIMIT ?${rowsParams.length + 1}`;
|
|
281
317
|
rowsParams.push(limit);
|
|
@@ -335,19 +371,20 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
335
371
|
network_id: z.string().max(200).optional().describe("Filter by network"),
|
|
336
372
|
},
|
|
337
373
|
async ({ filter_status, filter_server, network_id: netId }) => {
|
|
338
|
-
const
|
|
339
|
-
|
|
374
|
+
const readScope = resolveReadScope(netId);
|
|
375
|
+
if (readScope.denied) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
|
|
376
|
+
console.log(`[${ts()}] hub → get_all_status${filter_status ? ": filter=" + filter_status : ""}${readScope.networkId ? " net=" + readScope.networkId.slice(0, 12) : ""}`);
|
|
340
377
|
|
|
341
378
|
const sessions = db.transaction(() => {
|
|
342
379
|
const cutoff = new Date(Date.now() - 10 * 60 * 1000).toISOString().replace("T", " ").slice(0, 19);
|
|
343
380
|
const staleParams: any[] = [cutoff];
|
|
344
381
|
let staleSql = "UPDATE sessions SET status = 'offline' WHERE updated_at < ?1 AND status != 'offline'";
|
|
345
|
-
staleSql =
|
|
382
|
+
staleSql = addReadScope(staleSql, staleParams, readScope);
|
|
346
383
|
db.run(staleSql, staleParams);
|
|
347
384
|
|
|
348
385
|
let sql = "SELECT * FROM sessions WHERE 1=1";
|
|
349
386
|
const params: any[] = [];
|
|
350
|
-
|
|
387
|
+
sql = addReadScope(sql, params, readScope);
|
|
351
388
|
if (filter_status) { sql += " AND status = ?"; params.push(filter_status); }
|
|
352
389
|
if (filter_server) { sql += " AND server = ?"; params.push(filter_server); }
|
|
353
390
|
sql += " ORDER BY updated_at DESC";
|
|
@@ -356,7 +393,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
356
393
|
|
|
357
394
|
const summaryParams: any[] = [];
|
|
358
395
|
let summarySql = "SELECT status, COUNT(*) as count FROM sessions WHERE 1=1";
|
|
359
|
-
summarySql =
|
|
396
|
+
summarySql = addReadScope(summarySql, summaryParams, readScope);
|
|
360
397
|
summarySql += " GROUP BY status";
|
|
361
398
|
const summary = db.all(summarySql, ...summaryParams);
|
|
362
399
|
|
|
@@ -376,21 +413,22 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
376
413
|
"Get detailed status of a specific session by alias.",
|
|
377
414
|
{ alias: z.string().min(1).max(200).describe("Session alias") },
|
|
378
415
|
async ({ alias }) => {
|
|
379
|
-
const
|
|
416
|
+
const readScope = resolveReadScope(null);
|
|
417
|
+
if (readScope.denied) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
|
|
380
418
|
console.log(`[${ts()}] hub → get_session_status: ${alias}`);
|
|
381
419
|
const sessionParams: any[] = [alias];
|
|
382
420
|
let sessionSql = "SELECT * FROM sessions WHERE alias = ?1";
|
|
383
|
-
sessionSql =
|
|
421
|
+
sessionSql = addReadScope(sessionSql, sessionParams, readScope);
|
|
384
422
|
const session = db.get(sessionSql, ...sessionParams);
|
|
385
423
|
|
|
386
424
|
const pendingParams: any[] = [alias];
|
|
387
425
|
let pendingSql = "SELECT COUNT(*) as cnt FROM inbox WHERE session_name = ?1 AND acked = 0";
|
|
388
|
-
pendingSql =
|
|
426
|
+
pendingSql = addReadScope(pendingSql, pendingParams, readScope);
|
|
389
427
|
const pending = db.get<{ cnt: number }>(pendingSql, ...pendingParams);
|
|
390
428
|
|
|
391
429
|
const recentParams: any[] = [alias];
|
|
392
430
|
let recentSql = "SELECT * FROM completions WHERE session_name = ?1";
|
|
393
|
-
recentSql =
|
|
431
|
+
recentSql = addReadScope(recentSql, recentParams, readScope);
|
|
394
432
|
recentSql += " ORDER BY completed_at DESC LIMIT 5";
|
|
395
433
|
const recent = db.all(recentSql, ...recentParams);
|
|
396
434
|
|
|
@@ -488,7 +526,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
488
526
|
let pendingSql = "SELECT COUNT(*) as cnt FROM inbox WHERE session_name = ?1 AND acked = 0";
|
|
489
527
|
pendingSql = addScope(pendingSql, pendingParams, effectiveNetId);
|
|
490
528
|
const pending = db.get<{ cnt: number }>(pendingSql, ...pendingParams);
|
|
491
|
-
pushEvent(alias, { type: "new_task", inbox_count: pending?.cnt ?? 1, priority, from: from_session });
|
|
529
|
+
pushEvent(alias, { type: "new_task", inbox_count: pending?.cnt ?? 1, priority, from: from_session }, effectiveNetId);
|
|
492
530
|
|
|
493
531
|
return {
|
|
494
532
|
content: [
|
|
@@ -526,7 +564,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
526
564
|
|
|
527
565
|
const session = scopedSessionStatus(alias, effectiveNetId);
|
|
528
566
|
|
|
529
|
-
pushEvent(alias, { type: "new_message",
|
|
567
|
+
pushEvent(alias, { type: "new_message", from: from_session, message_id: id }, effectiveNetId);
|
|
530
568
|
|
|
531
569
|
return {
|
|
532
570
|
content: [
|
|
@@ -601,7 +639,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
601
639
|
[parentChain.parent_task_id]
|
|
602
640
|
);
|
|
603
641
|
if (parent?.from_name && parent.from_name !== "hub" && parent.from_name !== "api") {
|
|
604
|
-
pushEvent(parent.from_name, { type: "chained_reply", parent_task_id: parent.task_id, child_task_id: in_reply_to, child_alias: alias });
|
|
642
|
+
pushEvent(parent.from_name, { type: "chained_reply", parent_task_id: parent.task_id, child_task_id: in_reply_to, child_alias: alias }, effectiveNetId);
|
|
605
643
|
}
|
|
606
644
|
}
|
|
607
645
|
} catch (e: any) {
|
|
@@ -610,7 +648,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
610
648
|
}
|
|
611
649
|
|
|
612
650
|
const session = scopedSessionStatus(alias, effectiveNetId);
|
|
613
|
-
pushEvent(alias, { type: "new_reply", from: from_session, message_id: id, in_reply_to, status: replyStatus });
|
|
651
|
+
pushEvent(alias, { type: "new_reply", from: from_session, message_id: id, in_reply_to, status: replyStatus }, effectiveNetId);
|
|
614
652
|
|
|
615
653
|
return {
|
|
616
654
|
content: [{
|
|
@@ -687,7 +725,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
687
725
|
});
|
|
688
726
|
logTaskEvent(task_id, task.status, "delivered", from_session, "retry");
|
|
689
727
|
// SSE push (unconditional — channel is keyed by alias, not network)
|
|
690
|
-
pushEvent(task.to_name, { type: "new_task", inbox_count: 1, priority: task.priority, from: from_session });
|
|
728
|
+
pushEvent(task.to_name, { type: "new_task", inbox_count: 1, priority: task.priority, from: from_session }, effectiveNetId ?? task.network_id ?? null);
|
|
691
729
|
return {
|
|
692
730
|
content: [{ type: "text" as const, text: JSON.stringify({ ok: true, task_id, retried_to: task.to_name }) }],
|
|
693
731
|
};
|
|
@@ -702,10 +740,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
702
740
|
task_id: z.string().min(1).max(200).describe("Task ID to query"),
|
|
703
741
|
},
|
|
704
742
|
async ({ task_id }) => {
|
|
705
|
-
const
|
|
743
|
+
const readScope = resolveReadScope(null);
|
|
744
|
+
if (readScope.denied) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
|
|
706
745
|
const params: any[] = [task_id];
|
|
707
746
|
let sql = "SELECT * FROM tasks WHERE task_id = ?1";
|
|
708
|
-
sql =
|
|
747
|
+
sql = addReadScope(sql, params, readScope);
|
|
709
748
|
const task = db.get<any>(sql, ...params);
|
|
710
749
|
return {
|
|
711
750
|
content: [{
|
|
@@ -728,10 +767,11 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
728
767
|
limit: z.number().min(1).max(100).optional().default(20),
|
|
729
768
|
},
|
|
730
769
|
async ({ alias, status, from_name, network_id: netId, limit }) => {
|
|
731
|
-
const
|
|
770
|
+
const readScope = resolveReadScope(netId);
|
|
771
|
+
if (readScope.denied) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
|
|
732
772
|
let sql = "SELECT task_id, from_name, to_name, priority, status, content, result, created_at, completed_at FROM tasks WHERE 1=1";
|
|
733
773
|
const params: any[] = [];
|
|
734
|
-
|
|
774
|
+
sql = addReadScope(sql, params, readScope);
|
|
735
775
|
if (alias) { sql += ` AND to_name = ?${params.length + 1}`; params.push(alias); }
|
|
736
776
|
if (status) { sql += ` AND status = ?${params.length + 1}`; params.push(status); }
|
|
737
777
|
if (from_name) { sql += ` AND from_name = ?${params.length + 1}`; params.push(from_name); }
|
|
@@ -742,7 +782,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
742
782
|
// Stats
|
|
743
783
|
const statsParams: any[] = [];
|
|
744
784
|
let statsSql = "SELECT status, COUNT(*) as count FROM tasks WHERE 1=1";
|
|
745
|
-
statsSql =
|
|
785
|
+
statsSql = addReadScope(statsSql, statsParams, readScope);
|
|
746
786
|
statsSql += " GROUP BY status";
|
|
747
787
|
const stats = db.all(statsSql, ...statsParams);
|
|
748
788
|
|
|
@@ -826,7 +866,7 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
826
866
|
[newInboxId, new_alias, task.priority, task.content, from_session, effectiveNetId ?? task.network_id ?? null]);
|
|
827
867
|
});
|
|
828
868
|
logTaskEvent(task_id, task.status, "delivered", from_session, `reassign: ${oldAlias} → ${new_alias}`);
|
|
829
|
-
pushEvent(new_alias, { type: "new_task", inbox_count: 1, priority: task.priority, from: from_session });
|
|
869
|
+
pushEvent(new_alias, { type: "new_task", inbox_count: 1, priority: task.priority, from: from_session }, effectiveNetId ?? task.network_id ?? null);
|
|
830
870
|
return { content: [{ type: "text" as const, text: JSON.stringify({ ok: true, task_id, reassigned_from: oldAlias, reassigned_to: new_alias }) }] };
|
|
831
871
|
}
|
|
832
872
|
);
|
|
@@ -863,7 +903,9 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
863
903
|
ids.push(id);
|
|
864
904
|
}
|
|
865
905
|
|
|
866
|
-
|
|
906
|
+
for (const t of targets) {
|
|
907
|
+
pushEvent(t.alias, { type: "broadcast", inbox_count: 1 }, effectiveNetId ?? t.network_id ?? null);
|
|
908
|
+
}
|
|
867
909
|
|
|
868
910
|
return {
|
|
869
911
|
content: [
|
|
@@ -886,12 +928,13 @@ export function registerTools(server: McpServer, clientIP?: string, enforceNetwo
|
|
|
886
928
|
limit: z.number().min(1).max(500).optional().default(50),
|
|
887
929
|
},
|
|
888
930
|
async ({ since, alias, network_id: netId, limit }) => {
|
|
889
|
-
const
|
|
931
|
+
const readScope = resolveReadScope(netId);
|
|
932
|
+
if (readScope.denied) return { content: [{ type: "text" as const, text: JSON.stringify({ ok: false, error: readScope.denied }) }] };
|
|
890
933
|
console.log(`[${ts()}] hub → get_completions${alias ? ": " + alias : ""}`);
|
|
891
934
|
const cutoff = since ?? new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
|
|
892
935
|
let sql = "SELECT * FROM completions WHERE completed_at >= ?1";
|
|
893
936
|
const params: any[] = [cutoff];
|
|
894
|
-
sql =
|
|
937
|
+
sql = addReadScope(sql, params, readScope);
|
|
895
938
|
|
|
896
939
|
if (alias) {
|
|
897
940
|
sql += ` AND session_name = ?${params.length + 1}`;
|