Skip to content
Merged
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
19 changes: 18 additions & 1 deletion packages/opencode/src/ockit/workflow/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,21 @@ export {
type StepExecResult,
type RunOptions,
type RunResult,
} from "./runner"
} from "./runner"
export {
triggerWorkflow,
triggerAndReport,
getSessionRuns,
getSessionRun,
clearSessionRuns,
SessionBridgeError,
type SessionWorkflowRun,
} from "./session-bridge"
export {
resolveStepPermissions,
isToolAllowed,
isAgentAllowed,
filterAllowedTools,
filterAllowedAgents,
type StepPermissions,
} from "./permission-scope"
74 changes: 74 additions & 0 deletions packages/opencode/src/ockit/workflow/permission-scope.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// OC Kit workflow permission scoping. Controls which tools are available
// during each workflow step, based on the kit's declared skill permissions.
// This is a pure computation — no side effects.

import type { Kit, WorkflowStep } from "../types"

/** Permission scope for a single workflow step. */
export interface StepPermissions {
/** Tool permissions: tool ID → "allow" | "deny". Empty = all tools allowed. */
readonly toolPermissions: Record<string, "allow" | "deny">
}

/** Default permissions: everything allowed. */
const DEFAULT_PERMISSIONS: StepPermissions = {
toolPermissions: {},
}

/**
* Resolve the permission scope for a workflow step. Looks up the skill's
* declared permissions from the kit.
*/
export function resolveStepPermissions(
step: WorkflowStep,
kit: Kit,
): StepPermissions {
const skills = kit.skills ?? []
const skill = skills.find((s) => s.id === step.skill)

return {
toolPermissions: skill?.permissions ?? DEFAULT_PERMISSIONS.toolPermissions,
}
}

/**
* Check if a specific tool is allowed in the current step context.
* An empty toolPermissions map means all tools are permitted.
*/
export function isToolAllowed(toolId: string, permissions: StepPermissions): boolean {
const perm = permissions.toolPermissions[toolId]
if (perm === undefined) return true
return perm === "allow"
}

/**
* Filter a list of tool IDs to only those allowed by the current permissions.
*/
export function filterAllowedTools(
tools: ReadonlyArray<string>,
permissions: StepPermissions,
): ReadonlyArray<string> {
return tools.filter((t) => isToolAllowed(t, permissions))
}

/**
* Check if a specific agent is allowed in the current step context.
* An empty agentPermissions map means all agents are permitted.
*/
export function isAgentAllowed(agentId: string, permissions: StepPermissions): boolean {
const perm = permissions.toolPermissions[agentId]
if (perm === undefined) return true
return perm === "allow"
}

/**
* Filter a list of agent IDs to only those allowed by the current permissions.
*/
export function filterAllowedAgents(
agents: ReadonlyArray<string>,
permissions: StepPermissions,
): ReadonlyArray<string> {
return agents.filter((a) => isAgentAllowed(a, permissions))
}

export * as PermissionScope from "./permission-scope"
134 changes: 134 additions & 0 deletions packages/opencode/src/ockit/workflow/session-bridge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// OC Kit workflow-session bridge. Connects the workflow engine to OpenCode's
// session system so workflows can be triggered from within sessions, their
// runs tracked per-session, and their results fed back into session history.

import { Effect, Schema } from "effect"
import type { Kit, Workflow, WorkflowState } from "../types"
import { runWorkflow, type RunSummary, type EngineRunOptions } from "./engine"

/** A workflow run record scoped to a session. */
export const SessionWorkflowRun = Schema.Struct({
runId: Schema.String,
workflowId: Schema.String,
sessionId: Schema.String,
kitId: Schema.String,
state: Schema.String as Schema.Schema<WorkflowState>,
startedAt: Schema.String,
completedAt: Schema.optional(Schema.String),
})
export type SessionWorkflowRun = Schema.Schema.Type<typeof SessionWorkflowRun>

/** Error types for session bridge operations. */
export class SessionBridgeError extends Schema.TaggedErrorClass<SessionBridgeError>()("OCKitSessionBridgeError", {
kind: Schema.Literals(["not-found", "permission", "execution"]),
detail: Schema.String,
}) {
override get message(): string {
return `OC Kit session bridge: ${this.kind} — ${this.detail}`
}
}

/** In-memory store for session-scoped workflow runs. */
const sessionRuns = new Map<string, SessionWorkflowRun[]>()

