@sleep2agi/commhub-server 0.6.0 → 0.8.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 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
- **Current preview line.** The supported path is to install the `anet` CLI (`@sleep2agi/agent-network` 2.0.3-preview.4) and run `anet hub start`, which wires up port, the server token, the default account, and local config for you.
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@preview
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.3-preview.4 |
39
- | [`@sleep2agi/agent-network-dashboard`](https://www.npmjs.com/package/@sleep2agi/agent-network-dashboard) | 0.2.1-preview.1 |
40
- | [`@sleep2agi/agent-node`](https://www.npmjs.com/package/@sleep2agi/agent-node) | 2.2.0-preview.1 |
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
- COMMHUB_AUTH_TOKEN Bearer token for authentication
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.6.0",
3
+ "version": "0.8.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": "MIT",
32
- "homepage": "https://anet.vansin.me",
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/auth.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  * V3 Auth module — user registration, login, token management
3
3
  */
4
4
  import { db, generateId, hashPassword, hashToken, generateToken, generateUserToken, generateNetworkToken, uuidv4 } from "./db.js";
5
+ import { WEAK_PASSWORDS } from "./password-dict.js";
5
6
 
6
7
  export interface AuthUser {
7
8
  user_id: string;
@@ -20,10 +21,17 @@ export interface AuthResult {
20
21
  network_id?: string;
21
22
  }
22
23
 
24
+ function validatePasswordStrength(password: string, label = "password"): string | null {
25
+ if (!password || password.length < 8) return `${label} must be at least 8 characters`;
26
+ if (WEAK_PASSWORDS.has(password.toLowerCase())) return `${label} is too common`;
27
+ return null;
28
+ }
29
+
23
30
  export function register(username: string, password: string, email?: string, displayName?: string): AuthResult {
24
31
  if (!username || username.length < 2) return { ok: false, error: "username must be at least 2 characters" };
25
32
  if (username.length > 50) return { ok: false, error: "username too long (max 50)" };
26
- if (!password || password.length < 6) return { ok: false, error: "password must be at least 6 characters" };
33
+ const passwordError = validatePasswordStrength(password);
34
+ if (passwordError) return { ok: false, error: passwordError };
27
35
  if (!/^[a-zA-Z0-9_\-\u4e00-\u9fff]+$/.test(username)) return { ok: false, error: "username contains invalid characters" };
28
36
 
29
37
  const existing = db.get<any>("SELECT user_id FROM users WHERE username = ?1", username);
@@ -126,10 +134,10 @@ export function createNetworkTokenForNode(userId: string, networkId: string, nod
126
134
  return { ok: true, token };
127
135
  }
128
136
 
129
- export function resolveToken(token: string): { user: AuthUser; networkId: string | null; tokenName: string | null } | null {
137
+ export function resolveToken(token: string): { user: AuthUser; networkId: string | null; tokenName: string | null; tokenId: string | null } | null {
130
138
  const tHash = hashToken(token);
131
139
  const row = db.get<any>(
132
- `SELECT t.user_id, t.network_id, t.scope, t.name AS token_name,
140
+ `SELECT t.token_id, t.user_id, t.network_id, t.scope, t.name AS token_name,
133
141
  u.username, u.display_name, u.email, u.role
134
142
  FROM api_tokens t JOIN users u ON t.user_id = u.user_id
135
143
  WHERE t.token_hash = ?1 AND (t.expires_at IS NULL OR t.expires_at > datetime('now'))`,
@@ -143,6 +151,7 @@ export function resolveToken(token: string): { user: AuthUser; networkId: string
143
151
  return {
144
152
  user: { user_id: row.user_id, username: row.username, display_name: row.display_name, email: row.email, role: row.role },
145
153
  networkId: row.network_id,
154
+ tokenId: row.token_id || null,
146
155
  // tokenName carries the binding identity. For node-scoped ntok_, it's
147
156
  // 'node:<alias>'; we strip the prefix and use it as the default
148
157
  // from_session for any MCP send_task / send_message / etc, so peer
@@ -239,13 +248,47 @@ export function revokeToken(userId: string, tokenId: string): { ok: boolean; err
239
248
  return result.changes > 0 ? { ok: true } : { ok: false, error: "token not found" };
240
249
  }
241
250
 
242
- export function changePassword(userId: string, oldPassword: string, newPassword: string): { ok: boolean; error?: string } {
243
- if (!newPassword || newPassword.length < 6) return { ok: false, error: "new password must be at least 6 characters" };
251
+ export function issueUserToken(userId: string, name = "user-login"): { token: string; token_id: string } {
252
+ const token = generateUserToken();
253
+ const tokenId = generateId("tok");
254
+ db.run(
255
+ "INSERT INTO api_tokens (token_id, token_hash, user_id, network_id, name, scope) VALUES (?1, ?2, ?3, NULL, ?4, 'user')",
256
+ [tokenId, hashToken(token), userId, name]
257
+ );
258
+ return { token, token_id: tokenId };
259
+ }
260
+
261
+ export function revokeOtherUserTokens(userId: string, exceptTokenId?: string | null): number {
262
+ const result = exceptTokenId
263
+ ? db.run("DELETE FROM api_tokens WHERE user_id = ?1 AND network_id IS NULL AND token_id != ?2", [userId, exceptTokenId])
264
+ : db.run("DELETE FROM api_tokens WHERE user_id = ?1 AND network_id IS NULL", [userId]);
265
+ return result.changes;
266
+ }
267
+
268
+ export function changePassword(userId: string, oldPassword: string, newPassword: string, currentTokenId?: string | null): { ok: boolean; error?: string; revoked?: number } {
269
+ const passwordError = validatePasswordStrength(newPassword, "new password");
270
+ if (passwordError) return { ok: false, error: passwordError };
244
271
  const user = db.get<any>("SELECT password_hash FROM users WHERE user_id = ?1", userId);
245
272
  if (!user) return { ok: false, error: "user not found" };
246
273
  if (user.password_hash !== hashPassword(oldPassword)) return { ok: false, error: "incorrect current password" };
247
274
  db.run("UPDATE users SET password_hash = ?1, updated_at = datetime('now') WHERE user_id = ?2", [hashPassword(newPassword), userId]);
248
- return { ok: true };
275
+ const revoked = revokeOtherUserTokens(userId, currentTokenId);
276
+ return { ok: true, revoked };
277
+ }
278
+
279
+ export function resetUserPassword(targetUsername: string, callerIsHubAdmin: boolean): { ok: boolean; error?: string; username?: string; user_id?: string; password?: string; token?: string; token_id?: string; revoked?: number } {
280
+ if (!callerIsHubAdmin) return { ok: false, error: "hub admin required" };
281
+ const user = db.get<any>("SELECT user_id, username FROM users WHERE username = ?1", targetUsername);
282
+ if (!user) return { ok: false, error: "user not found" };
283
+ const password = `anet-${crypto.randomUUID().replace(/-/g, "").slice(0, 18)}`;
284
+ db.run("UPDATE users SET password_hash = ?1, updated_at = datetime('now') WHERE user_id = ?2", [hashPassword(password), user.user_id]);
285
+ const revoked = revokeOtherUserTokens(user.user_id, null);
286
+ const issued = issueUserToken(user.user_id, "admin-reset");
287
+ db.run(
288
+ "INSERT INTO audit_log (user_id, username, action, target_type, target_id, detail) VALUES (?1, ?2, 'password_reset_by_admin', 'user', ?3, ?4)",
289
+ [user.user_id, user.username, user.user_id, "local hub admin reset"]
290
+ );
291
+ return { ok: true, username: user.username, user_id: user.user_id, password, token: issued.token, token_id: issued.token_id, revoked };
249
292
  }
250
293
 
251
294
  // ══════════════════════════════════════
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 persistent worker subprocess.
113
+ * PostgreSQL adapter using a synchronous subprocess bridge.
114
114
  *
115
- * Architecture: a single node child process holds a pg.Pool connection.
116
- * Queries are sent via stdin (JSON line), responses read from stdout.
117
- * Bun.spawnSync is used per-query for sync blocking, but the PG
118
- * connection is persistent (no reconnect overhead per query).
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 UNIQUE,
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 {}