-
Notifications
You must be signed in to change notification settings - Fork 42
feat(kiloclaw): add agent config CRUD routes #3508
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e6f73f4
feat(kiloclaw): add agent config CRUD routes
pandemicsyn 9745e28
chore(kiloclaw): enable controller typecheck checks
pandemicsyn 13e129e
fix(kiloclaw): normalize agent CLI result IDs
pandemicsyn 0ce37e7
test(kiloclaw): validate created agent config in smoke test
pandemicsyn 8072d48
fix(kiloclaw): harden agent config CRUD inputs
pandemicsyn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
105 changes: 105 additions & 0 deletions
105
services/kiloclaw/controller/src/openclaw-agent-cli.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import { describe, expect, it, vi } from 'vitest'; | ||
| import { | ||
| BasicAgentCreateBodySchema, | ||
| OpenClawAgentCliError, | ||
| createAgentViaCli, | ||
| deleteAgentViaCli, | ||
| } from './openclaw-agent-cli'; | ||
|
|
||
| describe('createAgentViaCli', () => { | ||
| it('uses argv-only non-interactive JSON creation arguments', async () => { | ||
| const run = vi.fn(async () => ({ | ||
| stdout: JSON.stringify({ | ||
| agentId: 'Research Agent', | ||
| name: 'Research', | ||
| workspace: '/root/.openclaw/workspace-research', | ||
| agentDir: '/root/.openclaw/agents/research/agent', | ||
| model: 'kilocode/default', | ||
| bindings: { added: [], updated: [], skipped: [], conflicts: [] }, | ||
| }), | ||
| stderr: '', | ||
| })); | ||
| const body = BasicAgentCreateBodySchema.parse({ | ||
| name: 'Research', | ||
| workspace: '/root/.openclaw/workspace-research', | ||
| agentDir: '/root/.openclaw/agents/research/agent', | ||
| model: 'kilocode/default', | ||
| bindings: ['discord:team'], | ||
| }); | ||
|
|
||
| const result = await createAgentViaCli(body, { run }); | ||
|
|
||
| expect(result.agentId).toBe('research-agent'); | ||
| expect(run).toHaveBeenCalledWith([ | ||
| 'agents', | ||
| 'add', | ||
| 'Research', | ||
| '--workspace', | ||
| '/root/.openclaw/workspace-research', | ||
| '--agent-dir', | ||
| '/root/.openclaw/agents/research/agent', | ||
| '--model', | ||
| 'kilocode/default', | ||
| '--bind', | ||
| 'discord:team', | ||
| '--non-interactive', | ||
| '--json', | ||
| ]); | ||
| }); | ||
|
|
||
| it('rejects option-like create values before constructing CLI arguments', () => { | ||
| for (const body of [ | ||
| { name: '--help', workspace: '/tmp/research' }, | ||
| { name: 'Research', workspace: '/tmp/research', model: '--config=/tmp/other.json' }, | ||
| { name: 'Research', workspace: '/tmp/research', bindings: ['--debug'] }, | ||
| ]) { | ||
| expect(BasicAgentCreateBodySchema.safeParse(body).success).toBe(false); | ||
| } | ||
| }); | ||
|
|
||
| it('rejects malformed CLI JSON output', async () => { | ||
| await expect( | ||
| createAgentViaCli( | ||
| BasicAgentCreateBodySchema.parse({ name: 'Research', workspace: '/tmp/research' }), | ||
| { run: async () => ({ stdout: 'not-json', stderr: '' }) } | ||
| ) | ||
| ).rejects.toMatchObject({ code: 'openclaw_cli_failed', status: 502 }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('deleteAgentViaCli', () => { | ||
| it('uses forced JSON deletion arguments and parses deletion summary', async () => { | ||
| const run = vi.fn(async () => ({ | ||
| stdout: JSON.stringify({ | ||
| agentId: 'Research Agent', | ||
| workspace: '/root/.openclaw/workspace-research', | ||
| agentDir: '/root/.openclaw/agents/research/agent', | ||
| sessionsDir: '/root/.openclaw/agents/research/sessions', | ||
| removedBindings: 2, | ||
| removedAllow: 1, | ||
| }), | ||
| stderr: '', | ||
| })); | ||
|
|
||
| const result = await deleteAgentViaCli('research', { run }); | ||
|
|
||
| expect(run).toHaveBeenCalledWith(['agents', 'delete', 'research', '--force', '--json']); | ||
| expect(result.agentId).toBe('research-agent'); | ||
| expect(result.removedBindings).toBe(2); | ||
| expect(result.removedAllow).toBe(1); | ||
| }); | ||
|
|
||
| it('propagates typed CLI operation failures', async () => { | ||
| await expect( | ||
| deleteAgentViaCli('main', { | ||
| run: async () => { | ||
| throw new OpenClawAgentCliError( | ||
| 400, | ||
| 'reserved_agent_id', | ||
| 'The default agent is reserved' | ||
| ); | ||
| }, | ||
| }) | ||
| ).rejects.toMatchObject({ code: 'reserved_agent_id', status: 400 }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,187 @@ | ||
| import { execFile } from 'node:child_process'; | ||
| import path from 'node:path'; | ||
| import { z } from 'zod'; | ||
| import { normalizeAgentId } from './openclaw-agent-config'; | ||
|
|
||
| const AGENT_CLI_TIMEOUT_MS = 30_000; | ||
| const AGENT_CLI_MAX_OUTPUT_BYTES = 1_048_576; | ||
|
|
||
| const CliValueSchema = z | ||
| .string() | ||
| .trim() | ||
| .min(1) | ||
| .refine(value => !value.startsWith('-'), { | ||
| message: 'CLI value must not begin with a dash', | ||
| }); | ||
|
|
||
| export const BasicAgentCreateBodySchema = z | ||
| .object({ | ||
| name: CliValueSchema, | ||
| workspace: z | ||
| .string() | ||
| .trim() | ||
| .min(1) | ||
| .refine(value => path.isAbsolute(value), { | ||
| message: 'Workspace must be an absolute path', | ||
| }), | ||
| agentDir: z | ||
| .string() | ||
| .trim() | ||
| .min(1) | ||
| .refine(value => path.isAbsolute(value), { | ||
| message: 'Agent directory must be an absolute path', | ||
| }) | ||
| .optional(), | ||
| model: CliValueSchema.optional(), | ||
| bindings: z.array(CliValueSchema).optional(), | ||
| }) | ||
| .strict(); | ||
|
|
||
| export type BasicAgentCreateBody = z.infer<typeof BasicAgentCreateBodySchema>; | ||
|
|
||
| const NormalizedCliAgentIdSchema = z.string().trim().min(1).transform(normalizeAgentId); | ||
|
|
||
| const CreateResultSchema = z.object({ | ||
| agentId: NormalizedCliAgentIdSchema, | ||
| name: z.string().min(1), | ||
| workspace: z.string().min(1), | ||
| agentDir: z.string().min(1), | ||
| model: z.string().optional(), | ||
| bindings: z | ||
| .object({ | ||
| added: z.array(z.string()), | ||
| updated: z.array(z.string()), | ||
| skipped: z.array(z.string()), | ||
| conflicts: z.array(z.string()), | ||
| }) | ||
| .optional(), | ||
| }); | ||
|
|
||
| const DeleteResultSchema = z.object({ | ||
| agentId: NormalizedCliAgentIdSchema, | ||
| workspace: z.string().min(1), | ||
| agentDir: z.string().min(1), | ||
| sessionsDir: z.string().min(1), | ||
| removedBindings: z.number().int().min(0), | ||
| removedAllow: z.number().int().min(0), | ||
| }); | ||
|
|
||
| export type CreateAgentCliResult = z.infer<typeof CreateResultSchema>; | ||
| export type DeleteAgentCliResult = z.infer<typeof DeleteResultSchema>; | ||
|
|
||
| type CliProcessResult = { | ||
| stdout: string; | ||
| stderr: string; | ||
| }; | ||
|
|
||
| export type OpenClawAgentCliDeps = { | ||
| run: (args: string[]) => Promise<CliProcessResult>; | ||
| }; | ||
|
|
||
| export class OpenClawAgentCliError extends Error { | ||
| readonly status: number; | ||
| readonly code: string; | ||
|
|
||
| constructor(status: number, code: string, message: string) { | ||
| super(message); | ||
| this.name = 'OpenClawAgentCliError'; | ||
| this.status = status; | ||
| this.code = code; | ||
| } | ||
| } | ||
|
|
||
| const defaultDeps: OpenClawAgentCliDeps = { | ||
| run: args => | ||
| new Promise((resolve, reject) => { | ||
| execFile( | ||
| 'openclaw', | ||
| args, | ||
| { | ||
| env: process.env, | ||
| timeout: AGENT_CLI_TIMEOUT_MS, | ||
| maxBuffer: AGENT_CLI_MAX_OUTPUT_BYTES, | ||
| encoding: 'utf8', | ||
| }, | ||
| (error, stdout, stderr) => { | ||
| if (error) { | ||
| if ('killed' in error && error.killed === true) { | ||
| reject( | ||
| new OpenClawAgentCliError( | ||
| 504, | ||
| 'openclaw_cli_timeout', | ||
| 'OpenClaw agent command timed out' | ||
| ) | ||
| ); | ||
| return; | ||
| } | ||
| reject(mapCliFailure(`${stderr}\n${error.message}`)); | ||
| return; | ||
| } | ||
| resolve({ stdout, stderr }); | ||
| } | ||
| ); | ||
| }), | ||
| }; | ||
|
|
||
| function mapCliFailure(output: string): OpenClawAgentCliError { | ||
| if (/cannot be deleted|is reserved/i.test(output)) { | ||
| return new OpenClawAgentCliError(400, 'reserved_agent_id', 'The default agent is reserved'); | ||
| } | ||
| if (/already exists/i.test(output)) { | ||
| return new OpenClawAgentCliError(409, 'agent_exists', 'Agent already exists'); | ||
| } | ||
| if (/not found/i.test(output)) { | ||
| return new OpenClawAgentCliError(404, 'agent_not_found', 'Agent not found'); | ||
| } | ||
| return new OpenClawAgentCliError(502, 'openclaw_cli_failed', 'OpenClaw agent command failed'); | ||
| } | ||
|
|
||
| function parseCliJson<T>(stdout: string, schema: z.ZodType<T>): T { | ||
| let parsed: unknown; | ||
| try { | ||
| parsed = JSON.parse(stdout.trim()); | ||
| } catch { | ||
| throw new OpenClawAgentCliError( | ||
| 502, | ||
| 'openclaw_cli_failed', | ||
| 'OpenClaw agent command returned invalid JSON' | ||
| ); | ||
| } | ||
| const result = schema.safeParse(parsed); | ||
| if (!result.success) { | ||
| throw new OpenClawAgentCliError( | ||
| 502, | ||
| 'openclaw_cli_failed', | ||
| 'OpenClaw agent command returned an invalid response' | ||
| ); | ||
| } | ||
| return result.data; | ||
| } | ||
|
|
||
| export async function createAgentViaCli( | ||
| body: BasicAgentCreateBody, | ||
| deps: OpenClawAgentCliDeps = defaultDeps | ||
| ): Promise<CreateAgentCliResult> { | ||
| const args = [ | ||
| 'agents', | ||
| 'add', | ||
| body.name, | ||
| '--workspace', | ||
| body.workspace, | ||
| ...(body.agentDir ? ['--agent-dir', body.agentDir] : []), | ||
| ...(body.model ? ['--model', body.model] : []), | ||
| ...(body.bindings ?? []).flatMap(binding => ['--bind', binding]), | ||
| '--non-interactive', | ||
| '--json', | ||
| ]; | ||
| const result = await deps.run(args); | ||
| return parseCliJson(result.stdout, CreateResultSchema); | ||
| } | ||
|
|
||
| export async function deleteAgentViaCli( | ||
| agentId: string, | ||
| deps: OpenClawAgentCliDeps = defaultDeps | ||
| ): Promise<DeleteAgentCliResult> { | ||
| const result = await deps.run(['agents', 'delete', agentId, '--force', '--json']); | ||
| return parseCliJson(result.stdout, DeleteResultSchema); | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.