/** Get all workflow runs for a session. */
export function getSessionRuns(sessionId: string): ReadonlyArray<SessionWorkflowRun> {
return sessionRuns.get(sessionId) ?? []
}

/** Get a specific workflow run by ID within a session. */
export function getSessionRun(sessionId: string, runId: string): SessionWorkflowRun | undefined {
const runs = sessionRuns.get(sessionId) ?? []
return runs.find((r) => r.runId === runId)
}

/** Clear all runs for a session (e.g., on session disposal). */
export function clearSessionRuns(sessionId: string): void {
sessionRuns.delete(sessionId)
}

/** Record a workflow run in the session store. */
function recordRun(run: SessionWorkflowRun): void {
const existing = sessionRuns.get(run.sessionId) ?? []
existing.push(run)
sessionRuns.set(run.sessionId, existing)
}

/** Update an existing run's state and completion time. */
function updateRun(sessionId: string, runId: string, state: WorkflowState, completedAt?: string): void {
const runs = sessionRuns.get(sessionId) ?? []
const idx = runs.findIndex((r) => r.runId === runId)
if (idx >= 0) {
runs[idx] = { ...runs[idx], state, completedAt }
}
}

/**
* Trigger a workflow from within a session. Creates a run record, executes the
* workflow through the engine, and tracks the result per-session.
*/
export const triggerWorkflow = Effect.fn("OCKit.session.triggerWorkflow")(function* (
sessionId: string,
kit: Kit,
workflow: Workflow,
options?: Partial<EngineRunOptions>,
) {
const runId = options?.runId ?? `${workflow.id}-${Date.now()}`
const at = options?.at ?? new Date().toISOString()

// Record the run as CREATED before execution starts.
const pendingRun: SessionWorkflowRun = {
runId,
workflowId: workflow.id,
sessionId,
kitId: kit.id,
state: "CREATED",
startedAt: at,
}
recordRun(pendingRun)

// Execute the workflow through the engine.
const summary: RunSummary = yield* runWorkflow({
kit,
workflow,
sessionId,
runId,
...options,
at,
}).pipe(
Effect.mapError((err) => new SessionBridgeError({
kind: "execution",
detail: `Workflow "${workflow.id}" failed: ${String(err)}`,
})),
)

// Update the run record with the final state.
updateRun(sessionId, runId, summary.state, summary.completedAt)

return summary
})

/**
* Trigger a workflow and produce a session-visible message describing the
* outcome. Use this when you want the result appended to session history.
*/
export const triggerAndReport = Effect.fn("OCKit.session.triggerAndReport")(function* (
sessionId: string,
kit: Kit,
workflow: Workflow,
options?: Partial<EngineRunOptions>,
) {
const summary = yield* triggerWorkflow(sessionId, kit, workflow, options)

const statusEmoji = summary.state === "COMPLETED" ? "✅"
: summary.state === "FAILED" ? "❌"
: summary.recovered ? "🔄"
: "⏳"

return {
summary,
message: `${statusEmoji} Workflow "${workflow.id}" (${summary.state}): ${summary.steps.length} steps, ${summary.recovered ? "recovered" : "direct"}`,
}
})

export * as SessionBridge from "./session-bridge"
85 changes: 85 additions & 0 deletions packages/opencode/test/ockit/workflow/permission-scope.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { describe, expect, test } from "bun:test"
import {
resolveStepPermissions,
isToolAllowed,
filterAllowedTools,
} from "../../../src/ockit/workflow/permission-scope"
import type { Kit, WorkflowStep } from "../../../src/ockit/types"

const BASE_KIT: Kit = {
id: "test-kit",
name: "Test Kit",
version: "1.0.0",
runtime: "opencode",
skills: [
{ id: "skill-a", description: "Skill A" },
{ id: "skill-b", description: "Skill B", permissions: { read: "allow", write: "allow" } },
],
agents: [],
hooks: [],
}

const STEP_A: WorkflowStep = { skill: "skill-a" }
const STEP_B: WorkflowStep = { skill: "skill-b" }
const STEP_RESTRICTED: WorkflowStep = { skill: "skill-a" }

