Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
217 changes: 206 additions & 11 deletions apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import {
OPENCODE_2_STILL_STOPPING,
OPENCODE_PROVIDER,
t3McpServerName,
wildcardMatch,
} from "@t3tools/provider-opencode/testing";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { openCode2ReplayRuntime } from "./OpenCode2AdapterV2.testkit.ts";
Expand Down Expand Up @@ -98,12 +99,13 @@ const mcpRules = [
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: "t3-code-thread_opencode2-adapter_*", resource: "*", effect: "allow" },
];
const t3Rules = [{ action: "*", resource: "*", effect: "allow" }, ...mcpRules];
// Full access is T3's answer to each request: no session is written an allow a subagent could inherit.
const rootRules = mcpRules;
const TITLE = "Prime check";
const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
id: SESSION,
title: TITLE,
permissions: t3Rules,
permissions: rootRules,
projectID: "global",
model: { id: "big-pickle", providerID: "opencode", variant: "default" },
cost: 0,
Expand Down Expand Up @@ -284,13 +286,27 @@ const agentList = {
hidden: false,
permissions: [{ action: "*", resource: "*", effect: "allow" }, ...buildPaths],
},
{
id: "general",
name: "General",
request: { settings: {}, headers: {}, body: {} },
description: "A general subagent.",
mode: "subagent",
hidden: false,
permissions: [{ action: "*", resource: "*", effect: "allow" }],
},
],
};
// A reconnect drops the cached agents, so the next request answered from their rules reads them again.
const relistsAgents: ReadonlyArray<ProviderReplayEntry> = [
out("agent.list", "<any>"),
reply("agent.list", agentList),
];
const supervisedRules = [
{ action: "shell", resource: "*", effect: "ask" },
{ action: "edit", resource: "*", effect: "ask" },
{ action: "external_directory", resource: "*", effect: "ask" },
...buildPaths,
...buildPaths.map((entry) => ({ ...entry, effect: "ask" })),
...mcpRules,
];

Expand Down Expand Up @@ -1527,6 +1543,179 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}),
);

// regression: #38100 a subagent's own agent denies were overridden by T3's session rules
it.effect.each(["full-access", "approval-required"] as const)(
"holds a subagent to its own agent's denies without writing them to its session (%s)",
(mode) =>
Effect.gen(function* () {
const editDeny = { action: "edit", resource: "*", effect: "deny" };
const agents = {
...agentList,
data: [
...agentList.data,
{
id: "review",
name: "Review",
request: { settings: {}, headers: {}, body: {} },
description: "Reviews changes",
mode: "subagent",
hidden: false,
permissions: [{ action: "*", resource: "*", effect: "allow" }, editDeny],
},
],
};
const listsAgents = [out("agent.list", "<any>"), reply("agent.list", agents)];
const launch = backgroundLaunch(CHILD).map((entry) =>
entry.type === "emit_inbound" &&
(entry.frame as { event?: { type?: string } }).event?.type === "session.created"
? event("session.created", { ...childCreated(CHILD), agent: "review" })
: entry,
);
const supervised = mode === "approval-required";
const { runtime, thread } = yield* resumed([
...launch,
event("session.execution.succeeded", { sessionID: SESSION }),
...(supervised
? [
...listsAgents,
out("session.update", { sessionID: SESSION, permissions: supervisedRules }),
reply("session.update", null),
]
: []),
// Rules a subagent's own subagents would copy: no allow, and none of its agent's denies.
out("session.update", {
sessionID: CHILD,
permissions: supervised ? [...supervisedRules.slice(0, 3), ...mcpRules] : rootRules,
}),
reply("session.update", null),
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
promptAccepted,
event("permission.asked", {
id: "per_edit",
sessionID: CHILD,
action: "edit",
resources: ["from-review.txt"],
save: ["*"],
}),
...(supervised ? [] : listsAgents),
out("permission.reply", {
sessionID: CHILD,
requestID: "per_edit",
decision: "reject",
message: "The review agent's permissions do not allow edit here.",
}),
reply("permission.reply", null),
event("session.execution.succeeded", { sessionID: SESSION }),
]);
const firstEnded = yield* Deferred.make<void>();
const ended = yield* runtime.events.pipe(
Stream.filter(
(
event,
): event is Extract<
ProviderAdapter.ProviderAdapterV2Event,
{ type: "turn.terminal" }
> => event.type === "turn.terminal",
),
Stream.tap(() => Deferred.succeed(firstEnded, undefined)),
Stream.take(2),
Stream.runCollect,
Effect.forkScoped,
);
yield* runtime.startTurn(withLineage(thread));
yield* Deferred.await(firstEnded);
yield* runtime.startTurn({
...withLineage(thread),
runId: RunId.make("run:opencode2-adapter:2"),
runOrdinal: 2,
providerTurnOrdinal: 2,
attemptId: RunAttemptId.make("attempt:opencode2-adapter:2"),
runtimePolicy: policy(mode),
});
assert.deepEqual(
[...(yield* Fiber.join(ended))].map((terminal) => terminal.status),
["completed", "completed"],
);
}),
);

