Skip to content

Commit 5d89064

Browse files
govern redskills child agents over acp (#21)
1 parent 6e6c0eb commit 5d89064

12 files changed

Lines changed: 416 additions & 8 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"opencode": minor
3+
---
4+
5+
Add a governed RedSkills child Agent contract to `redcode acp`, including parent-bound outcomes and permissions, cancellation-safe multi-turn sessions, and authority isolation from GitHub and redskilled.
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
export type Contract = {
2+
readonly version: 1
3+
readonly parentSessionId: string
4+
readonly workerId: string
5+
readonly authority: "parent"
6+
readonly github: "parent-gateway"
7+
readonly permissions: "parent"
8+
}
9+
10+
export function parseChildAgentContract(metadata: Record<string, unknown> | null | undefined) {
11+
const redskills = record(metadata?.redskills)
12+
if (!redskills || !("childAgent" in redskills)) return
13+
const childAgent = record(redskills?.childAgent)
14+
if (
15+
!childAgent ||
16+
childAgent.version !== 1 ||
17+
typeof childAgent.parentSessionId !== "string" ||
18+
typeof childAgent.workerId !== "string" ||
19+
childAgent.authority !== "parent" ||
20+
childAgent.github !== "parent-gateway" ||
21+
childAgent.permissions !== "parent"
22+
) {
23+
throw new Error("Invalid RedSkills child Agent contract")
24+
}
25+
return childAgent as Contract
26+
}
27+
28+
export function childAgentMetadata(contract: Contract) {
29+
return {
30+
redskills: {
31+
childAgent: {
32+
version: contract.version,
33+
parentSessionId: contract.parentSessionId,
34+
workerId: contract.workerId,
35+
authority: contract.authority,
36+
},
37+
},
38+
}
39+
}
40+
41+
export function requireGovernedChildBoundary(
42+
_contract: Contract,
43+
mcpServers: readonly McpServer[],
44+
env: Readonly<Record<string, string | undefined>>,
45+
) {
46+
if (env.GITHUB_TOKEN || env.GH_TOKEN) {
47+
throw new Error("GitHub credentials belong to the parent")
48+
}
49+
if (Object.entries(env).some(([name, value]) => name.startsWith("REDSKILLED_") && value)) {
50+
throw new Error("redskilled authority belongs to the parent")
51+
}
52+
if (
53+
mcpServers.some(
54+
(server) =>
55+
server.name.toLowerCase().includes("redskilled") ||
56+
("command" in server && server.command.toLowerCase().includes("redskilled")) ||
57+
("url" in server && server.url.toLowerCase().includes("redskilled")),
58+
)
59+
) {
60+
throw new Error("redskilled MCP side channel is forbidden for a governed child Agent")
61+
}
62+
}
63+
64+
function record(value: unknown) {
65+
if (!value || typeof value !== "object" || Array.isArray(value)) return
66+
return value as Record<string, unknown>
67+
}
68+
import type { McpServer } from "@agentclientprotocol/sdk"

‎packages/opencode/src/acp/error.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,13 @@ export class UnsupportedOperationError extends Schema.TaggedErrorClass<Unsupport
4343
},
4444
) {}
4545