describe("permission-scope", () => {
test("resolveStepPermissions returns empty permissions when no skill permissions declared", () => {
const perms = resolveStepPermissions(STEP_A, BASE_KIT)
expect(perms.toolPermissions).toEqual({})
})

test("resolveStepPermissions uses skill-level permissions", () => {
const perms = resolveStepPermissions(STEP_B, BASE_KIT)
expect(perms.toolPermissions).toEqual({ read: "allow", write: "allow" })
})

test("isToolAllowed returns true when toolPermissions is empty", () => {
const perms = resolveStepPermissions(STEP_A, BASE_KIT)
expect(isToolAllowed("any-tool", perms)).toBe(true)
})

test("isToolAllowed returns true for allowed tools", () => {
const perms = resolveStepPermissions(STEP_B, BASE_KIT)
expect(isToolAllowed("read", perms)).toBe(true)
expect(isToolAllowed("write", perms)).toBe(true)
})

test("isToolAllowed returns true for unlisted tools (not explicitly denied)", () => {
const perms = resolveStepPermissions(STEP_B, BASE_KIT)
expect(isToolAllowed("bash", perms)).toBe(true)
})

test("isToolAllowed returns false for denied tools", () => {
const kitWithDeny: Kit = {
id: "test-kit",
name: "Test Kit",
version: "1.0.0",
runtime: "opencode",
skills: [
{ id: "skill-c", permissions: { bash: "deny" } },
],
}
const step: WorkflowStep = { skill: "skill-c" }
const perms = resolveStepPermissions(step, kitWithDeny)
expect(isToolAllowed("bash", perms)).toBe(false)
})

test("filterAllowedTools filters correctly", () => {
const perms = resolveStepPermissions(STEP_B, BASE_KIT)
const filtered = filterAllowedTools(["read", "write", "bash", "edit"], perms)
expect(filtered).toEqual(["read", "write", "bash", "edit"])
})

test("filterAllowedTools returns all when no restrictions", () => {
const perms = resolveStepPermissions(STEP_A, BASE_KIT)
const filtered = filterAllowedTools(["read", "write", "bash"], perms)
expect(filtered).toEqual(["read", "write", "bash"])
})

test("resolveStepPermissions handles missing skills gracefully", () => {
const step: WorkflowStep = { skill: "nonexistent" }
const perms = resolveStepPermissions(step, BASE_KIT)
expect(perms.toolPermissions).toEqual({})
})
})
76 changes: 76 additions & 0 deletions packages/opencode/test/ockit/workflow/session-bridge.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { describe, expect, test } from "bun:test"
import { Effect, Layer } from "effect"
import { testEffect } from "../../lib/effect"
import {
triggerWorkflow,
triggerAndReport,
getSessionRuns,
getSessionRun,
clearSessionRuns,
SessionBridgeError,
} from "../../../src/ockit/workflow/session-bridge"
import type { Kit, Workflow } from "../../../src/ockit/types"

const it = testEffect(Layer.empty)

const KIT: Kit = {
id: "test-kit",
name: "Test Kit",
version: "1.0.0",
runtime: "opencode",
skills: [{ id: "skill-a", description: "Skill A" }],
agents: [],
hooks: [],
}

const WORKFLOW: Workflow = {
id: "test-workflow",
steps: [{ skill: "skill-a" }],
}

describe("session-bridge", () => {
test("getSessionRuns returns empty array for unknown session", () => {
expect(getSessionRuns("nonexistent")).toEqual([])
})

test("getSessionRun returns undefined for unknown run", () => {
expect(getSessionRun("session-1", "nonexistent")).toBeUndefined()
})

it.effect("triggerWorkflow records a run and executes the workflow", () =>
Effect.gen(function* () {
const summary = yield* triggerWorkflow("session-1", KIT, WORKFLOW, {
runId: "run-1",
at: "2026-08-26T00:00:00Z",
})

expect(summary.workflowId).toBe("test-workflow")
expect(summary.runId).toBe("run-1")
expect(summary.state).toBe("COMPLETED")
expect(summary.steps).toHaveLength(1)

const runs = getSessionRuns("session-1")
expect(runs).toHaveLength(1)
expect(runs[0].runId).toBe("run-1")
expect(runs[0].state).toBe("COMPLETED")
}),
)

it.effect("triggerAndReport returns summary and message", () =>
Effect.gen(function* () {
const result = yield* triggerAndReport("session-2", KIT, WORKFLOW, {
runId: "run-2",
at: "2026-08-26T00:00:00Z",
})

expect(result.summary.state).toBe("COMPLETED")
expect(result.message).toContain("✅")
expect(result.message).toContain("test-workflow")
}),
)

test("clearSessionRuns removes all runs for a session", () => {
clearSessionRuns("session-1")
expect(getSessionRuns("session-1")).toEqual([])
})
})
Loading