FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

fix(session): surface drain failures + check @mention skill permissions by holny · Pull Request #49945 · anomalyco/opencode · GitHub

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .ts  (5) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
13 changes: 11 additions & 2 deletions packages/core/src/session/execution.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
Expand Up @@ -50,7 +50,11 @@ type InterruptReason = "user" | "shutdown" | "inactivity"

export function terminal(exit: Exit.Exit<void, SessionRunner.RunError>, reason?: InterruptReason) {
if (Exit.isSuccess(exit)) return { type: "succeeded" as const }
if (Cause.hasInterrupts(exit.cause)) return { type: "interrupted" as const, reason: reason ?? "shutdown" }
// Only a pure interruption is a deliberate stop. A cause that mixes an
// interruption with a real failure (inactivity eviction or location close
// racing the unwind) must still settle as failed, or the error never reaches
// the durable failure event and the Session looks merely stopped.
if (Cause.hasInterruptsOnly(exit.cause)) return { type: "interrupted" as const, reason: reason ?? "shutdown" }
const failure = Cause.squash(exit.cause)
if (failure instanceof UserInterruptedError) return { type: "interrupted" as const, reason: "user" as const }
return { type: "failed" as const, error: toSessionError(failure) }
Expand Down Expand Up @@ -99,10 +103,15 @@ export const layer = Layer.effect(
runner.drain({ sessionID, force, continuation, promotable }),
).pipe(
instances.provide(session),
// The durable `Execution.Failed` terminal is written by the settled hook, once per
// busy period. The catch path shapes the cause with the same `toSessionError` mapping
// so the log line correlates with the durable event's error envelope.
Effect.tapCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.void
: Effect.logError("Failed to drain Session", cause).pipe(Effect.annotateLogs({ sessionID })),
: Effect.logError("Failed to drain Session", cause).pipe(
Effect.annotateLogs({ sessionID, error: toSessionError(Cause.squash(cause)) }),
),
),
)
return yield* SessionRunner.DrainResult.$match(result, {
Expand Down
20 changes: 19 additions & 1 deletion packages/core/src/session/prompt.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
Expand Up @@ -12,6 +12,7 @@ import { fileURLToPath } from "url"
import { Image } from "../image.js"
import { Instance } from "../instance/service.js"
import { Mime } from "../mime.js"
import { Permission } from "../permission.js"
import { Plugin } from "../plugin/service.js"
import { PluginHooks } from "../plugin/hooks.js"
import { Skill } from "../skill.js"
Expand Down Expand Up @@ -57,18 +58,35 @@ export const prepare = Effect.fn("SessionPrompt.prepare")(function* (request: {
const selected = yield* Effect.gen(function* () {
if (!requested?.length) return undefined
const skillService = yield* Skill.Service
const permission = yield* Permission.Service
const prepared = new Map<Skill.ID, Skill.Name>()
return yield* Effect.forEach(requested, (attachment) =>
Effect.gen(function* () {
const name = prepared.get(attachment.id)
if (name !== undefined) return { id: attachment.id, name, mention: attachment.mention }
const skill = yield* skillService.get(attachment.id)
if (!skill) return yield* new SkillNotFoundError({ skill: attachment.id })
// Mentions load through the same `skill` permission as the skill tool. Without
// this check a denied skill's full body enters the model context via @mention.
// `ask` cannot block admission, so the attachment records the mention without
// the prepared body while the request awaits the user's answer.
const decision = yield* permission
.ask({
action: "skill",
resources: [skill.id],
sessionID: request.session.id,
agent: request.session.agent,
})
.pipe(Effect.orDie)
if (decision.effect === "deny")
return yield* new Permission.BlockedError({ rules: [], permission: "skill", resources: [skill.id] })
prepared.set(skill.id, skill.name)
return {
id: skill.id,
name: skill.name,
text: (yield* Skill.prepare(fs, skill).pipe(Effect.orDie)).output,
...(decision.effect === "allow"
? { text: (yield* Skill.prepare(fs, skill).pipe(Effect.orDie)).output }
: {}),
mention: attachment.mention,
}
}),
Expand Down
44 changes: 44 additions & 0 deletions packages/core/test/session-execution.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
Expand Up @@ -56,6 +56,21 @@ describe("SessionExecution lifecycle", () => {
})
})

test("settles a cause mixing an interruption with a real failure as failed", () => {
const failure = new AIError({
reason: new TransportError({ message: "Disconnected", transport: "http", operation: "request" }),
})
const mixed = Exit.failCause(Cause.combine(Cause.interrupt())(Cause.fail(failure)))
expect(SessionExecution.terminal(mixed)).toEqual({
type: "failed",
error: { type: "provider.transport", message: "Disconnected" },
})
expect(SessionExecution.terminal(mixed, "user")).toEqual({
type: "failed",
error: { type: "provider.transport", message: "Disconnected" },
})
})

it.effect("the sweep only lists claimed top-level Sessions", () =>
Effect.gen(function* () {
const database = yield* Database.Service
Expand Down Expand Up @@ -146,6 +161,35 @@ describe("SessionExecution lifecycle", () => {
}),
)

it.effect("a failing drain settles a durable Execution.Failed and releases the claim", () =>
Effect.gen(function* () {
const database = yield* Database.Service
const bus = yield* Bus.Service
const sessionID = Session.ID.make("ses_drain_failed")
yield* seedSessions(database, [sessionID])

const scope = yield* Scope.make()
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void))
const context = yield* buildExecution(scope, () =>
Effect.fail(
new AIError({
reason: new TransportError({ message: "Disconnected", transport: "http", operation: "request" }),
}),
),
)
const execution = Context.get(context, SessionExecution.Service)
const failed: SessionEvent.Execution.Failed[] = []
yield* bus.project(SessionEvent.Execution.Failed, (event) => Effect.sync(() => void failed.push(event)))

const exit = yield* execution.resume(sessionID).pipe(Effect.exit)
expect(Exit.isSuccess(exit)).toBe(false)
yield* execution.awaitIdle(sessionID)
expect(failed).toHaveLength(1)
expect(failed[0].data.error).toEqual({ type: "provider.transport", message: "Disconnected" })
expect((yield* claims(database))[sessionID]).toBe(false)
}),
)

it.effect("reports an idle interrupt as a no-op", () =>
Effect.gen(function* () {
const sessionID = Session.ID.make("ses_idle_cancel")
Expand Down
95 changes: 79 additions & 16 deletions packages/core/test/session-skill.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
Expand Up @@ -11,6 +11,7 @@ import { Location } from "@opencode/core/location"
import { LocationServiceMap } from "@opencode/core/location-service-map"
import type { LocationServices } from "@opencode/core/location-services"
import { Project } from "@opencode/core/project"
import { Permission } from "@opencode/core/permission"
import { Plugin } from "@opencode/core/plugin"
import { PluginHooks } from "@opencode/core/plugin/hooks"
import { AbsolutePath } from "@opencode/core/schema"
Expand All @@ -24,6 +25,7 @@ import { SessionInbox } from "@opencode/core/session/inbox"
import { Skill } from "@opencode/core/skill"
import { Event } from "@opencode/schema/event"
import { testEffect } from "./lib/effect"
import { location as locationFixture } from "./fixture/location"
import { globalProjectNode } from "./lib/project"

const location = Location.Ref.make({ directory: AbsolutePath.make("/project") })
Expand All @@ -38,21 +40,31 @@ const locations = makeGlobalNode({
service: LocationServiceMap.Service,
layer: Layer.effect(
LocationServiceMap.Service,
LayerMap.make(
(_ref: Location.Ref) =>
// These tests need skill activation and prompt preparation from the same location services.
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
Layer.mergeAll(
LayerNode.compile(LayerNode.group([PluginHooks.node, Image.node])),
Layer.mock(Skill.Service, {
get: (id) => Effect.succeed(id === info.id ? info : undefined),
list: () => Effect.succeed([info]),
}),
Layer.mock(Plugin.Service, { awaitActivation: Effect.void }),
) as unknown as Layer.Layer<LocationServices>,
),
Effect.gen(function* () {
const bus = yield* Bus.Service
return yield* LayerMap.make(
(_ref: Location.Ref) =>
// These tests need skill activation and prompt preparation from the same location services.
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
Layer.mergeAll(
LayerNode.compile(LayerNode.group([PluginHooks.node, Image.node, Permission.node]), {
replacements: [
Bus.node.replace(Layer.succeed(Bus.Service, bus)),
Location.node.replace(
Layer.succeed(Location.Service, Location.Service.of(locationFixture(_ref))),
),
],
}),
Layer.mock(Skill.Service, {
get: (id) => Effect.succeed(id === info.id ? info : undefined),
list: () => Effect.succeed([info]),
}),
Layer.mock(Plugin.Service, { awaitActivation: Effect.void }),
) as unknown as Layer.Layer<LocationServices>,
)
}),
),
deps: [],
deps: [Bus.node],
})
const it = testEffect(
AppNodeBuilder.build(
Expand All @@ -66,12 +78,15 @@ const it = testEffect(
)

describe("Session.skill", () => {
const allowAll = [{ action: "*", resource: "*", effect: "allow" as const }]
const skillRules = (effect: "allow" | "deny" | "ask") => [{ action: "skill", resource: "*", effect }]

it.effect("materializes mentioned skills on their owning prompt", () =>
Effect.gen(function* () {
const sessions = yield* Session.Service
const database = yield* Database.Service
const bus = yield* Bus.Service
const session = yield* sessions.create({ location })
const session = yield* sessions.create({ location, permissions: allowAll })
const id = SessionMessage.ID.make("msg_skill_attachment")

yield* sessions.prompt({
Expand Down Expand Up @@ -115,7 +130,7 @@ describe("Session.skill", () => {
const sessions = yield* Session.Service
const database = yield* Database.Service
const bus = yield* Bus.Service
const session = yield* sessions.create({ location })
const session = yield* sessions.create({ location, permissions: allowAll })
const initial = SessionMessage.ID.make("msg_before_skill_attachment")
const selected = SessionMessage.ID.make("msg_fork_skill_attachment")

Expand All @@ -137,6 +152,54 @@ describe("Session.skill", () => {
}),
)

it.effect("rejects a prompt whose denied skill is mentioned", () =>
Effect.gen(function* () {
const sessions = yield* Session.Service
const session = yield* sessions.create({ location, permissions: skillRules("deny") })

const failure = yield* sessions
.prompt({
sessionID: session.id,
text: "Apply @effect",
skills: [{ id: info.id, mention: { start: 6, end: 13, text: "@effect" } }],
resume: false,
})
.pipe(Effect.flip)

expect(failure._tag).toBe("Permission.BlockedError")
expect(failure.message).toBe("Permission denied: skill")
expect(yield* sessions.inbox(session.id)).toEqual([])
}),
)

it.effect("mentions an unapproved skill without injecting its body", () =>
Effect.gen(function* () {
const sessions = yield* Session.Service
const database = yield* Database.Service
const bus = yield* Bus.Service
const session = yield* sessions.create({ location, permissions: skillRules("ask") })
const id = SessionMessage.ID.make("msg_unapproved_skill_attachment")

yield* sessions.prompt({
id,
sessionID: session.id,
text: "Apply @effect",
skills: [{ id: info.id, mention: { start: 6, end: 13, text: "@effect" } }],
resume: false,
})
yield* SessionInbox.promote(database.db, bus, session.id, "steer")

expect(yield* sessions.messages({ sessionID: session.id })).toEqual([
expect.objectContaining({
id,
type: "user",
text: "Apply @effect",
skills: [{ id: "effect", name: "Effect", mention: { start: 6, end: 13, text: "@effect" } }],
}),
])
}),
)

it.effect("publishes raw standalone content under the caller-supplied ID without inbox admission", () =>
Effect.gen(function* () {
const sessions = yield* Session.Service
Expand Down
3 changes: 3 additions & 0 deletions packages/server/src/handlers/session.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
Expand Up @@ -329,6 +329,9 @@ export const SessionHandler = HttpApiBuilder.group(Api, "server.session", (handl
Effect.catchTag("Session.SkillNotFoundError", (error) =>
Effect.fail(new InvalidRequestError({ message: `Skill not found: ${error.skill}`, field: "skills" })),
),
Effect.catchTag("Permission.BlockedError", (error) =>
Effect.fail(new InvalidRequestError({ message: error.message, field: "skills" })),
),
),
}
}),
Expand Down
Loading

Back | FazBrowse Home | New Git URL