nyk commited on
Commit
7446200
·
unverified ·
1 Parent(s): be80b82

feat: provision full OpenClaw workspaces from agent creation

Browse files
src/app/api/agents/route.ts CHANGED
@@ -8,6 +8,10 @@ import { requireRole } from '@/lib/auth';
8
  import { mutationLimiter } from '@/lib/rate-limit';
9
  import { logger } from '@/lib/logger';
10
  import { validateBody, createAgentSchema } from '@/lib/validation';
 
 
 
 
11
 
12
  /**
13
  * GET /api/agents - List all agents with optional filtering
@@ -123,6 +127,7 @@ export async function POST(request: NextRequest) {
123
 
124
  const {
125
  name,
 
126
  role,
127
  session_key,
128
  soul_content,
@@ -130,9 +135,16 @@ export async function POST(request: NextRequest) {
130
  config = {},
131
  template,
132
  gateway_config,
133
- write_to_gateway
 
 
134
  } = body;
135
 
 
 
 
 
 
136
  // Resolve template if specified
137
  let finalRole = role;
138
  let finalConfig: Record<string, any> = { ...config };
@@ -158,6 +170,32 @@ export async function POST(request: NextRequest) {
158
  if (existingAgent) {
159
  return NextResponse.json({ error: 'Agent name already exists' }, { status: 409 });
160
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
  const now = Math.floor(Date.now() / 1000);
163
 
@@ -215,7 +253,6 @@ export async function POST(request: NextRequest) {
215
  // Write to gateway config if requested
216
  if (write_to_gateway && finalConfig) {
217
  try {
218
- const openclawId = (name || 'agent').toLowerCase().replace(/\s+/g, '-');
219
  await writeAgentToConfig({
220
  id: openclawId,
221
  name,
 
8
  import { mutationLimiter } from '@/lib/rate-limit';
9
  import { logger } from '@/lib/logger';
10
  import { validateBody, createAgentSchema } from '@/lib/validation';
11
+ import { runOpenClaw } from '@/lib/command';
12
+ import { config as appConfig } from '@/lib/config';
13
+ import { resolveWithin } from '@/lib/paths';
14
+ import path from 'node:path';
15
 
16
  /**
17
  * GET /api/agents - List all agents with optional filtering
 
127
 
128
  const {
129
  name,
130
+ openclaw_id,
131
  role,
132
  session_key,
133
  soul_content,
 
135
  config = {},
136
  template,
137
  gateway_config,
138
+ write_to_gateway,
139
+ provision_openclaw_workspace,
140
+ openclaw_workspace_path
141
  } = body;
142
 
143
+ const openclawId = (openclaw_id || name || 'agent')
144
+ .toLowerCase()
145
+ .replace(/[^a-z0-9]+/g, '-')
146
+ .replace(/^-|-$/g, '');
147
+
148
  // Resolve template if specified
149
  let finalRole = role;
150
  let finalConfig: Record<string, any> = { ...config };
 
170
  if (existingAgent) {
171
  return NextResponse.json({ error: 'Agent name already exists' }, { status: 409 });
172
  }
173
+
174
+ if (provision_openclaw_workspace) {
175
+ if (!appConfig.openclawStateDir) {
176
+ return NextResponse.json(
177
+ { error: 'OPENCLAW_STATE_DIR is not configured; cannot provision OpenClaw workspace' },
178
+ { status: 500 }
179
+ );
180
+ }
181
+
182
+ const workspacePath = openclaw_workspace_path
183
+ ? path.resolve(openclaw_workspace_path)
184
+ : resolveWithin(appConfig.openclawStateDir, path.join('workspaces', openclawId));
185
+
186
+ try {
187
+ await runOpenClaw(
188
+ ['agents', 'add', openclawId, '--name', name, '--workspace', workspacePath, '--non-interactive'],
189
+ { timeoutMs: 20000 }
190
+ );
191
+ } catch (provisionError: any) {
192
+ logger.error({ err: provisionError, openclawId, workspacePath }, 'OpenClaw workspace provisioning failed');
193
+ return NextResponse.json(
194
+ { error: provisionError?.message || 'Failed to provision OpenClaw agent workspace' },
195
+ { status: 502 }
196
+ );
197
+ }
198
+ }
199
 
200
  const now = Math.floor(Date.now() / 1000);
201
 
 
253
  // Write to gateway config if requested
254
  if (write_to_gateway && finalConfig) {
255
  try {
 
256
  await writeAgentToConfig({
257
  id: openclawId,
258
  name,
src/components/panels/agent-detail-tabs.tsx CHANGED
@@ -852,6 +852,7 @@ export function CreateAgentModal({
852
  dockerNetwork: 'none' as 'none' | 'bridge',
853
  session_key: '',
854
  write_to_gateway: true,
 
855
  })
856
  const [isCreating, setIsCreating] = useState(false)
857
  const [error, setError] = useState<string | null>(null)
@@ -916,10 +917,12 @@ export function CreateAgentModal({
916
  headers: { 'Content-Type': 'application/json' },
917
  body: JSON.stringify({
918
  name: formData.name,
 
919
  role: formData.role,
920
  session_key: formData.session_key || undefined,
921
  template: selectedTemplate || undefined,
922
  write_to_gateway: formData.write_to_gateway,
 
923
  gateway_config: {
924
  model: { primary: primaryModel },
925
  identity: { name: formData.name, theme: formData.role, emoji: formData.emoji },
@@ -1199,6 +1202,16 @@ export function CreateAgentModal({
1199
  />
1200
  <span className="text-sm text-foreground">Add to gateway config (openclaw.json)</span>
1201
  </label>
 
 
 
 
 
 
 
 
 
 
1202
  </div>
1203
  )}
1204
  </div>
 
852
  dockerNetwork: 'none' as 'none' | 'bridge',
853
  session_key: '',
854
  write_to_gateway: true,
855
+ provision_openclaw_workspace: true,
856
  })
857
  const [isCreating, setIsCreating] = useState(false)
858
  const [error, setError] = useState<string | null>(null)
 
917
  headers: { 'Content-Type': 'application/json' },
918
  body: JSON.stringify({
919
  name: formData.name,
920
+ openclaw_id: formData.id || undefined,
921
  role: formData.role,
922
  session_key: formData.session_key || undefined,
923
  template: selectedTemplate || undefined,
924
  write_to_gateway: formData.write_to_gateway,
925
+ provision_openclaw_workspace: formData.provision_openclaw_workspace,
926
  gateway_config: {
927
  model: { primary: primaryModel },
928
  identity: { name: formData.name, theme: formData.role, emoji: formData.emoji },
 
1202
  />
1203
  <span className="text-sm text-foreground">Add to gateway config (openclaw.json)</span>
1204
  </label>
1205
+
1206
+ <label className="flex items-center gap-2 cursor-pointer">
1207
+ <input
1208
+ type="checkbox"
1209
+ checked={formData.provision_openclaw_workspace}
1210
+ onChange={(e) => setFormData(prev => ({ ...prev, provision_openclaw_workspace: e.target.checked }))}
1211
+ className="w-4 h-4 rounded border-border"
1212
+ />
1213
+ <span className="text-sm text-foreground">Provision full OpenClaw workspace (`openclaw agents add`)</span>
1214
+ </label>
1215
  </div>
1216
  )}
1217
  </div>
src/lib/validation.ts CHANGED
@@ -45,6 +45,7 @@ export const updateTaskSchema = createTaskSchema.partial()
45
 
46
  export const createAgentSchema = z.object({
47
  name: z.string().min(1, 'Name is required').max(100),
 
48
  role: z.string().min(1, 'Role is required').max(100).optional(),
49
  session_key: z.string().max(200).optional(),
50
  soul_content: z.string().max(50000).optional(),
@@ -53,6 +54,8 @@ export const createAgentSchema = z.object({
53
  template: z.string().max(100).optional(),
54
  gateway_config: z.record(z.string(), z.unknown()).optional(),
55
  write_to_gateway: z.boolean().optional(),
 
 
56
  })
57
 
58
  export const bulkUpdateTaskStatusSchema = z.object({
 
45
 
46
  export const createAgentSchema = z.object({
47
  name: z.string().min(1, 'Name is required').max(100),
48
+ openclaw_id: z.string().regex(/^[a-z0-9][a-z0-9-]*$/, 'openclaw_id must be kebab-case').max(100).optional(),
49
  role: z.string().min(1, 'Role is required').max(100).optional(),
50
  session_key: z.string().max(200).optional(),
51
  soul_content: z.string().max(50000).optional(),
 
54
  template: z.string().max(100).optional(),
55
  gateway_config: z.record(z.string(), z.unknown()).optional(),
56
  write_to_gateway: z.boolean().optional(),
57
+ provision_openclaw_workspace: z.boolean().optional(),
58
+ openclaw_workspace_path: z.string().min(1).max(500).optional(),
59
  })
60
 
61
  export const bulkUpdateTaskStatusSchema = z.object({