46+
export class InvalidChildAgentBoundaryError extends Schema.TaggedErrorClass<InvalidChildAgentBoundaryError>()(
47+
"ACPInvalidChildAgentBoundaryError",
48+
{
49+
reason: Schema.String,
50+
},
51+
) {}
52+
4653
export class ServiceFailureError extends Schema.TaggedErrorClass<ServiceFailureError>()("ACPServiceFailureError", {
4754
safeMessage: Schema.String,
4855
service: Schema.optional(Schema.String),
@@ -58,6 +65,7 @@ export type Error =
5865
| AuthRequiredError
5966
| UnknownAuthMethodError
6067
| UnsupportedOperationError
68+
| InvalidChildAgentBoundaryError
6169
| ServiceFailureError
6270

6371
export function toRequestError(error: Error) {
@@ -81,6 +89,8 @@ export function toRequestError(error: Error) {
8189
return RequestError.invalidParams({ methodId: error.methodId }, `unknown auth method: ${error.methodId}`)
8290
case "ACPUnsupportedOperationError":
8391
return RequestError.methodNotFound(error.method)
92+
case "ACPInvalidChildAgentBoundaryError":
93+
return RequestError.invalidParams({ boundary: "redskills-child-agent" }, error.reason)
8494
case "ACPServiceFailureError":
8595
return RequestError.internalError(
8696
{

‎packages/opencode/src/acp/permission.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { exists, readText } from "@/util/filesystem"
1212
import type { ACPSession } from "./session"
1313
import { pendingToolCall, toLocations, type ToolInput } from "./tool"
1414
import { Effect } from "effect"
15+
import { childAgentMetadata } from "./child-agent"
1516

1617
type PermissionEvent = Extract<Event, { type: "permission.asked" }>
1718
type Reply = "once" | "always" | "reject"
@@ -61,6 +62,7 @@ export class Handler {
6162
const result = await this.input.connection
6263
.requestPermission({
6364
sessionId: permission.sessionID,
65+
...(session.childAgent ? { _meta: childAgentMetadata(session.childAgent) } : {}),
6466
toolCall: await permissionToolCall({
6567
toolCallId: permission.tool?.callID ?? permission.id,
6668
toolName: permission.permission,

‎packages/opencode/src/acp/service.ts‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,12 @@ import { ProviderV2 } from "@opencode-ai/core/provider"
4545
import { ModelV2 } from "@opencode-ai/core/model"
4646
import { Provider } from "@/provider/provider"
4747
import type { Command } from "@/command"
48+
import {
49+
type Contract as ChildAgentContract,
50+
childAgentMetadata,
51+
parseChildAgentContract,
52+
requireGovernedChildBoundary,
53+
} from "./child-agent"
4854

4955
export const AuthMethodID = "redcode-login"
5056

@@ -78,6 +84,7 @@ export function make(input: {
7884
directory?: Directory.Interface
7985
session?: ACPSession.Interface
8086
usage?: UsageService.Interface
87+
env?: NodeJS.ProcessEnv
8188
eventSubscription?: (subscription: ACPEvent.Subscription) => void
8289
}): Interface {
8390
const session = input.session ?? makeSessionService()
@@ -162,6 +169,17 @@ export function make(input: {
162169

163170
const newSession = Effect.fn("ACP.newSession")(function* (params: NewSessionRequest) {
164171
const started = performance.now()
172+
const childAgent = yield* Effect.try({
173+
try: () => {
174+
const contract = parseChildAgentContract(params._meta)
175+
if (contract) requireGovernedChildBoundary(contract, params.mcpServers, input.env ?? process.env)
176+
return contract
177+
},
178+
catch: (error) =>
179+
new ACPError.InvalidChildAgentBoundaryError({
180+
reason: error instanceof Error ? error.message : "Invalid governed child Agent boundary",
181+
}),
182+
})
165183
const snapshot = yield* directorySnapshot(params.cwd)
166184
const selected = selectDefaultModel(snapshot)
167185
const variant = selectVariant(snapshot, selected)
@@ -190,6 +208,7 @@ export function make(input: {
190208
model: selected,
191209
variant,
192210
modeId,
211+
childAgent,
193212
})
194213
sessionSnapshots.set(state.id, snapshot)
195214

@@ -198,6 +217,7 @@ export function make(input: {
198217

199218
const response = {
200219
sessionId: state.id,
220+
...(state.childAgent ? { _meta: childAgentMetadata(state.childAgent) } : {}),
201221
configOptions: configOptions(snapshot, {
202222
model: state.model ?? selected,
203223
variant: state.variant,
@@ -525,7 +545,7 @@ export function make(input: {
525545
"session",
526546
)
527547
yield* sendUsageUpdate(input.usage, input.sdk, input.connection, current.id, current.cwd)
528-
return yield* promptResponse(response.info, params.messageId)
548+
return yield* promptResponse(response.info, params.messageId, current.childAgent)
529549
}
530550

531551
const known = snapshot.availableCommands.find((item) => item.name === command.name)
@@ -549,7 +569,7 @@ export function make(input: {
549569
"session",
550570
)
551571
yield* sendUsageUpdate(input.usage, input.sdk, input.connection, current.id, current.cwd)
552-
return yield* promptResponse(response.info, params.messageId)
572+
return yield* promptResponse(response.info, params.messageId, current.childAgent)
553573
}
554574

555575
if (command.name === "compact") {
@@ -571,7 +591,7 @@ export function make(input: {
571591
}
572592

573593
yield* sendUsageUpdate(input.usage, input.sdk, input.connection, current.id, current.cwd)
574-
return yield* promptResponse(undefined, params.messageId)
594+
return yield* promptResponse(undefined, params.messageId, current.childAgent)
575595
}),
576596
cancel,
577597
}
@@ -824,20 +844,22 @@ function detectSlashCommand(parts: ReturnType<typeof promptContentToParts>) {
824844
const promptResponse = Effect.fn("ACP.promptResponse")(function* (
825845
info: AssistantInfo,
826846
messageId: string | null | undefined,
847+
childAgent?: ChildAgentContract,
827848
) {
849+
const metadata = childAgent ? childAgentMetadata(childAgent) : {}
828850
if (!info?.error) {
829851
return {
830852
stopReason: "end_turn" as const,
831853
...(info ? { usage: UsageService.buildUsage(info) } : {}),
832854
...(messageId ? { userMessageId: messageId } : {}),
833-
_meta: {},
855+
_meta: metadata,
834856
}
835857
}
836858

837859
const base = {
838860
usage: UsageService.buildUsage(info),
839861
...(messageId ? { userMessageId: messageId } : {}),
840-
_meta: {},
862+
_meta: metadata,
841863
}
842864

843865
if (info.error.name === "MessageAbortedError") {

‎packages/opencode/src/acp/session.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { ProviderV2 } from "@opencode-ai/core/provider"
55
import { ModelV2 } from "@opencode-ai/core/model"
66
import { Context, Effect, Layer, Ref } from "effect"
77
import * as ACPError from "./error"
8+
import type { Contract as ChildAgentContract } from "./child-agent"
89

910
export type SelectedModel = {
1011
providerID: ProviderV2.ID
@@ -30,6 +31,7 @@ export type Info = {
3031
variant?: string
3132
modeId?: string
3233
knownParts: ReadonlyMap<string, KnownMessagePartMetadata>
34+
childAgent?: ChildAgentContract
3335
}
3436

3537
export type StoreInput = {
@@ -40,6 +42,7 @@ export type StoreInput = {
4042
model?: SelectedModel
4143
variant?: string
4244
modeId?: string
45+
childAgent?: ChildAgentContract
4346
}
4447

4548
export type RecordPartMetadataInput = {
@@ -212,6 +215,7 @@ function makeSession(input: StoreInput): Info {
212215
model: input.model,
213216
variant: input.variant,
214217
modeId: input.modeId,
218+
childAgent: input.childAgent,
215219
knownParts: new Map(),
216220
}
217221
}

‎packages/opencode/src/cli/cmd/acp.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,6 @@ export const AcpCommand = effectCmd({
6868
process.stdin.on("end", () => resolve())
6969
process.stdin.on("error", reject)
7070
}),
71-
)
71+
).pipe(Effect.ensuring(Effect.promise(() => server.stop(true))))
7272
}),
7373
})
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import { describe, expect, it } from "bun:test"
2+
import {
3+
childAgentMetadata,
4+
parseChildAgentContract,
5+
requireGovernedChildBoundary,
6+
} from "../../src/acp/child-agent"
7+
8+
const contract = {
9+
version: 1 as const,
10+
parentSessionId: "workflow-session",
11+
workerId: "worker-17",
12+
authority: "parent" as const,
13+
github: "parent-gateway" as const,
14+
permissions: "parent" as const,
15+
}
16+
17+
describe("RedSkills governed child Agent contract", () => {
18+
it("accepts the explicit parent-owned launch contract and projects terminal metadata", () => {
19+
expect(parseChildAgentContract({ redskills: { childAgent: contract } })).toEqual(contract)
20+
expect(childAgentMetadata(contract)).toEqual({
21+
redskills: {
22+
childAgent: {
23+
version: 1,
24+
parentSessionId: "workflow-session",
25+
workerId: "worker-17",
26+
authority: "parent",
27+
},
28+
},
29+
})
30+
})
31+
32+
it("refuses ambient GitHub authority in a governed child Agent", () => {
33+
expect(() =>
34+
requireGovernedChildBoundary(contract, [], {
35+
GITHUB_TOKEN: "leaked",
36+
}),
37+
).toThrow(/github.*credential.*parent/i)
38+
})
39+
40+
it("refuses the GitHub CLI credential alias in a governed child Agent", () => {
41+
expect(() => requireGovernedChildBoundary(contract, [], { GH_TOKEN: "leaked" })).toThrow(
42+
/github.*credential.*parent/i,
43+
)
44+
})
45+
46+
it("refuses an MCP side channel to redskilled", () => {
47+
expect(() =>
48+
requireGovernedChildBoundary(
49+
contract,
50+
[{ name: "redskilled", command: "red-skills-redskilled-mcp", args: [], env: [] }],
51+
{},
52+
),
53+
).toThrow(/redskilled.*side channel/i)
54+
})
55+
56+
it("refuses ambient redskilled authority in a governed child Agent", () => {
57+
expect(() =>
58+
requireGovernedChildBoundary(contract, [], {
59+
REDSKILLED_SOCKET: "/run/user/1000/redskilled.sock",
60+
}),
61+
).toThrow(/redskilled.*authority.*parent/i)
62+
})
63+
64+
it("recognizes a disguised redskilled MCP command as a side channel", () => {
65+
expect(() =>
66+
requireGovernedChildBoundary(
67+
contract,
68+
[{ name: "workflow", command: "red-skills-redskilled-mcp", args: [], env: [] }],
69+
{},
70+
),
71+
).toThrow(/redskilled.*side channel/i)
72+
})
73+
74+
it("recognizes a disguised redskilled MCP URL as a side channel", () => {
75+
expect(() =>
76+
requireGovernedChildBoundary(
77+
contract,
78+
[{ name: "workflow", type: "http", url: "http://redskilled.local/mcp", headers: [] }],
79+
{},
80+
),
81+
).toThrow(/redskilled.*side channel/i)
82+
})
83+
84+
it("rejects a malformed child Agent contract instead of downgrading it to an editor session", () => {
85+
expect(() =>
86+
parseChildAgentContract({
87+
redskills: {
88+
childAgent: { ...contract, authority: "self" },
89+
},
90+
}),
91+
).toThrow(/invalid.*child Agent contract/i)
92+
})
93+
})

0 commit comments

Comments
 (0)