it.effect("answers a new subagent's requests from its agent's rules before writing any", () =>
Effect.gen(function* () {
const editDeny = { action: "edit", resource: "*", effect: "deny" };
const tool = { sessionID: SESSION, assistantMessageID: "msg_assistant", id: "call-review" };
const asked = (id: string, action: string, sessionID = CHILD) =>
event("permission.asked", {
id,
sessionID,
action,
resources: ["t.txt"],
save: ["t.txt"],
source: { type: "tool", messageID: "msg_assistant", id: tool.id },
});
const { runtime, thread } = yield* resumed([
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
promptAccepted,
event("session.execution.started", { sessionID: SESSION }),
event("session.tool.input.started", { ...tool, name: "subagent" }),
// The child copies the root's rules, which hold no allow to outrank its agent's deny.
event("session.created", {
...childCreated(CHILD),
agent: "review",
permissions: rootRules,
}),
// An ask left in a child's rules by an earlier mode would outrank the deny; T3 still refuses.
asked("per_edit", "edit"),
out("agent.list", "<any>"),
reply("agent.list", {
...agentList,
data: [
...agentList.data,
{
...agentList.data[1],
id: "review",
permissions: [{ action: "read", resource: "*", effect: "ask" }, editDeny],
},
],
}),
out("permission.reply", {
sessionID: CHILD,
requestID: "per_edit",
decision: "reject",
message: "The review agent's permissions do not allow edit here.",
}),
reply("permission.reply", null),
// Full access answers what the agent only asks about.
asked("per_read", "read"),
out("permission.reply", { sessionID: CHILD, requestID: "per_read", decision: "once" }),
reply("permission.reply", null),
event("session.execution.succeeded", { sessionID: SESSION }),
]);
const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
yield* runtime.startTurn(withLineage(thread));
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
}),
);

it("matches rule patterns the way OpenCode does", () => {
for (const [value, pattern, matches] of [
["edit", "*", true],
["edit", "edit", true],
["edit", "edi", false],
["t3-code-thread_x_read", "t3-code-*", true],
["src/a.ts", "src/*.ts", true],
["src/a.tsx", "src/*.ts", false],
["a.ts", "?.ts", true],
["git status", "git *", true],
["git", "git *", true],
["github", "git *", false],
["a(b).ts", "a(b).ts", true],
["C:\\work\\a.ts", "C:/work/*", true],
["a".repeat(2000), `${"*a".repeat(1000)}b`, false],
] as const) {
assert.equal(wildcardMatch(value, pattern), matches, `${value} ~ ${pattern}`);
}
});

