@clawchatsai/connector 0.1.25 → 0.1.27

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.
@@ -53,6 +53,6 @@ export declare function handleAuthMessage(dc: DataChannelSend, connectionId: str
53
53
  */
54
54
  export declare function cleanupAuth(connectionId: string): void;
55
55
  /**
56
- * Check if a connection is authenticated (no longer in auth sessions).
56
+ * Check if a connection completed auth.
57
57
  */
58
58
  export declare function isAuthenticated(connectionId: string): boolean;
@@ -19,15 +19,31 @@ import { issueSessionToken, verifySessionToken } from './session-token.js';
19
19
  // ---------------------------------------------------------------------------
20
20
  /** Tracks per-connection auth state */
21
21
  const authSessions = new Map();
22
+ /**
23
+ * Connections that completed auth. This is the only thing that grants access:
24
+ * a connection whose auth session was dropped (timeout, rate limit, eviction)
25
+ * is NOT authenticated, it is blocked until it reconnects.
26
+ */
27
+ const authenticatedConnections = new Set();
22
28
  /** Rate limiting: connectionIds blocked after too many failures */
23
29
  const blockedConnections = new Map(); // connectionId → unblock timestamp
24
30
  /** TOTP replay prevention */
25
31
  let lastUsedTotpStep = 0;
32
+ /**
33
+ * Gateway-wide auth-full lockout. Per-connection limits alone reset on every
34
+ * reconnect, so failures are also counted across all connections.
35
+ */
36
+ let globalFailCount = 0;
37
+ let globalLockoutCount = 0;
38
+ let globalLockedUntil = 0;
26
39
  /** Max nonces to prevent memory leaks from connection storms */
27
40
  const MAX_PENDING_NONCES = 10;
28
41
  const AUTH_TIMEOUT_MS = 60_000; // 60s — enough time to open authenticator app and enter code
29
42
  const MAX_FAILURES = 5;
30
43
  const BLOCK_DURATION_MS = 60_000;
44
+ const GLOBAL_MAX_FAILURES = 5;
45
+ const GLOBAL_LOCKOUT_BASE_MS = 60_000; // doubles per consecutive lockout
46
+ const GLOBAL_LOCKOUT_MAX_MS = 60 * 60_000;
31
47
  // ---------------------------------------------------------------------------
32
48
  // Public API
33
49
  // ---------------------------------------------------------------------------
@@ -63,6 +79,8 @@ export function initAuth(dc, connectionId) {
63
79
  const old = authSessions.get(oldestKey);
64
80
  clearTimeout(old.timeoutHandle);
65
81
  authSessions.delete(oldestKey);
82
+ // Tell the evicted client so it reconnects instead of hanging
83
+ old.dc.send(JSON.stringify({ type: 'auth-failed', reason: 'auth_timeout' }));
66
84
  }
67
85
  }
68
86
  const nonce = crypto.randomBytes(32).toString('hex');
@@ -83,6 +101,7 @@ export function initAuth(dc, connectionId) {
83
101
  failCount: 0,
84
102
  createdAt: Date.now(),
85
103
  timeoutHandle,
104
+ dc,
86
105
  });
