@clawchatsai/connector 0.1.22 → 0.1.24

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clawchatsai/connector",
3
- "version": "0.1.22",
3
+ "version": "0.1.24",
4
4
  "type": "module",
5
5
  "description": "ClawChats OpenClaw plugin — P2P tunnel + local API bridge",
6
6
  "main": "dist/index.js",
@@ -7,6 +7,13 @@ import { parseMultipart } from '../util/multipart.js';
7
7
  const HOME = os.homedir();
8
8
  const ALLOWED_FILE_DIRS = [HOME, '/tmp'];
9
9
 
10
+ // Resolves a `~`-relative or absolute path; returns null unless it is HOME or inside it
11
+ // (a bare prefix check would also admit siblings such as /home/user2).
12
+ function resolveInHome(p) {
13
+ const resolved = path.resolve(p.replace(/^~/, HOME));
14
+ return resolved === HOME || resolved.startsWith(HOME + path.sep) ? resolved : null;
15
+ }
16
+
10
17
  export function handleServeFile(req, res, query, workspaceDir) {
11
18
  const filePath = query.path;
12
19
  if (!filePath) return sendError(res, 400, 'Missing path parameter');
@@ -39,8 +46,8 @@ export function handleWorkspaceList(req, res, query) {
39
46
  const reqPath = query.path || '~/.openclaw/workspace';
40
47
  const depth = parseInt(query.depth || '2', 10);
41
48
  const showHidden = query.hidden === '1' || query.hidden === 'true';
42
- const resolved = path.resolve(reqPath.replace(/^~/, HOME));
43
- if (!resolved.startsWith(HOME)) return sendError(res, 403, 'Access denied');
49
+ const resolved = resolveInHome(reqPath);
50
+ if (!resolved) return sendError(res, 403, 'Access denied');
44
51
  if (!fs.existsSync(resolved)) return sendError(res, 404, 'Path not found');
45
52
 
46
53
  const files = [{ path: resolved + '/', type: 'dir', name: path.basename(resolved), size: 0 }];
@@ -61,11 +68,13 @@ export function handleWorkspaceList(req, res, query) {
61
68
  send(res, 200, { files, cwd: resolved });
62
69
  }
63
70
 
64
- export function handleWorkspaceFileRead(req, res, query) {
71
+ // 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) {
65
75
  const filePath = query.path;
66
76
  if (!filePath) return sendError(res, 400, 'Missing path parameter');
67
- const resolved = path.resolve(filePath.replace(/^~/, HOME));
68
- if (!resolved.startsWith(HOME)) return sendError(res, 403, 'Access denied');
77
+ const resolved = path.resolve(workspaceDir, filePath.replace(/^~(?=\/|$)/, HOME));
69
78
  if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) return sendError(res, 404, 'File not found');
70
79
 
71
80
  const stat = fs.statSync(resolved);
@@ -87,8 +96,8 @@ export function handleWorkspaceFileRead(req, res, query) {
87
96
  export async function handleWorkspaceFileWrite(req, res, query) {
88
97
  const filePath = query.path;
89
98
  if (!filePath) return sendError(res, 400, 'Missing path parameter');
90
- const resolved = path.resolve(filePath.replace(/^~/, HOME));
91
- if (!resolved.startsWith(HOME)) return sendError(res, 403, 'Can only write to workspace directory');
99
+ const resolved = resolveInHome(filePath);
100
+ if (!resolved) return sendError(res, 403, 'Can only write to workspace directory');
92
101
  const chunks = [];
93
102
  for await (const chunk of req) chunks.push(chunk);
94
103
  const dir = path.dirname(resolved);
@@ -100,8 +109,8 @@ export async function handleWorkspaceFileWrite(req, res, query) {
100
109
  export function handleWorkspaceFileDelete(req, res, query) {
101
110
  const filePath = query.path;
102
111
  if (!filePath) return sendError(res, 400, 'Missing path parameter');
103
- const resolved = path.resolve(filePath.replace(/^~/, HOME));
104
- if (!resolved.startsWith(HOME)) return sendError(res, 403, 'Access denied');
112
+ const resolved = resolveInHome(filePath);
113
+ if (!resolved) return sendError(res, 403, 'Access denied');
105
114
  if (!fs.existsSync(resolved)) return sendError(res, 404, 'Path not found');
106
115
  try {
107
116
  const stat = fs.statSync(resolved);
@@ -113,8 +122,8 @@ export function handleWorkspaceFileDelete(req, res, query) {
113
122
  export async function handleWorkspaceUpload(req, res, query) {
114
123
  const targetDir = query.path;
115
124
  if (!targetDir) return sendError(res, 400, 'Missing path parameter');
116
- const resolved = path.resolve(targetDir.replace(/^~/, HOME));
117
- if (!resolved.startsWith(HOME)) return sendError(res, 403, 'Access denied');
125
+ const resolved = resolveInHome(targetDir);
126
+ if (!resolved) return sendError(res, 403, 'Access denied');
118
127
  if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) return sendError(res, 404, 'Target directory not found');
119
128
  if (!(req.headers['content-type'] || '').includes('multipart/form-data')) return sendError(res, 400, 'Expected multipart/form-data');
120
129
 
@@ -137,3 +146,23 @@ export async function handleWorkspaceUpload(req, res, query) {
137
146
  }
138
147
  send(res, 200, { ok: true, uploaded });
139
148
  }
149
+
150
+ // Creates one empty file or folder named `name` inside the directory `path`.
151
+ export function handleWorkspaceCreate(req, res, query) {
152
+ const { path: parentPath, name, type } = query;
153
+ if (!parentPath || !name) return sendError(res, 400, 'Missing path or name parameter');
154
+ if (type !== 'file' && type !== 'dir') return sendError(res, 400, 'type must be file or dir');
155
+ if (name === '.' || name === '..' || /[/\\\0]/.test(name) || name.trim() !== name) return sendError(res, 400, 'Invalid name');
156
+ const parent = resolveInHome(parentPath);
157
+ if (!parent) return sendError(res, 403, 'Access denied');
158
+ if (!fs.existsSync(parent) || !fs.statSync(parent).isDirectory()) return sendError(res, 404, 'Target directory not found');
159
+ const target = path.join(parent, name);
160
+ try {
161
+ if (type === 'dir') fs.mkdirSync(target);
162
+ else fs.writeFileSync(target, '', { flag: 'wx' });
163
+ } catch (err) {
164
+ if (err.code === 'EEXIST') return sendError(res, 409, `"${name}" already exists`);
165
+ return sendError(res, 500, 'Create failed: ' + err.message);
166
+ }
167
+ send(res, 200, { ok: true, path: target + (type === 'dir' ? '/' : ''), type });
168
+ }
@@ -0,0 +1,83 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import fs from 'node:fs';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { handleWorkspaceFileRead, handleWorkspaceCreate } from './filesystem.js';
7
+
8
+ function read(filePath, workspaceDir) {
9
+ const out = { status: 0, body: '' };
10
+ const res = {
11
+ writeHead(status) { out.status = status; },
12
+ setHeader() {},
13
+ end(body) { out.body = String(body ?? ''); },
14
+ };
15
+ handleWorkspaceFileRead({}, res, { path: filePath }, workspaceDir);
16
+ return out;
17
+ }
18
+
19
+ test('file reads: any absolute path, ~ is home, relative paths resolve against the workspace', () => {
20
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-read-'));
21
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'cc-ws-'));
22
+ fs.writeFileSync(path.join(outside, 'a.md'), 'outside');
23
+ fs.mkdirSync(path.join(workspace, 'notes'));
24
+ fs.writeFileSync(path.join(workspace, 'notes', 'b.md'), 'relative');
25
+ try {
26
+ assert.deepEqual(read(path.join(outside, 'a.md'), workspace), { status: 200, body: 'outside' });
27
+ assert.deepEqual(read('notes/b.md', workspace), { status: 200, body: 'relative' });
28
+ assert.deepEqual(read('./notes/b.md', workspace), { status: 200, body: 'relative' });
29
+ assert.equal(read('notes/missing.md', workspace).status, 404);
30
+ assert.equal(read('notes', workspace).status, 404);
31
+ // `~` only expands as the home segment; "~x" is an ordinary relative name.
32
+ assert.equal(read('~x/b.md', workspace).status, 404);
33
+ } finally {
34
+ fs.rmSync(outside, { recursive: true, force: true });
35
+ fs.rmSync(workspace, { recursive: true, force: true });
36
+ }
37
+ });
38
+
39
+ test('file reads: ~/ expands to home', () => {
40
+ const dir = fs.mkdtempSync(path.join(os.homedir(), '.cc-read-test-'));
41
+ fs.writeFileSync(path.join(dir, 'c.txt'), 'home');
42
+ try {
43
+ const rel = '~/' + path.relative(os.homedir(), path.join(dir, 'c.txt'));
44
+ assert.deepEqual(read(rel, '/nonexistent-workspace'), { status: 200, body: 'home' });
45
+ } finally {
46
+ fs.rmSync(dir, { recursive: true, force: true });
47
+ }
48
+ });
49
+
50
+ function create(query) {
51
+ const out = { status: 0, body: null };
52
+ const res = {
53
+ writeHead(status) { out.status = status; },
54
+ setHeader() {},
55
+ end(body) { out.body = JSON.parse(String(body ?? 'null')); },
56
+ };
57
+ handleWorkspaceCreate({}, res, query);
58
+ return out;
59
+ }
60
+
61
+ test('create: makes an empty file or folder inside home, rejects bad names and existing entries', () => {
62
+ const dir = fs.mkdtempSync(path.join(os.homedir(), '.cc-create-test-'));
63
+ const tilde = '~/' + path.relative(os.homedir(), dir);
64
+ try {
65
+ assert.equal(create({ path: tilde, name: 'sub', type: 'dir' }).status, 200);
66
+ assert.ok(fs.statSync(path.join(dir, 'sub')).isDirectory());
67
+ const file = create({ path: path.join(dir, 'sub'), name: 'a.md', type: 'file' });
68
+ assert.equal(file.status, 200);
69
+ assert.equal(file.body.path, path.join(dir, 'sub', 'a.md'));
70
+ assert.equal(fs.readFileSync(path.join(dir, 'sub', 'a.md'), 'utf8'), '');
71
+ assert.equal(create({ path: dir, name: 'sub', type: 'dir' }).status, 409);
72
+ assert.equal(create({ path: dir, name: 'sub', type: 'file' }).status, 409);
73
+ for (const name of ['..', '.', 'a/b', 'a\\b', ' x', '']) {
74
+ assert.notEqual(create({ path: dir, name, type: 'dir' }).status, 200, name);
75
+ }
76
+ assert.equal(create({ path: dir, name: 'x', type: 'link' }).status, 400);
77
+ assert.equal(create({ path: path.join(dir, 'missing'), name: 'x', type: 'dir' }).status, 404);
78
+ assert.equal(create({ path: '/tmp', name: 'cc-x', type: 'dir' }).status, 403);
79
+ assert.equal(create({ path: os.homedir() + '-sibling', name: 'x', type: 'dir' }).status, 403);
80
+ } finally {
81
+ fs.rmSync(dir, { recursive: true, force: true });
82
+ }
83
+ });
package/server/index.js CHANGED
@@ -8,7 +8,7 @@ import { Database } from './bootstrap/native.js';
8
8
  import { GATEWAY_WS_URL, AUTH_TOKEN, discoverWorkspaceDir } from './config.js';
9
9
  import { DebugLogger } from './debug.js';
10
10
  import { GatewayClient } from './gateway.js';
11
- import { handleServeFile, handleWorkspaceList, handleWorkspaceFileRead, handleWorkspaceFileWrite, handleWorkspaceFileDelete, handleWorkspaceUpload } from './controllers/filesystem.js';
11
+ import { handleServeFile, handleWorkspaceList, handleWorkspaceFileRead, handleWorkspaceFileWrite, handleWorkspaceFileDelete, handleWorkspaceUpload, handleWorkspaceCreate } from './controllers/filesystem.js';
12
12
  import { handleTranscribe } from './controllers/transcribe.js';
13
13
  import { createGatewayMediaHandler } from './controllers/gateway-media.js';
14
14
  import { handleStatic } from './controllers/static.js';
@@ -153,10 +153,11 @@ export function createApp(config = {}) {
153
153
  if (method === 'GET' && urlPath === '/api/file') return handleServeFile(req, res, query, workspaceDir);
154
154
  if (method === 'GET' && urlPath === '/api/gw-media') return handleGatewayMedia(req, res, query);
155
155
  if (method === 'GET' && urlPath === '/api/workspace') return handleWorkspaceList(req, res, query);
156
- if (method === 'GET' && urlPath === '/api/workspace/file') return handleWorkspaceFileRead(req, res, query);
156
+ if (method === 'GET' && urlPath === '/api/workspace/file') return handleWorkspaceFileRead(req, res, query, workspaceDir);
157
157
  if (method === 'PUT' && urlPath === '/api/workspace/file') return await handleWorkspaceFileWrite(req, res, query);
158
158
  if (method === 'DELETE' && urlPath === '/api/workspace/file') return handleWorkspaceFileDelete(req, res, query);
159
159
  if (method === 'POST' && urlPath === '/api/workspace/upload') return await handleWorkspaceUpload(req, res, query);
160
+ if (method === 'POST' && urlPath === '/api/workspace/create') return handleWorkspaceCreate(req, res, query);
160
161
 
161
162
  // Settings & misc
162
163
  if (method === 'GET' && urlPath === '/api/settings') return handleGetSettings(req, res);
@@ -173,7 +174,7 @@ export function createApp(config = {}) {
173
174
  }
174
175
  if ((p = matchRoute(method, urlPath, 'PUT /api/extras/project-styles/:name'))) {
175
176
  const body = await parseBody(req);
176
- extras.setProjectStyle(p.name, { color: body.color, icon: body.icon });
177
+ extras.setProjectStyle(p.name, { color: body.color, icon: body.icon, preset: body.preset });
177
178
  broadcast(JSON.stringify({ type: 'clawchats', event: 'project-styles-changed' }));
178
179
  return send(res, 200, { styles: extras.getProjectStyles() });
179
180
  }
@@ -29,7 +29,7 @@ export const ROW_FIELDS = new Set([
29
29
  'createdAt', 'updatedAt', 'lastActivityAt', 'lastInteractionAt',
30
30
  'status', 'hasActiveRun', 'activeRunIds', 'lastRunId', 'lastRunError', 'endedAt', 'agentStatus',
31
31
  'model', 'modelProvider', 'thinkingLevel', 'contextTokens', 'totalTokens', 'totalTokensFresh',
32
- 'inputTokens', 'outputTokens', 'permissionMode', 'contextBudgetStatus', 'fastMode', 'effectiveFastMode',
32
+ 'inputTokens', 'outputTokens', 'permissionMode', 'workspaceDir', 'contextBudgetStatus', 'fastMode', 'effectiveFastMode',
33
33
  ]);
34
34
 
35
35
  // `sessions.changed` envelope fields (snapshot fields are spread next to these).
@@ -1,16 +1,40 @@
1
1
  // ExtrasStore: ClawChats-only data the gateway has no place for. Lives in the global DB.
2
2
  // Registry of what belongs here: EXTRAS.md at the repo root.
3
3
  //
4
- // project_styles color/icon per gateway session group (groups are just {name, position})
4
+ // project_styles color/icon and new-chat preset per gateway session group (groups are just {name, position})
5
5
  // thread_extras per-session ClawChats data (Intelligence panel etc.), keyed by session key
6
6
  // legacy_created creation time of chats from before the gateway recorded createdAt
7
7
 
8
+ // New-chat preset: what a new chat in the project starts with. Every field is optional;
9
+ // a missing field means the gateway default. `cwd` and `projectId` are exclusive places.
10
+ const PRESET_STRINGS = ['agentId', 'cwd', 'projectId', 'projectLabel', 'permissionMode', 'model', 'thinkingLevel'];
11
+ const PERMISSION_MODES = new Set(['read-only', 'guarded', 'workspace', 'full']);
12
+
13
+ export function cleanPreset(p) {
14
+ if (!p || typeof p !== 'object' || Array.isArray(p)) return null;
15
+ const out = {};
16
+ for (const k of PRESET_STRINGS) {
17
+ if (typeof p[k] === 'string' && p[k].trim()) out[k] = p[k].trim().slice(0, 1000);
18
+ }
19
+ if (out.permissionMode && !PERMISSION_MODES.has(out.permissionMode)) delete out.permissionMode;
20
+ if (out.projectId) delete out.cwd;
21
+ else delete out.projectLabel;
22
+ if (typeof p.fastMode === 'boolean') out.fastMode = p.fastMode;
23
+ return Object.keys(out).length ? out : null;
24
+ }
25
+
26
+ function parsePreset(text) {
27
+ if (!text) return null;
28
+ try { return cleanPreset(JSON.parse(text)); } catch { return null; }
29
+ }
30
+
8
31
  export function createExtrasStore(getGlobalDb) {
9
32
  let ready = false;
10
33
  function db() {
11
34
  const g = getGlobalDb();
12
35
  if (!ready) {
13
36
  g.exec(`CREATE TABLE IF NOT EXISTS project_styles (name TEXT PRIMARY KEY, color TEXT, icon TEXT, updated_at INTEGER NOT NULL)`);
37
+ if (!g.prepare('PRAGMA table_info(project_styles)').all().some(c => c.name === 'preset')) g.exec('ALTER TABLE project_styles ADD COLUMN preset TEXT');
14
38
  g.exec(`CREATE TABLE IF NOT EXISTS legacy_created (session_key TEXT PRIMARY KEY, created_at INTEGER NOT NULL)`);
15
39
  g.exec(`CREATE TABLE IF NOT EXISTS thread_extras (session_key TEXT NOT NULL, kind TEXT NOT NULL, data TEXT NOT NULL, updated_at INTEGER NOT NULL, PRIMARY KEY (session_key, kind))`);
16
40
  ready = true;
@@ -19,19 +43,22 @@ export function createExtrasStore(getGlobalDb) {
19
43
  }
20
44
 
21
45
  return {
22
- /** { [groupName]: { color, icon } } */
46
+ /** { [groupName]: { color, icon, preset } } */
23
47
  getProjectStyles() {
24
48
  const out = {};
25
- for (const r of db().prepare('SELECT name, color, icon FROM project_styles').all()) out[r.name] = { color: r.color, icon: r.icon };
49
+ for (const r of db().prepare('SELECT name, color, icon, preset FROM project_styles').all()) {
50
+ out[r.name] = { color: r.color, icon: r.icon, preset: parsePreset(r.preset) };
51
+ }
26
52
  return out;
27
53
  },
28
54
 
29
- /** Set color and/or icon; absent fields keep their value, null clears. */
30
- setProjectStyle(name, { color, icon } = {}) {
55
+ /** Set color, icon and/or new-chat preset; absent fields keep their value, null clears. */
56
+ setProjectStyle(name, { color, icon, preset } = {}) {
31
57
  if (!name) return;
32
- const cur = db().prepare('SELECT color, icon FROM project_styles WHERE name = ?').get(name) || {};
33
- db().prepare('INSERT INTO project_styles (name, color, icon, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET color = excluded.color, icon = excluded.icon, updated_at = excluded.updated_at')
34
- .run(name, color !== undefined ? color : (cur.color ?? null), icon !== undefined ? icon : (cur.icon ?? null), Date.now());
58
+ const cur = db().prepare('SELECT color, icon, preset FROM project_styles WHERE name = ?').get(name) || {};
59
+ const nextPreset = preset === undefined ? (cur.preset ?? null) : (cleanPreset(preset) ? JSON.stringify(cleanPreset(preset)) : null);
60
+ db().prepare('INSERT INTO project_styles (name, color, icon, preset, updated_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET color = excluded.color, icon = excluded.icon, preset = excluded.preset, updated_at = excluded.updated_at')
61
+ .run(name, color !== undefined ? color : (cur.color ?? null), icon !== undefined ? icon : (cur.icon ?? null), nextPreset, Date.now());
35
62
  },
36
63
 
37
64
  renameProjectStyle(from, to) {
@@ -0,0 +1,45 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { Database } from '../bootstrap/native.js';
4
+ import { createExtrasStore, cleanPreset } from './extras-store.js';
5
+
6
+ test('project preset: stored with the style, kept when only color changes, cleared by null, follows rename/delete', () => {
7
+ const db = new Database(':memory:');
8
+ const extras = createExtrasStore(() => db);
9
+ extras.setProjectStyle('Work', { color: 'red' });
10
+ assert.deepEqual(extras.getProjectStyles().Work, { color: 'red', icon: null, preset: null });
11
+
12
+ extras.setProjectStyle('Work', { preset: { agentId: 'dev', cwd: '/home/u/repos', permissionMode: 'full', thinkingLevel: 'high', fastMode: false } });
13
+ extras.setProjectStyle('Work', { color: 'blue' });
14
+ assert.deepEqual(extras.getProjectStyles().Work, {
15
+ color: 'blue', icon: null,
16
+ preset: { agentId: 'dev', cwd: '/home/u/repos', permissionMode: 'full', thinkingLevel: 'high', fastMode: false },
17
+ });
18
+
19
+ extras.renameProjectStyle('Work', 'Job');
20
+ assert.equal(extras.getProjectStyles().Job.preset.agentId, 'dev');
21
+ extras.setProjectStyle('Job', { preset: null });
22
+ assert.equal(extras.getProjectStyles().Job.preset, null);
23
+ extras.deleteProjectStyle('Job');
24
+ assert.equal(extras.getProjectStyles().Job, undefined);
25
+ });
26
+
27
+ test('project preset: adds the column to an existing table', () => {
28
+ const db = new Database(':memory:');
29
+ db.exec('CREATE TABLE project_styles (name TEXT PRIMARY KEY, color TEXT, icon TEXT, updated_at INTEGER NOT NULL)');
30
+ db.prepare('INSERT INTO project_styles VALUES (?, ?, ?, ?)').run('Old', 'green', null, 1);
31
+ const extras = createExtrasStore(() => db);
32
+ assert.deepEqual(extras.getProjectStyles().Old, { color: 'green', icon: null, preset: null });
33
+ extras.setProjectStyle('Old', { preset: { model: 'anthropic/claude-opus-5-5' } });
34
+ assert.deepEqual(extras.getProjectStyles().Old.preset, { model: 'anthropic/claude-opus-5-5' });
35
+ });
36
+
37
+ test('cleanPreset: known fields only, valid permission mode, projectId wins over cwd', () => {
38
+ assert.equal(cleanPreset(null), null);
39
+ assert.equal(cleanPreset({}), null);
40
+ assert.equal(cleanPreset({ junk: 'x', agentId: ' ' }), null);
41
+ assert.deepEqual(cleanPreset({ permissionMode: 'yolo', agentId: 'dev' }), { agentId: 'dev' });
42
+ assert.deepEqual(cleanPreset({ cwd: '/a', projectId: 'p1', projectLabel: 'Repo' }), { projectId: 'p1', projectLabel: 'Repo' });
43
+ assert.deepEqual(cleanPreset({ cwd: '/a', projectLabel: 'Repo' }), { cwd: '/a' });
44
+ assert.deepEqual(cleanPreset({ fastMode: true }), { fastMode: true });
45
+ });