it.effect("gives a background subagent the rules of a mode changed while it runs", () =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed([
Expand Down Expand Up @@ -2712,7 +2901,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
[
...backgroundLaunch(CHILD),
event("session.execution.succeeded", { sessionID: SESSION }),
out("session.update", { sessionID: CHILD, permissions: t3Rules }),
out("session.update", { sessionID: CHILD, permissions: rootRules }),
reply("session.update", null),
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
reply("session.prompt", {
Expand Down Expand Up @@ -2853,7 +3042,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
}),
),
...noOpenRequests,
out("session.update", { sessionID: SESSION, permissions: t3Rules }),
out("session.update", { sessionID: SESSION, permissions: rootRules }),
reply("session.update", null),
]);
yield* runtime.resumeThread({
Expand Down Expand Up @@ -3117,7 +3306,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
sessionID: SESSION,
permissions: [
...supervisedRules.slice(0, 3),
{ action: "shell", resource: "echo *", effect: "allow" },
{ action: "shell", resource: "echo *", effect: "ask" },
...supervisedRules.slice(3),
],
}),
Expand Down Expand Up @@ -3787,9 +3976,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
...(source === "stream"
? [
event("permission.asked", shellAsk.data, "late-permission"),
...relistsAgents,
event("form.created", { form: colorForm }),
]
: []),
: relistsAgents),
out("permission.reply", {
sessionID: SESSION,
requestID: shellAsk.data.id,
Expand Down Expand Up @@ -4085,6 +4275,8 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
reply("session.form.reply", null),
],
{
// Full access answers a subagent's requests itself; a supervised thread shows them.
supervised: true,
beforeResponse: (path) =>
path === `/api/session/${CHILD}/form`
? Deferred.succeed(reading, undefined).pipe(Effect.andThen(Deferred.await(resume)))
Expand Down Expand Up @@ -4112,7 +4304,10 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
),
Effect.forkScoped,
);
yield* runtime.startTurn(withLineage(thread));
yield* runtime.startTurn({
...withLineage(thread),
runtimePolicy: policy("approval-required"),
});
yield* Deferred.await(reading);
const stopping = yield* runtime
.interruptTurn({ providerThread: thread, providerTurnId: yield* providerTurnId })
Expand Down Expand Up @@ -4220,6 +4415,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
promptAccepted,
...reconnected({ [SESSION]: { type: "running" } }),
...openRequests([shellAsk.data]),
...relistsAgents,
out("permission.reply", {
sessionID: SESSION,
requestID: shellAsk.data.id,
Expand Down Expand Up @@ -5255,7 +5451,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
"session.get",
sessionInfo({
permissions: [
{ action: "*", resource: "*", effect: "allow" },
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: `${server}_*`, resource: "*", effect: "allow" },
],
Expand Down Expand Up @@ -5849,6 +6044,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
...(streamed ? { time: { created: 2, streamed: 3 } } : {}),
}),
...openRequests([shellAsk.data]),
...relistsAgents,
event("session.execution.succeeded", { sessionID: SESSION }, "finish"),
],
{ supervised: true, replayGate: gate },
Expand Down Expand Up @@ -5995,7 +6191,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
out("session.create", {
location: { directory: custom },
model: { providerID: "opencode", id: "big-pickle" },
permissions: t3Rules,
permissions: rootRules,
}),
replyData("session.create", sessionInfo({ location: { directory: custom } })),
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
Expand Down Expand Up @@ -6847,7 +7043,6 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
out("session.update", {
sessionID: FORK,
permissions: [
{ action: "*", resource: "*", effect: "allow" },
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: "t3-code-thread_opencode2-adapter_fork_*", resource: "*", effect: "allow" },
],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,10 @@ const mcpRules = (name: string) => [
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: `t3-code-thread_${name}_*`, resource: "*", effect: "allow" },
];
const FULL_ACCESS = [{ action: "*", resource: "*", effect: "allow" }];

const t3Rules = (name: string) => [...FULL_ACCESS, ...mcpRules(name)];
// A session is written no allow a subagent could inherit: T3 answers what the rules would allow.
const t3Rules = mcpRules;
const asks = (rules: ReadonlyArray<{ action: string; resource: string }>) =>
rules.map((entry) => ({ ...entry, effect: "ask" }));