87
106
  dc.send(JSON.stringify({
88
107
  type: 'auth-required',
@@ -99,16 +118,14 @@ export function initAuth(dc, connectionId) {
99
118
  * 'blocked' if the message was dropped (pre-auth non-auth message)
100
119
  */
101
120
  export async function handleAuthMessage(dc, connectionId, msg, config) {
102
- const session = authSessions.get(connectionId);
103
- // No auth session = already authenticated or unknown connection
104
- if (!session) {
121
+ if (authenticatedConnections.has(connectionId)) {
105
122
  return 'pass';
106
123
  }
107
- // Already authenticated (shouldn't happen, but be safe)
108
- if (session.state === 'authenticated') {
109
- clearTimeout(session.timeoutHandle);
110
- authSessions.delete(connectionId);
111
- return 'pass';
124
+ const session = authSessions.get(connectionId);
125
+ // No auth session and never authenticated: the session was dropped (timeout,
126
+ // rate limit, eviction) or never started. Block; the client must reconnect.
127
+ if (!session || session.state !== 'awaiting-auth') {
128
+ return 'blocked';
112
129
  }
113
130
  // Only accept auth messages pre-auth
114
131
  const msgType = msg['type'];
@@ -141,16 +158,23 @@ export async function handleAuthMessage(dc, connectionId, msg, config) {
141
158
  const totp = msg['totp'];
142
159
  const sessionDays = msg['sessionDays'] || 7;
143
160
  const msgNonce = msg['nonce'];
161
+ // Gateway-wide lockout: refuse without checking anything, so no guess is tested
162
+ if (Date.now() < globalLockedUntil) {
163
+ dc.send(JSON.stringify({ type: 'auth-failed', reason: 'rate_limited' }));
164
+ return 'pending';
165
+ }
144
166
  // Verify nonce
145
167
  if (msgNonce !== session.nonce) {
146
168
  return sendFailure(dc, connectionId, 'nonce_mismatch');
147
169
  }
148
- // Verify Google ID token (skipped when not configured or in dev mode)
170
+ // Google ID token check. The frontend sends 'signaling-verified' on purpose
171
+ // (bd29058): login.clawchats.ai already did Google sign-in, so TOTP is the
172
+ // connector-side factor and the gateway-wide lockout above protects it.
149
173
  const skipGoogle = !config.google.clientId || config.google.clientId === 'dev-placeholder'
150
174
  || idToken === 'signaling-verified'
151
175
  || (config.devMode && idToken === 'dev-mode-no-google');
152
176
  if (skipGoogle) {
153
- console.log('[Auth] Skipping Google ID token verification (not configured)');
177
+ console.log('[Auth] Skipping Google ID token verification (TOTP-only auth)');
154
178
  }
155
179
  else {
156
180
  try {
@@ -192,14 +216,18 @@ export async function handleAuthMessage(dc, connectionId, msg, config) {
192
216
  // Caller should persist the updated config
193
217
  }
194
218
  else {
219
+ recordGlobalFailure();
195
220
  return sendFailure(dc, connectionId, 'invalid_totp');
196
221
  }
197
222
  }
223
+ globalFailCount = 0;
224
+ globalLockoutCount = 0;
198
225
  // Issue session token
199
226
  const sessionToken = issueSessionToken(config.userId, config.google.authorizedSub, sessionDays, config.sessionSecret);
200
227
  const expiresAt = new Date(Date.now() + Math.min(Math.max(sessionDays, 1), 30) * 86400 * 1000).toISOString();
201
228
  clearTimeout(session.timeoutHandle);
202
229
  authSessions.delete(connectionId);
230
+ authenticatedConnections.add(connectionId);
203
231
  dc.send(JSON.stringify({
204
232
  type: 'auth-ok',
205
233
  sessionToken,
@@ -218,12 +246,13 @@ export function cleanupAuth(connectionId) {
218
246
  clearTimeout(session.timeoutHandle);
219
247
  authSessions.delete(connectionId);
220
248
  }
249
+ authenticatedConnections.delete(connectionId);
221
250
  }
222
251
  /**
223
- * Check if a connection is authenticated (no longer in auth sessions).
252
+ * Check if a connection completed auth.
224
253
  */
225
254
  export function isAuthenticated(connectionId) {
226
- return !authSessions.has(connectionId);
255
+ return authenticatedConnections.has(connectionId);
227
256
  }
228
257
  // ---------------------------------------------------------------------------
229
258
  // Internal helpers
@@ -234,9 +263,20 @@ function authSuccess(dc, connectionId) {
234
263
  clearTimeout(session.timeoutHandle);
235
264
  authSessions.delete(connectionId);
236
265
  }
266
+ authenticatedConnections.add(connectionId);
237
267
  dc.send(JSON.stringify({ type: 'auth-ok' }));
238
268
  return 'authenticated';
239
269
  }
270
+ function recordGlobalFailure() {
271
+ globalFailCount++;
272
+ if (globalFailCount < GLOBAL_MAX_FAILURES)
273
+ return;
274
+ const duration = Math.min(GLOBAL_LOCKOUT_BASE_MS * 2 ** globalLockoutCount, GLOBAL_LOCKOUT_MAX_MS);
275
+ globalLockedUntil = Date.now() + duration;
276
+ globalLockoutCount++;
277
+ globalFailCount = 0;
278
+ console.warn(`[Auth] ${GLOBAL_MAX_FAILURES} failed TOTP attempts — full auth locked for ${duration / 1000}s`);
279
+ }
240
280
  function sendFailure(dc, connectionId, reason) {
241
281
  const session = authSessions.get(connectionId);
242
282
  if (!session)
package/dist/index.js CHANGED
@@ -445,11 +445,9 @@ function setupDataChannelHandler(dc, connectionId, ctx) {
445
445
  // Pre-auth non-auth message — drop silently
446
446
  return;
447
447
  case 'pass':
448
- // Already authenticated — process message normally.
449
- // Note: if auth_timeout deleted the session but DC is still open,
450
- // we get 'pass' for a potentially un-authed connection. This is
451
- // acceptable because auth_timeout now triggers a P2P reconnect
452
- // (Fix 4), which re-establishes the full auth flow.
448
+ // Completed auth on this connection — process message normally.
449
+ // A connection whose auth timed out or was rate-limited gets
450
+ // 'blocked', never 'pass'; the client reconnects (Fix 4).
453
451
  break;
454
452
  }
455
453
  // Authenticated message processing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.25",
3
+ "version": "0.1.27",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
@@ -68,16 +68,121 @@ export function handleWorkspaceList(req, res, query) {
68
68
  send(res, 200, { files, cwd: resolved });
69
69
  }
70
70
 
71
+ const MAX_HINTS = 40;
72
+ const MAX_SEARCH_DIRS = 400;
73
+
74
+ function isFile(p) {
75
+ try { return fs.statSync(p).isFile(); } catch { return false; }
76
+ }
77
+
78
+ function exists(p) {
79
+ try { fs.statSync(p); return true; } catch { return false; }
80
+ }
81
+
82
+ function addMatch(matches, candidate) {
83
+ if (!isFile(candidate)) return;
84
+ try { matches.set(fs.realpathSync(candidate), candidate); } catch { /* vanished */ }
85
+ }
86
+
87
+ // True when the file sits in a git main checkout (`.git` is a folder), false in a linked
88
+ // worktree (`.git` is a file) or outside git.
89
+ function inMainCheckout(file) {
90
+ for (let dir = path.dirname(file); ; dir = path.dirname(dir)) {
91
+ try { return fs.statSync(path.join(dir, '.git')).isDirectory(); } catch { /* keep walking */ }
92
+ if (dir === path.dirname(dir)) return false;
93
+ }
94
+ }
95
+
96
+ // One distinct file wins; among several, a single one in a git main checkout wins (other chats'
97
+ // worktrees carry copies of the same file). Anything else is ambiguous.
98
+ function pickMatch(matches) {
99
+ const found = [...matches.values()];
100
+ if (found.length <= 1) return found[0] ?? null;
101
+ const main = found.filter(inMainCheckout);
102
+ return main.length === 1 ? main[0] : null;
103
+ }
104
+
105
+ // Directory children worth searching: no dot-folders, no node_modules.
106
+ function childDirs(dir) {
107
+ try {
108
+ return fs.readdirSync(dir, { withFileTypes: true })
109
+ .filter(e => e.isDirectory() && !e.name.startsWith('.') && e.name !== 'node_modules')
110
+ .map(e => path.join(dir, e.name));
111
+ } catch { return []; }
112
+ }
113
+
114
+ // The hint's folder no longer exists (typically a worktree removed after its branch merged). Search
115
+ // two levels below the parent of its nearest surviving ancestor, kept inside HOME, for the file.
116
+ function searchAroundGoneHint(hint, p, matches, searched) {
117
+ let survivor = path.dirname(hint);
118
+ while (!exists(survivor) && survivor !== path.dirname(survivor)) survivor = path.dirname(survivor);
119
+ const insideHome = d => d.startsWith(HOME + path.sep);
120
+ const base = insideHome(path.dirname(survivor)) ? path.dirname(survivor) : insideHome(survivor) ? survivor : null;
121
+ if (!base || searched.has(base)) return;
122
+ searched.add(base);
123
+ let budget = MAX_SEARCH_DIRS;
124
+ for (const child of childDirs(base)) {
125
+ if (--budget < 0) return;
126
+ addMatch(matches, path.join(child, p));
127
+ for (const grandchild of childDirs(child)) {
128
+ if (--budget < 0) return;
129
+ addMatch(matches, path.join(grandchild, p));
130
+ }
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Where a file reference from chat points (specs/file-link-check.md in the clawchats repo).
136
+ * `~` is home and absolute paths stand as written. A relative path tries the session root, then
137
+ * the agent workspace. Failing those it tries every ancestor of each hint (absolute paths from
138
+ * the same turn's tool calls, e.g. a `cd` target); if none matches, hints whose folder is gone get
139
+ * a bounded search near where they were. Ties go to a git main checkout (pickMatch).
140
+ * Returns the absolute path, or null.
141
+ */
142
+ export function resolveReadPath(filePath, { roots = [], hints = [] } = {}) {
143
+ const p = filePath.replace(/^~(?=\/|$)/, HOME);
144
+ if (path.isAbsolute(p)) return isFile(p) ? path.resolve(p) : null;
145
+ for (const root of roots) {
146
+ if (!root) continue;
147
+ const candidate = path.resolve(root, p);
148
+ if (isFile(candidate)) return candidate;
149
+ }
150
+ const absHints = [...new Set(hints.slice(0, MAX_HINTS)
151
+ .map(h => h.replace(/^~(?=\/|$)/, HOME))
152
+ .filter(h => path.isAbsolute(h))
153
+ .map(h => path.resolve(h)))];
154
+ const matches = new Map(); // real path -> path as found
155
+ const tried = new Set();
156
+ for (const hint of absHints) {
157
+ for (let dir = hint; ; dir = path.dirname(dir)) {
158
+ if (!tried.has(dir)) {
159
+ tried.add(dir);
160
+ addMatch(matches, path.resolve(dir, p));
161
+ }
162
+ if (dir === path.dirname(dir)) break;
163
+ }
164
+ }
165
+ if (matches.size) return pickMatch(matches);
166
+ const searched = new Set();
167
+ for (const hint of absHints) {
168
+ if (!exists(hint)) searchAroundGoneHint(hint, p, matches, searched);
169
+ }
170
+ return pickMatch(matches);
171
+ }
172
+
71
173
  // Reads any file the gateway user can read (file links in chat open any path, as the agent
72
- // wrote it): `~` is home, relative paths resolve against the agent workspace. Writes and
73
- // deletes stay limited to HOME.
74
- export function handleWorkspaceFileRead(req, res, query, workspaceDir) {
174
+ // wrote it); resolution in resolveReadPath. `stat=1` answers {path, size} instead of the
175
+ // content, so a click can check a link before opening the pane. `hints` is newline-separated.
176
+ // Writes and deletes stay limited to HOME.
177
+ export function handleWorkspaceFileRead(req, res, query, workspaceDir, sessionRoot = null) {
75
178
  const filePath = query.path;
76
179
  if (!filePath) return sendError(res, 400, 'Missing path parameter');
77
- const resolved = path.resolve(workspaceDir, filePath.replace(/^~(?=\/|$)/, HOME));
78
- if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) return sendError(res, 404, 'File not found');
180
+ const hints = query.hints ? query.hints.split('\n').filter(Boolean) : [];
181
+ const resolved = resolveReadPath(filePath, { roots: [sessionRoot, workspaceDir], hints });
182
+ if (!resolved) return sendError(res, 404, 'File not found');
79
183
 
80
184
  const stat = fs.statSync(resolved);
185
+ if (query.stat) return send(res, 200, { path: resolved, size: stat.size });
81
186
  const ext = path.extname(resolved).toLowerCase().slice(1);
82
187
  const binaryMime = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', bmp: 'image/bmp', ico: 'image/x-icon', pdf: 'application/pdf', mp3: 'audio/mpeg', mp4: 'video/mp4', wav: 'audio/wav', ogg: 'audio/ogg', webm: 'video/webm' };
83
188
  const mime = binaryMime[ext];
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict';
3
3
  import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
- import { handleWorkspaceFileRead, handleWorkspaceCreate } from './filesystem.js';
6
+ import { handleWorkspaceFileRead, handleWorkspaceCreate, resolveReadPath } from './filesystem.js';
7
7
 
8
8
  function read(filePath, workspaceDir) {
9
9
  const out = { status: 0, body: '' };
@@ -47,6 +47,87 @@ test('file reads: ~/ expands to home', () => {
47
47
  }
48
48
  });
49
49
 
50
+ test('resolveReadPath: session root before workspace, then a unique match under a hint ancestor', () => {
51
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-resolve-'));
52
+ const mk = (rel, body = rel) => { const f = path.join(base, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, body); return f; };
53
+ const inSession = mk('session/src/a.ts');
54
+ mk('ws/src/a.ts');
55
+ const inRepo = mk('repos/up/ui/src/pages/p.ts');
56
+ mk('repos/up/ui/src/pages/deep/x.md');
57
+ mk('one/lib/dup.ts');
58
+ mk('two/lib/dup.ts');
59
+ const roots = [path.join(base, 'session'), path.join(base, 'ws')];
60
+ try {
61
+ assert.equal(resolveReadPath('src/a.ts', { roots }), inSession);
62
+ assert.equal(resolveReadPath('src/a.ts', { roots: [null, path.join(base, 'ws')] }), path.join(base, 'ws/src/a.ts'));
63
+ assert.equal(resolveReadPath(inRepo, { roots }), inRepo);
64
+ assert.equal(resolveReadPath('ui/src/pages/p.ts', { roots }), null);
65
+ // The agent `cd`'d deep into the repo; the repo root is an ancestor of the hint.
66
+ assert.equal(resolveReadPath('ui/src/pages/p.ts', { roots, hints: [path.join(base, 'repos/up/ui/src/pages/deep')] }), inRepo);
67
+ // Two different files match: ambiguous, not found.
68
+ assert.equal(resolveReadPath('lib/dup.ts', { roots, hints: [path.join(base, 'one/lib'), path.join(base, 'two')] }), null);
69
+ // Relative hints are ignored.
70
+ assert.equal(resolveReadPath('ui/src/pages/p.ts', { roots, hints: ['repos/up'] }), null);
71
+ } finally {
72
+ fs.rmSync(base, { recursive: true, force: true });
73
+ }
74
+ });
75
+
76
+ test('resolveReadPath: a hint into a removed worktree finds the file in the main checkout', () => {
77
+ // Searches stay inside HOME, so this layout lives there.
78
+ const base = fs.mkdtempSync(path.join(os.homedir(), '.cc-gone-'));
79
+ const mk = (rel, body = rel) => { const f = path.join(base, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, body); return f; };
80
+ fs.mkdirSync(path.join(base, 'repos/app/.git'), { recursive: true });
81
+ const main = mk('repos/app/known-gaps/q.md');
82
+ // Another chat's live worktree of the same repo has a copy (linked worktree: `.git` is a file).
83
+ mk('repos/worktrees/app-other/.git', 'gitdir: elsewhere');
84
+ mk('repos/worktrees/app-other/known-gaps/q.md');
85
+ const gone = path.join(base, 'repos/worktrees/app-queue/frontend');
86
+ try {
87
+ assert.equal(resolveReadPath('known-gaps/q.md', { hints: [gone] }), main);
88
+ // Two main checkouts with the file: ambiguous.
89
+ fs.mkdirSync(path.join(base, 'repos/fork/.git'), { recursive: true });
90
+ mk('repos/fork/known-gaps/q.md');
91
+ assert.equal(resolveReadPath('known-gaps/q.md', { hints: [gone] }), null);
92
+ // Hints that still exist never trigger the search.
93
+ assert.equal(resolveReadPath('known-gaps/q.md', { hints: [path.join(base, 'repos/worktrees')] }), null);
94
+ } finally {
95
+ fs.rmSync(base, { recursive: true, force: true });
96
+ }
97
+ });
98
+
99
+ test('resolveReadPath: several hint matches prefer the git main checkout', () => {
100
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-tie-'));
101
+ const mk = (rel, body = rel) => { const f = path.join(base, rel); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, body); return f; };
102
+ fs.mkdirSync(path.join(base, 'app/.git'), { recursive: true });
103
+ const main = mk('app/src/a.js');
104
+ mk('wt/.git', 'gitdir: elsewhere');
105
+ mk('wt/src/a.js');
106
+ try {
107
+ assert.equal(resolveReadPath('src/a.js', { hints: [path.join(base, 'app/lib'), path.join(base, 'wt/lib')] }), main);
108
+ } finally {
109
+ fs.rmSync(base, { recursive: true, force: true });
110
+ }
111
+ });
112
+
113
+ test('file reads: stat=1 answers the resolved path and size; hints arrive newline-separated', () => {
114
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-stat-'));
115
+ const f = path.join(base, 'repo/docs/n.md');
116
+ fs.mkdirSync(path.dirname(f), { recursive: true });
117
+ fs.writeFileSync(f, 'hello');
118
+ const out = { status: 0, body: '' };
119
+ const res = { writeHead(s) { out.status = s; }, setHeader() {}, end(b) { out.body = String(b ?? ''); } };
120
+ try {
121
+ handleWorkspaceFileRead({}, res, { path: 'docs/n.md', stat: '1', hints: `/nonexistent\n${path.join(base, 'repo/docs')}` }, '/nonexistent-ws');
122
+ assert.equal(out.status, 200);
123
+ assert.deepEqual(JSON.parse(out.body), { path: f, size: 5 });
124
+ handleWorkspaceFileRead({}, res, { path: 'docs/gone.md', stat: '1' }, base, path.join(base, 'repo'));
125
+ assert.equal(out.status, 404);
126
+ } finally {
127
+ fs.rmSync(base, { recursive: true, force: true });
128
+ }
129
+ });
130
+
50
131
  function create(query) {
51
132
  const out = { status: 0, body: null };
52
133
  const res = {
@@ -19,12 +19,12 @@ export function normalizeTitle(raw) {
19
19
  }
20
20
 
21
21
  /**
22
+ * Direct completion where the main model's provider has a direct transport; CLI and harness
23
+ * runtimes (claude-cli, codex, …) only run in isolated agent-runtime mode.
22
24
  * @param {{ complete?: (params: object) => Promise<{ text?: string }> }} llm api.runtime.llm
23
25
  */
24
- export function createTitleHandler(llm) {
25
- // Direct completion where the main model's provider has a direct transport; CLI and harness
26
- // runtimes (claude-cli, codex, …) only run in isolated agent-runtime mode.
27
- async function complete(message) {
26
+ function createCompletion(llm) {
27
+ return async function complete(message) {
28
28
  const base = { messages: [{ role: 'user', content: message }], systemPrompt: TITLE_PROMPT, purpose: 'clawchats.title', maxTokens: 64 };
29
29
  try {
30
30
  return await llm.complete(base);
@@ -32,7 +32,23 @@ export function createTitleHandler(llm) {
32
32
  if (err?.code === 'LLM_COMPLETION_NOT_AUTHORIZED') throw err;
33
33
  return await llm.complete({ ...base, maxTokens: undefined, execution: { mode: 'isolated-agent-runtime', timeoutMs: TIMEOUT_MS } });
34
34
  }
35
- }
35
+ };
36
+ }
37
+
38
+ /** message → title or null (null also when the host has no plugin model completion). */
39
+ export function createTitler(llm) {
40
+ const complete = createCompletion(llm);
41
+ return async message => {
42
+ if (typeof llm?.complete !== 'function' || typeof message !== 'string' || !message.trim()) return null;
43
+ return normalizeTitle((await complete(Array.from(message.trim()).slice(0, SOURCE_MAX_CHARS).join('')))?.text);
44
+ };
45
+ }
46
+
47
+ /**
48
+ * @param {{ complete?: (params: object) => Promise<{ text?: string }> }} llm api.runtime.llm
49
+ */
50
+ export function createTitleHandler(llm) {
51
+ const complete = createCompletion(llm);
36
52
 
37
53
  return async function handleTitle(req, res) {
38
54
  if (typeof llm?.complete !== 'function') return sendError(res, 501, 'This OpenClaw version has no plugin model completion');
package/server/gateway.js CHANGED
@@ -91,6 +91,9 @@ export class GatewayClient {
91
91
  return;
92
92
  }
93
93
 
94
+ // Connector-side observers (team chat run tracking) see every event before the lens filters.
95
+ if (msg.type === 'event' && this.onEvent) { try { this.onEvent(msg); } catch (e) { console.error('[gateway] event observer:', e.message); } }
96
+
94
97
  if (msg.type === 'event' && msg.event === 'connect.challenge') {
95
98
  this.ws.send(JSON.stringify({ type: 'req', id: 'gw-connect-1', method: 'connect', params: this._connectParams(msg.payload?.nonce || '', ['tool-events']) }));
96
99
  return;
package/server/index.js CHANGED
@@ -13,11 +13,13 @@ import { handleTranscribe } from './controllers/transcribe.js';
13
13
  import { createGatewayMediaHandler } from './controllers/gateway-media.js';
14
14
  import { handleStatic } from './controllers/static.js';
15
15
  import { handleAgents } from './controllers/agents.js';
16
- import { createTitleHandler } from './controllers/title.js';
16
+ import { createTitleHandler, createTitler } from './controllers/title.js';
17
17
  import { createSettingsHandlers } from './controllers/settings.js';
18
18
  import { createWorkspaceStore } from './store/workspace-store.js';
19
19
  import { createExtrasStore } from './store/extras-store.js';
20
+ import { createTeamStore } from './store/team-store.js';
20
21
  import { SessionLens } from './session-lens.js';
22
+ import { TeamCoordinator } from './team.js';
21
23
  import { send, sendError, parseBody, uuid, matchRoute, setCors } from './util/http.js';
22
24
 
23
25
  // PORT is passed via createApp(config.port); env var is read by plugin host (src/index.ts).
@@ -70,7 +72,26 @@ export function createApp(config = {}) {
70
72
  const extras = createExtrasStore(() => globalDbCache.get());
71
73
  try { const n = extras.seedFromWorkspaces(getWorkspaces()); if (n) console.log(`[extras] seeded ${n} project style(s) from workspaces.json`); }
72
74
  catch (e) { console.error('[extras] style seed failed:', e.message); }
73
- gatewayClient.lens = new SessionLens({ broadcast, request: (m, p, t) => gatewayClient.request(m, p, t), extras });
75
+ const gwRequest = (m, p, t) => gatewayClient.request(m, p, t);
76
+ // Team chats: several agents in one thread (server/team.js).
77
+ const team = new TeamCoordinator({ store: createTeamStore(() => globalDbCache.get()), request: gwRequest, broadcast, titler: createTitler(config.llm) });
78
+ gatewayClient.onEvent = msg => team.onGatewayEvent(msg);
79
+ gatewayClient.lens = new SessionLens({ broadcast, request: gwRequest, extras, team });
80
+
81
+ // A session's working root, for relative file links (gateway resolveSessionWorkspaceRoots:
82
+ // spawnedCwd before sessionRoot). Cached briefly; null when the gateway can't say.
83
+ const sessionRoots = new Map(); // key -> { root, at }
84
+ async function sessionRoot(key) {
85
+ const hit = sessionRoots.get(key);
86
+ if (hit && Date.now() - hit.at < 60_000) return hit.root;
87
+ let root = null;
88
+ try {
89
+ const s = (await gatewayClient.request('sessions.describe', { key }, 5000))?.session;
90
+ root = s?.spawnedCwd || s?.sessionRoot || null;
91
+ } catch { /* fall back to the workspace */ }
92
+ sessionRoots.set(key, { root, at: Date.now() });
93
+ return root;
94
+ }
74
95
 
75
96
  // Instantiate controllers
76
97
  const handleGatewayMedia = createGatewayMediaHandler({ gatewayWsUrl: gatewayUrl, gatewayToken });
@@ -153,7 +174,7 @@ export function createApp(config = {}) {
153
174
  if (method === 'GET' && urlPath === '/api/file') return handleServeFile(req, res, query, workspaceDir);
154
175
  if (method === 'GET' && urlPath === '/api/gw-media') return handleGatewayMedia(req, res, query);
155
176
  if (method === 'GET' && urlPath === '/api/workspace') return handleWorkspaceList(req, res, query);
156
- if (method === 'GET' && urlPath === '/api/workspace/file') return handleWorkspaceFileRead(req, res, query, workspaceDir);
177
+ if (method === 'GET' && urlPath === '/api/workspace/file') return handleWorkspaceFileRead(req, res, query, workspaceDir, query.session ? await sessionRoot(query.session) : null);
157
178
  if (method === 'PUT' && urlPath === '/api/workspace/file') return await handleWorkspaceFileWrite(req, res, query);
158
179
  if (method === 'DELETE' && urlPath === '/api/workspace/file') return handleWorkspaceFileDelete(req, res, query);
159
180
  if (method === 'POST' && urlPath === '/api/workspace/upload') return await handleWorkspaceUpload(req, res, query);
@@ -201,6 +222,50 @@ export function createApp(config = {}) {
201
222
  return send(res, 200, { ok: true });
202
223
  }
203
224
 
225
+ // Team chats (server/team.js; EXTRAS.md). Room keys contain ':' and are URL-encoded.
226
+ if (method === 'GET' && urlPath === '/api/team') return send(res, 200, { rooms: team.rooms() });
227
+ if (method === 'POST' && urlPath === '/api/team') {
228
+ const body = await parseBody(req);
229
+ try { return send(res, 200, { room: await team.createRoom(body) }); }
230
+ catch (e) { return sendError(res, 400, e.message); }
231
+ }
232
+ if ((p = matchRoute(method, urlPath, 'GET /api/team/:room'))) {
233
+ const room = team.room(p.room);
234
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
235
+ }
236
+ if ((p = matchRoute(method, urlPath, 'PATCH /api/team/:room'))) {
237
+ const room = team.setDiscuss(p.room, (await parseBody(req)).discuss);
238
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
239
+ }
240
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/agents'))) {
241
+ const { agentId } = await parseBody(req);
242
+ if (typeof agentId !== 'string' || !agentId) return sendError(res, 400, 'agentId is required');
243
+ try {
244
+ const room = await team.addAgent(p.room, agentId);
245
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
246
+ } catch (e) { return sendError(res, 400, e.message); }
247
+ }
248
+ if ((p = matchRoute(method, urlPath, 'DELETE /api/team/:room/agents/:agentId'))) {
249
+ try {
250
+ const room = team.removeAgent(p.room, p.agentId);
251
+ return room ? send(res, 200, { room }) : sendError(res, 404, 'Not a team chat');
252
+ } catch (e) { return sendError(res, 400, e.message); }
253
+ }
254
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/send'))) {
255
+ try { return send(res, 200, await team.send(p.room, await parseBody(req))); }
256
+ catch (e) { return sendError(res, 400, e.message); }
257
+ }
258
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/unconvert'))) {
259
+ try {
260
+ const sourceKey = await team.unconvert(p.room);
261
+ return sourceKey ? send(res, 200, { sourceKey }) : sendError(res, 404, 'Not a team chat');
262
+ } catch (e) { return sendError(res, 400, e.message); }
263
+ }
264
+ if ((p = matchRoute(method, urlPath, 'POST /api/team/:room/stop'))) {
265
+ await team.stop(p.room);
266
+ return send(res, 200, { ok: true });
267
+ }
268
+
204
269
 
205
270
  sendError(res, 404, `Not found: ${method} ${urlPath}`);
206
271
  } catch (err) {
@@ -254,6 +319,7 @@ export function createApp(config = {}) {
254
319
  shutdown: closeAll,
255
320
  gatewayClient,
256
321
  extras,
322
+ team,
257
323
  setupBrowserWs,
258
324
  debugLogger,
259
325
  dataDir: DATA_DIR,
@@ -14,6 +14,8 @@
14
14
  //
15
15
  // Visible = a root, direct, user chat: `agent:<id>:dashboard:<id>` (gateway-created) or
16
16
  // `agent:<id>:<project>:chat:<id>` (legacy ClawChats). Everything else is hidden.
17
+ // Team chat working sessions (server/team.js) are hidden too, but their run events are
18
+ // forwarded: the room shows each agent's reply streaming.
17
19
 
18
20
  const DASHBOARD_KEY = /^agent:[^:]+:dashboard:[^:]+$/;
19
21
  const LEGACY_CHAT_KEY = /^agent:[^:]+:[^:]+:chat:[^:]+$/;
@@ -116,11 +118,13 @@ export class SessionLens {
116
118
  * @param {(data: string) => void} opts.broadcast send a frame to all browsers
117
119
  * @param {(method: string, params: object, timeoutMs?: number) => Promise<any>} [opts.request] connector-originated gateway RPC
118
120
  * @param {object} [opts.extras] ExtrasStore (project style side effects)
121
+ * @param {object} [opts.team] TeamCoordinator (`isWorkKey`, `onSessionDeleted`)
119
122
  */
120
- constructor({ broadcast, request, extras, logger = console }) {
123
+ constructor({ broadcast, request, extras, team, logger = console }) {
121
124
  this.broadcast = broadcast;
122
125
  this.request = request;
123
126
  this.extras = extras;
127
+ this.team = team;
124
128
  this.log = logger;
125
129
  this.hidden = new Set(); // candidate-shaped keys a row revealed as not a user chat
126
130
  this.pending = new Map(); // browser req id -> { method, params }
@@ -137,16 +141,16 @@ export class SessionLens {
137
141
  const verdict = rowVerdict(row);
138
142
  if (verdict === true) this.hidden.add(key);
139
143
  else if (verdict === false) this.hidden.delete(key);
140
- return !this.hidden.has(key);
144
+ return this.isVisible(key);
141
145
  }
142
146
 
143
147
  isVisible(key) {
144
- return isCandidateKey(key) && !this.hidden.has(key);
148
+ return isCandidateKey(key) && !this.hidden.has(key) && !this.team?.isWorkKey(key);
145
149
  }
146
150
 
147
- /** chat/agent run events: visible chats plus the connector's own utility sessions. */
151
+ /** chat/agent run events: visible chats, team chat working sessions, utility sessions. */
148
152
  forwardsRunEvent(key) {
149
- return isUtilityKey(key) || this.isVisible(key);
153
+ return isUtilityKey(key) || this.isVisible(key) || !!this.team?.isWorkKey(key);
150
154
  }
151
155
 
152
156
  /** Seed `hidden` from a full roster so partial events of child sessions stay hidden. */
@@ -169,6 +173,9 @@ export class SessionLens {
169
173
  if (!payload || typeof payload !== 'object') return null;
170
174
  const key = payload.sessionKey;
171
175
  if (!key) return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) }; // catalog/groups
176
+ if (payload.reason === 'delete' && this.team) {
177
+ try { this.team.onSessionDeleted(key); } catch (e) { this.log.warn?.(`[lens] team delete: ${e.message}`); }
178
+ }
172
179
  if (!this.observe(key, payload.session || payload)) return null;
173
180
  if (payload.reason === 'delete' && this.extras) this.extras.deleteThreadExtras?.(key);
174
181
  return { type: 'event', event: 'sessions.changed', payload: trimEvent(payload) };