Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/quiet-agent-sections.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Allow Agent Manager sessions to move their worktree between sections or ungroup it through the `agent_manager` tool.
4 changes: 2 additions & 2 deletions packages/kilo-docs/pages/automate/agent-manager.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,9 @@ Each request can include 1-20 tasks. Each task must include at least one of `pro

The companion `agent_manager_models` tool searches models and their supported reasoning variants on demand. Results are grouped by model name (with the offering providers listed for reference) and limited to 20 per call, so the full catalog is never added to the conversation context.

The same tool also manages existing sessions. It can return a compact overview of sections, worktrees, and local sessions, send a prompt to one managed session, or stop a managed session. Stopping aborts the session's active work and removes it from the panel, just like closing the session tab.
The same tool also manages existing sessions. It can return an overview of sections, worktrees, and local sessions, send a prompt to one managed session, stop a managed session, or move a session's worktree into a section. The overview includes section IDs, each section's assigned worktrees, worktree IDs, and session IDs. Use those exact IDs for a subsequent move. Moving accepts a section ID from the overview, or `null` to ungroup the worktree. Moving a session moves its whole worktree, including multi-version siblings. Local sessions cannot be assigned to a section. Stopping aborts the session's active work and removes it from the panel, just like closing the session tab.

The tool uses the `agent_manager` permission. Approval prompts are scoped to the requested capability, so approving `worktree` does not automatically approve `local`, an overview, or a targeted prompt. Prompting an existing managed session requires an explicit `prompt` approval the first time, even if Agent Manager session creation was previously approved broadly. Stopping a session likewise requires an explicit `stop` approval.
The tool uses the `agent_manager` permission. Approval prompts are scoped to the requested capability, so approving `worktree` does not automatically approve `local`, an overview, or a targeted prompt. Prompting an existing managed session requires an explicit `prompt` approval the first time, even if Agent Manager session creation was previously approved broadly. Stopping a session likewise requires an explicit `stop` approval, and moving a worktree requires an explicit `move` approval.

## Sections

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ export class AgentManagerProvider implements Disposable {
},
stats: (refresh) => this.statsPoller.snapshot(refresh),
prs: () => this.prBridge.snapshot(),
push: () => this.pushState(),
managed: (id) => this.panelSessions.has(id) || !!this.state?.getSession(id),
close: async (id) => {
await this.onCloseSession(id)
Expand Down
17 changes: 17 additions & 0 deletions packages/kilo-vscode/src/agent-manager/orchestration-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type { PRStatus } from "./types"
import type { WorktreeStateManager } from "./WorktreeStateManager"
import {
OrchestrationError,
move,
overview,
prompt,
sameManagedDirectory,
Expand All @@ -26,11 +27,13 @@ type Request =
| (RequestBase & { operation: "overview"; filter?: OverviewFilter })
| (RequestBase & { operation: "prompt"; targetSessionID: string; prompt: string })
| (RequestBase & { operation: "stop"; targetSessionID: string })
| (RequestBase & { operation: "move"; targetSessionID: string; sectionID: string | null })

type Result =
| { operation: "overview"; overview: Overview }
| { operation: "prompt"; sessionID: string; delivered: true }
| { operation: "stop"; sessionID: string; stopped: true }
| { operation: "move"; sessionID: string; sectionID: string | null; moved: true }

interface Failure {
code: FailureCode | "cancelled" | "disconnected" | "timeout"
Expand All @@ -43,6 +46,7 @@ interface Options {
state(): WorktreeStateManager | undefined
stats(refresh?: boolean): Promise<{ worktrees: WorktreeStats[]; local?: LocalStats }>
prs(): Map<string, PRStatus>
push(): void
managed(sessionID: string): boolean
close(sessionID: string): Promise<void>
log(...args: unknown[]): void
Expand Down Expand Up @@ -279,6 +283,19 @@ export class AgentManagerOrchestrationBridge {
if (this.disposed || active.cancelled) return
return { result: { operation: "prompt", sessionID: request.targetSessionID, delivered: true } }
}
if (request.operation === "move") {
move({ state, sessionID: request.targetSessionID, sectionID: request.sectionID })
this.options.push()
if (this.disposed || active.cancelled) return
return {
result: {
operation: "move",
sessionID: request.targetSessionID,
sectionID: request.sectionID,
moved: true,
},
}
}
if (!this.options.managed(request.targetSessionID)) {
throw new OrchestrationError("unknown_session", "The session is not managed by this Agent Manager workspace")
}
Expand Down
18 changes: 18 additions & 0 deletions packages/kilo-vscode/src/agent-manager/orchestration-domain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export type FailureCode =
| "host_error"
| "stale_session"
| "unavailable_session"
| "unknown_section"
| "unknown_session"
| "workspace_unavailable"

Expand Down Expand Up @@ -362,3 +363,20 @@ export async function prompt(input: {
{ throwOnError: true },
)
}

export function move(input: { state: WorktreeStateManager; sessionID: string; sectionID: string | null }): void {
const session = input.state.getSession(input.sessionID)
if (!session)
throw new OrchestrationError("unknown_session", "The session is not managed by this Agent Manager workspace")
if (!session.worktreeId) {
if (input.sectionID === null) return
throw new OrchestrationError(
"unavailable_session",
"Only sessions attached to a worktree can be assigned to a section",
)
}
if (input.sectionID !== null && !input.state.getSection(input.sectionID)) {
throw new OrchestrationError("unknown_section", "The target section is not managed by this Agent Manager workspace")
}
input.state.moveToSection([session.worktreeId], input.sectionID)
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ describe("AgentManagerOrchestrationBridge", () => {
const managed = new Set(["ses_target"])
const promptAsync = mock(async () => ({ data: undefined }))
const close = mock(async () => undefined)
const push = mock(() => undefined)
const client = {
session: {
get: mock(async () => ({
Expand Down Expand Up @@ -97,6 +98,7 @@ describe("AgentManagerOrchestrationBridge", () => {
state: () => state,
stats: async () => ({ worktrees: [] }),
prs: () => new Map(),
push,
managed: (id) => managed.has(id),
close,
log: () => undefined,
Expand All @@ -106,7 +108,7 @@ describe("AgentManagerOrchestrationBridge", () => {
{ id: `event-${value.id}`, type: "kilocode.agent_manager.requested", properties: value } as SSEPayload,
directory,
)
return { bridge, client, close, handlers, lists, managed, promptAsync, rejections, replies, request, status }
return { bridge, client, close, handlers, lists, managed, promptAsync, push, rejections, replies, request, status }
}

const request: AgentManagerRequest = {
Expand Down Expand Up @@ -185,6 +187,52 @@ describe("AgentManagerOrchestrationBridge", () => {
test.bridge.dispose()
})

it("moves its own worktree into a section and then ungroups it", async () => {
const test = harness()
const section = state.addSection("Review", null)

test.request(
{
id: "amr_move",
sessionID: "ses_target",
operation: "move",
targetSessionID: "ses_target",
sectionID: section.id,
},
dir,
)
await waitFor(() => test.replies.length === 1)

const worktreeID = state.getSession("ses_target")!.worktreeId!
expect(state.getWorktree(worktreeID)?.sectionId).toBe(section.id)
expect(test.push).toHaveBeenCalledTimes(1)
expect(test.replies[0]).toEqual({
requestID: "amr_move",
directory: dir,
result: { operation: "move", sessionID: "ses_target", sectionID: section.id, moved: true },
})

test.request(
{
id: "amr_ungroup",
sessionID: "ses_target",
operation: "move",
targetSessionID: "ses_target",
sectionID: null,
},
dir,
)
await waitFor(() => test.replies.length === 2)

expect(state.getWorktree(worktreeID)?.sectionId).toBeUndefined()
expect(test.replies[1]).toEqual({
requestID: "amr_ungroup",
directory: dir,
result: { operation: "move", sessionID: "ses_target", sectionID: null, moved: true },
})
test.bridge.dispose()
})

it("stops a live panel session before it is persisted", async () => {
const test = harness()
test.managed.add("ses_live")
Expand Down
11 changes: 11 additions & 0 deletions packages/opencode/src/kilocode/agent-manager/protection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import * as path from "path"

export function assertMutablePath(filepath: string) {
const parts = filepath.split(path.sep)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Splitting on path.sep without normalizing lets the guard be bypassed

edit.ts and write.ts pass params.filePath through verbatim when it is absolute (path.isAbsolute(params.filePath) ? params.filePath : path.join(...)), so assertMutablePath can receive an unnormalized path:

  • On Windows, path.sep is \, but a model commonly emits forward slashes. C:/proj/.kilo/agent-manager.json splits into a single element, file becomes the whole string, and the guard returns early — the write goes through.
  • On POSIX, /proj/.kilo/./agent-manager.json yields dir === ".", and /proj/.kilo//agent-manager.json yields dir === "". Both bypass the check.

(apply_patch.ts is fine because it resolves the path first.) Normalizing fixes all three cases:

Suggested change
const parts = filepath.split(path.sep)
const parts = path.normalize(filepath).split(path.sep)

Reply with @kilocode-bot fix it to have Kilo Code address this issue.

const file = parts.at(-1)
const dir = parts.at(-2)
if (file !== "agent-manager.json" || ![".kilo", ".kilocode"].includes(dir ?? "")) return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: This guard is global and unconditional, with no escape hatch

Two things worth confirming are intended:

  1. The block applies to every Kilo surface, including the TUI and kilo run where Agent Manager does not exist, and a user cannot opt out. .kilo/agent-manager.json is documented as recoverable state (packages/kilo-docs/pages/automate/agent-manager.md), so an explicit request like "the JSON in .kilo/agent-manager.json is corrupted, fix it" now hard-fails with a message pointing at action=move, which cannot repair malformed JSON. Consider routing this through a permission ask instead of an unconditional throw.
  2. edit/write/apply_patch are covered, but bash is not — echo ... > .kilo/agent-manager.json still succeeds. Fine for a nudge-level guardrail, but it means this should not be treated as an actual invariant.

Reply with @kilocode-bot fix it to have Kilo Code address this issue.

throw new Error(
"Do not edit Agent Manager state directly. Use the agent_manager tool: call action=list to read section and session IDs, then call action=move with the returned IDs.",
)
}
19 changes: 17 additions & 2 deletions packages/opencode/src/kilocode/agent-manager/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,14 @@ export const StopRequest = Schema.Struct({
targetSessionID: SessionID,
}).annotate({ identifier: "AgentManagerStopRequest" })

export const Request = Schema.Union([OverviewRequest, PromptRequest, StopRequest]).annotate({
export const MoveRequest = Schema.Struct({
...Base,
operation: Schema.Literal("move"),
targetSessionID: SessionID,
sectionID: Schema.NullOr(ID),
}).annotate({ identifier: "AgentManagerMoveRequest" })

export const Request = Schema.Union([OverviewRequest, PromptRequest, StopRequest, MoveRequest]).annotate({
identifier: "AgentManagerRequest",
})
export type Request = Schema.Schema.Type<typeof Request>
Expand All @@ -127,7 +134,14 @@ export const StopResult = Schema.Struct({
stopped: Schema.Literal(true),
}).annotate({ identifier: "AgentManagerStopResult" })

export const Result = Schema.Union([OverviewResult, PromptResult, StopResult]).annotate({
export const MoveResult = Schema.Struct({
operation: Schema.Literal("move"),
sessionID: SessionID,
sectionID: Schema.NullOr(ID),
moved: Schema.Literal(true),
}).annotate({ identifier: "AgentManagerMoveResult" })

export const Result = Schema.Union([OverviewResult, PromptResult, StopResult, MoveResult]).annotate({
identifier: "AgentManagerResult",
})
export type Result = Schema.Schema.Type<typeof Result>
Expand All @@ -140,6 +154,7 @@ export const ErrorCode = Schema.Literals([
"stale_session",
"timeout",
"unavailable_session",
"unknown_section",
"unknown_session",
"workspace_unavailable",
])
Expand Down
4 changes: 2 additions & 2 deletions packages/opencode/src/kilocode/permission/agent-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { type Rule } from "./rule"

export namespace AgentManagerPermission {
/**
* Prompting or stopping an existing Agent Manager session has an external side effect.
* Prompting, stopping, or moving an existing Agent Manager session has an external side effect.
* Broad approvals for legacy session creation must not silently grant it.
*/
export function harden(permission: string, pattern: string, rule: Rule): Rule {
if (permission !== "agent_manager" || !["prompt", "stop"].includes(pattern) || rule.action !== "allow") return rule
if (permission !== "agent_manager" || !["prompt", "stop", "move"].includes(pattern) || rule.action !== "allow") return rule
if (rule.permission === "agent_manager" && rule.pattern === pattern) return rule
return { permission, pattern, action: "ask" }
}
Expand Down
Loading
Loading