const BUILD_PATHS = [
{
Expand Down Expand Up @@ -111,16 +112,15 @@ const agentList = (directory: string) => ({

const autoEditRules = (name: string) => [
{ action: "shell", resource: "*", effect: "ask" },
{ action: "edit", resource: "*", effect: "allow" },
{ action: "edit", resource: "*", effect: "ask" },
{ action: "external_directory", resource: "*", effect: "ask" },
...BUILD_PATHS,
...asks(BUILD_PATHS),
...mcpRules(name),
];

const planRules = (name: string) => [
{ action: "*", resource: "*", effect: "allow" },
{ action: "edit", resource: "*", effect: "deny" },
...PLAN_PATHS,
...asks(PLAN_PATHS),
...mcpRules(name),
];

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
{"type": "emit_inbound", "label": "message.list.synthetic.response", "frame": {"type": "sdk.response", "operation": "message.list", "data": {"data": [], "cursor": {}}}}
{"type": "expect_outbound", "label": "session.fork", "frame": {"type": "session.fork", "input": {"sessionID": "ses_f1484ea8affe5aTo8CcgbGIszj", "before": "msg_0eb7b1f9f001g95Bduh3bi8syS"}}}
{"type": "emit_inbound", "label": "session.fork.response", "frame": {"type": "sdk.response", "operation": "session.fork", "data": {"data": {"id": "ses_f1484db83ffeLGtrRCFimo1H0e", "fork": {"sessionID": "ses_f1484ea8affe5aTo8CcgbGIszj", "boundary": {"type": "before", "messageID": "msg_0eb7b1f9f001g95Bduh3bi8syS"}}, "projectID": "global", "model": {"id": "big-pickle", "providerID": "opencode", "variant": "default"}, "cost": 0, "tokens": {"input": 0, "output": 0, "reasoning": 0, "cache": {"read": 0, "write": 0}}, "time": {"created": 1790657111165, "updated": 1790657111165}, "title": "spike fork (fork #1)", "location": {"directory": "<work>"}, "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "subagent", "resource": "*", "effect": "deny"}]}}}}
{"type": "expect_outbound", "label": "session.update", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "permissions": [{"action": "*", "resource": "*", "effect": "allow"}, {"action": "t3-code-*", "resource": "*", "effect": "deny"}, {"action": "t3-code-thread_opencode2-fork_target_*", "resource": "*", "effect": "allow"}]}}}
{"type": "expect_outbound", "label": "session.update", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "permissions": [{"action": "t3-code-*", "resource": "*", "effect": "deny"}, {"action": "t3-code-thread_opencode2-fork_target_*", "resource": "*", "effect": "allow"}]}}}
{"type": "emit_inbound", "label": "session.update.response", "frame": {"type": "sdk.response", "operation": "session.update", "data": null}}
{"type": "emit_inbound", "label": "session.forked", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7b247d001fXzFroPg5P0bps", "created": 1790657111165, "type": "session.forked", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "parentID": "ses_f1484ea8affe5aTo8CcgbGIszj", "boundary": {"type": "before", "messageID": "msg_0eb7b1f9f001g95Bduh3bi8syS"}, "instructions": {"core/environment": "db4a793a05fec32fdfa985a3432125a86d6cb42debc8b9ee8f6a99fbfcf2f93b", "core/date": "bf08b8486572ab3eef677a3c9ee12468e411ae41a8f4d2fb6cf02a6ca73f1986", "core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6", "core/skill-guidance": "0d001919496102654717308c72635523bf7c3cd99c81e058cc79f2947104f9a5"}, "instructionEntries": []}, "durable": {"aggregateID": "ses_f1484db83ffeLGtrRCFimo1H0e", "seq": 0, "version": 2}}}}
{"type": "expect_outbound", "label": "session.update.title", "frame": {"type": "session.update", "input": {"sessionID": "ses_f1484db83ffeLGtrRCFimo1H0e", "title": "<any>"}}}
Expand Down
Loading
Loading