Compare commits

...

12 Commits

Author SHA1 Message Date
YeonGyu-Kim
a7d8c1cdf4 feat: dual-publish platform binaries for oh-my-openagent
After publishing oh-my-opencode-{platform}, rename package.json and
publish oh-my-openagent-{platform} from the same build artifact.
Download/extract steps now run if either package needs publishing.
2026-03-09 02:56:01 +09:00
YeonGyu-Kim
beb89faa0f Merge pull request #2388 from code-yeongyu/fix/background-output-undefined-status-2387
fix: handle undefined sessionStatus in pollRunningTasks (#2387)
2026-03-08 23:54:58 +09:00
YeonGyu-Kim
dc370f7fa8 fix: handle undefined sessionStatus in pollRunningTasks (#2387)
When a completed session is no longer returned by session.status(),
allStatuses[sessionID] is undefined. Previously this fell through to
a 'still running' log, leaving the task stuck as running forever.

Match the sync-session-poller pattern: only continue (skip completion
check) when sessionStatus EXISTS and is not idle. When undefined,
fall through to validateSessionHasOutput + checkSessionTodos +
tryCompleteTask, same as idle.
2026-03-08 23:42:11 +09:00
github-actions[bot]
a5fe6eb1a6 @vaur94 has signed the CLA in code-yeongyu/oh-my-openagent#2385 2026-03-08 14:02:29 +00:00
acamq
ba6fc35abd Merge pull request #2376 from acamq/fix/idle-notification-grace-period
fix(session-notification): add grace period to prevent late events from cancelling idle notifications
2026-03-07 14:46:25 -07:00
acamq
9b4c826d01 chore: restore bun.lock from dev 2026-03-07 14:39:04 -07:00
github-actions[bot]
8a827f9927 @acamq has signed the CLA in code-yeongyu/oh-my-openagent#2012 2026-03-07 21:32:30 +00:00
CrazyRabbit
4e352f9caf fix(session-notification): add grace period to prevent late events from cancelling idle notifications 2026-03-07 14:07:08 -07:00
acamq
621cad7268 Merge pull request #2230 from Chocothin/fix/respect-config-question-permission
fix(tool-config): respect question permission from OPENCODE_CONFIG_CONTENT
2026-03-07 14:02:47 -07:00
acamq
ab5a713d2d Merge pull request #2291 from SeeYouCowboi/fix/cache-dir-invalidation-stale-version
fix: also invalidate plugin from CACHE_DIR in invalidatePackage
2026-03-07 13:10:15 -07:00
SeeYouCowboi
f67b605f7a fix: also invalidate plugin from CACHE_DIR in invalidatePackage
Fix #2289

invalidatePackage() only removed the plugin from USER_CONFIG_DIR/node_modules/,
but bun may install it in CACHE_DIR/node_modules/ on some systems. This left a
stale copy behind, causing the startup toast to keep showing the old version even
after the auto-update completed successfully.

Now both candidate locations are checked and removed so the reinstalled version
is loaded on the next restart.
2026-03-04 16:48:33 +08:00
Chocothin
65bc742881 fix(tool-config): respect question permission from OPENCODE_CONFIG_CONTENT
applyToolConfig() unconditionally set question permission based only on
OPENCODE_CLI_RUN_MODE, ignoring the question:deny already configured via
OPENCODE_CONFIG_CONTENT. This caused agents to hang in headless environments
(e.g. Maestro Auto Run) where the host sets question:deny but does not
know about the plugin-internal OPENCODE_CLI_RUN_MODE variable.

Read permission.question from OPENCODE_CONFIG_CONTENT and give it highest
priority: config deny > CLI run mode deny > default allow.
2026-03-01 22:49:47 +09:00
10 changed files with 426 additions and 48 deletions

View File

@@ -193,10 +193,9 @@ jobs:
if-no-files-found: error
# =============================================================================
# Job 2: Publish all platforms using OIDC/Provenance
# Job 2: Publish all platforms (oh-my-opencode + oh-my-openagent)
# - Runs on ubuntu-latest for ALL platforms (just downloading artifacts)
# - Uses npm Trusted Publishing (OIDC) - no NODE_AUTH_TOKEN needed
# - Fresh OIDC token at publish time avoids timeout issues
# - Uses NODE_AUTH_TOKEN for auth + OIDC for provenance attestation
# =============================================================================
publish:
needs: build
@@ -208,7 +207,7 @@ jobs:
matrix:
platform: [darwin-arm64, darwin-x64, darwin-x64-baseline, linux-x64, linux-x64-baseline, linux-arm64, linux-x64-musl, linux-x64-musl-baseline, linux-arm64-musl, windows-x64, windows-x64-baseline]
steps:
- name: Check if already published
- name: Check if oh-my-opencode already published
id: check
run: |
PKG_NAME="oh-my-opencode-${{ matrix.platform }}"
@@ -222,9 +221,23 @@ jobs:
echo "→ ${PKG_NAME}@${VERSION} will be published"
fi
- name: Check if oh-my-openagent already published
id: check-openagent
run: |
PKG_NAME="oh-my-openagent-${{ matrix.platform }}"
VERSION="${{ inputs.version }}"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" "https://registry.npmjs.org/${PKG_NAME}/${VERSION}")
if [ "$STATUS" = "200" ]; then
echo "skip=true" >> $GITHUB_OUTPUT
echo "✓ ${PKG_NAME}@${VERSION} already published, skipping"
else
echo "skip=false" >> $GITHUB_OUTPUT
echo "→ ${PKG_NAME}@${VERSION} will be published"
fi
- name: Download artifact
id: download
if: steps.check.outputs.skip != 'true'
if: steps.check.outputs.skip != 'true' || steps.check-openagent.outputs.skip != 'true'
continue-on-error: true
uses: actions/download-artifact@v4
with:
@@ -232,7 +245,7 @@ jobs:
path: .
- name: Extract artifact
if: steps.check.outputs.skip != 'true' && steps.download.outcome == 'success'
if: (steps.check.outputs.skip != 'true' || steps.check-openagent.outputs.skip != 'true') && steps.download.outcome == 'success'
run: |
PLATFORM="${{ matrix.platform }}"
mkdir -p packages/${PLATFORM}
@@ -248,7 +261,7 @@ jobs:
ls -la packages/${PLATFORM}/bin/
- uses: actions/setup-node@v4
if: steps.check.outputs.skip != 'true' && steps.download.outcome == 'success'
if: (steps.check.outputs.skip != 'true' || steps.check-openagent.outputs.skip != 'true') && steps.download.outcome == 'success'
with:
node-version: "24"
registry-url: "https://registry.npmjs.org"
@@ -268,3 +281,25 @@ jobs:
NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}
NPM_CONFIG_PROVENANCE: true
timeout-minutes: 15
- name: Publish oh-my-openagent-${{ matrix.platform }}
if: steps.check-openagent.outputs.skip != 'true' && steps.download.outcome == 'success'
run: |
cd packages/${{ matrix.platform }}
# Rename package for oh-my-openagent
jq --arg name "oh-my-openagent-${{ matrix.platform }}" \
--arg desc "Platform-specific binary for oh-my-openagent (${{ matrix.platform }})" \
'.name = $name | .description = $desc | .bin = {"oh-my-openagent": (.bin | to_entries | .[0].value)}' \
package.json > tmp.json && mv tmp.json package.json
TAG_ARG=""
if [ -n "${{ inputs.dist_tag }}" ]; then
TAG_ARG="--tag ${{ inputs.dist_tag }}"
fi
npm publish --access public --provenance $TAG_ARG
env:
NODE_AUTH_TOKEN: ${{ secrets.NODE_AUTH_TOKEN }}
NPM_CONFIG_PROVENANCE: true
timeout-minutes: 15

View File

@@ -2015,6 +2015,22 @@
"created_at": "2026-03-07T13:53:56Z",
"repoId": 1108837393,
"pullRequestNo": 2360
},
{
"name": "crazyrabbit0",
"id": 5244848,
"comment_id": 3936744393,
"created_at": "2026-02-20T19:40:05Z",
"repoId": 1108837393,
"pullRequestNo": 2012
},
{
"name": "vaur94",
"id": 100377859,
"comment_id": 4019104338,
"created_at": "2026-03-08T14:01:19Z",
"repoId": 1108837393,
"pullRequestNo": 2385
}
]
}

View File

@@ -2,6 +2,7 @@ import { describe, test, expect } from "bun:test"
import { tmpdir } from "node:os"
import type { PluginInput } from "@opencode-ai/plugin"
import { BackgroundManager } from "./manager"
import type { BackgroundTask } from "./types"
function createManagerWithStatus(statusImpl: () => Promise<{ data: Record<string, { type: string }> }>): BackgroundManager {
const client = {
@@ -51,3 +52,105 @@ describe("BackgroundManager polling overlap", () => {
expect(statusCallCount).toBe(1)
})
})
function createRunningTask(sessionID: string): BackgroundTask {
return {
id: `bg_test_${sessionID}`,
sessionID,
parentSessionID: "parent-session",
parentMessageID: "parent-msg",
description: "test task",
prompt: "test",
agent: "explore",
status: "running",
startedAt: new Date(),
progress: { toolCalls: 0, lastUpdate: new Date() },
}
}
function injectTask(manager: BackgroundManager, task: BackgroundTask): void {
const tasks = (manager as unknown as { tasks: Map<string, BackgroundTask> }).tasks
tasks.set(task.id, task)
}
function createManagerWithClient(clientOverrides: Record<string, unknown> = {}): BackgroundManager {
const client = {
session: {
status: async () => ({ data: {} }),
prompt: async () => ({}),
promptAsync: async () => ({}),
abort: async () => ({}),
todo: async () => ({ data: [] }),
messages: async () => ({
data: [{
info: { role: "assistant", finish: "end_turn", id: "msg-2" },
parts: [{ type: "text", text: "done" }],
}, {
info: { role: "user", id: "msg-1" },
parts: [{ type: "text", text: "go" }],
}],
}),
...clientOverrides,
},
}
return new BackgroundManager({ client, directory: tmpdir() } as unknown as PluginInput)
}
describe("BackgroundManager pollRunningTasks", () => {
describe("#given a running task whose session is no longer in status response", () => {
test("#when pollRunningTasks runs #then completes the task instead of leaving it running", async () => {
//#given
const manager = createManagerWithClient()
const task = createRunningTask("ses-gone")
injectTask(manager, task)
//#when
const poll = (manager as unknown as { pollRunningTasks: () => Promise<void> }).pollRunningTasks
await poll.call(manager)
manager.shutdown()
//#then
expect(task.status).toBe("completed")
expect(task.completedAt).toBeDefined()
})
})
describe("#given a running task whose session status is idle", () => {
test("#when pollRunningTasks runs #then completes the task", async () => {
//#given
const manager = createManagerWithClient({
status: async () => ({ data: { "ses-idle": { type: "idle" } } }),
})
const task = createRunningTask("ses-idle")
injectTask(manager, task)
//#when
const poll = (manager as unknown as { pollRunningTasks: () => Promise<void> }).pollRunningTasks
await poll.call(manager)
manager.shutdown()
//#then
expect(task.status).toBe("completed")
})
})
describe("#given a running task whose session status is busy", () => {
test("#when pollRunningTasks runs #then keeps the task running", async () => {
//#given
const manager = createManagerWithClient({
status: async () => ({ data: { "ses-busy": { type: "busy" } } }),
})
const task = createRunningTask("ses-busy")
injectTask(manager, task)
//#when
const poll = (manager as unknown as { pollRunningTasks: () => Promise<void> }).pollRunningTasks
await poll.call(manager)
manager.shutdown()
//#then
expect(task.status).toBe("running")
})
})
})

View File

@@ -1501,32 +1501,7 @@ Use \`background_output(task_id="${task.id}")\` to retrieve this result when rea
try {
const sessionStatus = allStatuses[sessionID]
if (sessionStatus?.type === "idle") {
// Edge guard: Validate session has actual output before completing
const hasValidOutput = await this.validateSessionHasOutput(sessionID)
if (!hasValidOutput) {
log("[background-agent] Polling idle but no valid output yet, waiting:", task.id)
continue
}
// Re-check status after async operation
if (task.status !== "running") continue
const hasIncompleteTodos = await this.checkSessionTodos(sessionID)
if (hasIncompleteTodos) {
log("[background-agent] Task has incomplete todos via polling, waiting:", task.id)
continue
}
await this.tryCompleteTask(task, "polling (idle status)")
continue
}
// Session is still actively running (not idle).
// Progress is already tracked via handleEvent(message.part.updated),
// so we skip the expensive session.messages() fetch here.
// Completion will be detected when session transitions to idle.
// Handle retry before checking running state
if (sessionStatus?.type === "retry") {
const retryMessage = typeof (sessionStatus as { message?: string }).message === "string"
? (sessionStatus as { message?: string }).message
@@ -1537,12 +1512,40 @@ Use \`background_output(task_id="${task.id}")\` to retrieve this result when rea
}
}
log("[background-agent] Session still running, relying on event-based progress:", {
taskId: task.id,
sessionID,
sessionStatus: sessionStatus?.type ?? "not_in_status",
toolCalls: task.progress?.toolCalls ?? 0,
})
// Match sync-session-poller pattern: only skip completion check when
// status EXISTS and is not idle (i.e., session is actively running).
// When sessionStatus is undefined, the session has completed and dropped
// from the status response — fall through to completion detection.
if (sessionStatus && sessionStatus.type !== "idle") {
log("[background-agent] Session still running, relying on event-based progress:", {
taskId: task.id,
sessionID,
sessionStatus: sessionStatus.type,
toolCalls: task.progress?.toolCalls ?? 0,
})
continue
}
// Session is idle or no longer in status response (completed/disappeared)
const completionSource = sessionStatus?.type === "idle"
? "polling (idle status)"
: "polling (session gone from status)"
const hasValidOutput = await this.validateSessionHasOutput(sessionID)
if (!hasValidOutput) {
log("[background-agent] Polling idle/gone but no valid output yet, waiting:", task.id)
continue
}
// Re-check status after async operation
if (task.status !== "running") continue
const hasIncompleteTodos = await this.checkSessionTodos(sessionID)
if (hasIncompleteTodos) {
log("[background-agent] Task has incomplete todos via polling, waiting:", task.id)
continue
}
await this.tryCompleteTask(task, completionSource)
} catch (error) {
log("[background-agent] Poll error for task:", { taskId: task.id, error })
}

View File

@@ -1,6 +1,6 @@
import * as fs from "node:fs"
import * as path from "node:path"
import { PACKAGE_NAME, USER_CONFIG_DIR } from "./constants"
import { CACHE_DIR, PACKAGE_NAME, USER_CONFIG_DIR } from "./constants"
import { log } from "../../shared/logger"
interface BunLockfile {
@@ -48,17 +48,22 @@ function removeFromBunLock(packageName: string): boolean {
export function invalidatePackage(packageName: string = PACKAGE_NAME): boolean {
try {
const pkgDir = path.join(USER_CONFIG_DIR, "node_modules", packageName)
const pkgDirs = [
path.join(USER_CONFIG_DIR, "node_modules", packageName),
path.join(CACHE_DIR, "node_modules", packageName),
]
const pkgJsonPath = path.join(USER_CONFIG_DIR, "package.json")
let packageRemoved = false
let dependencyRemoved = false
let lockRemoved = false
if (fs.existsSync(pkgDir)) {
fs.rmSync(pkgDir, { recursive: true, force: true })
log(`[auto-update-checker] Package removed: ${pkgDir}`)
packageRemoved = true
for (const pkgDir of pkgDirs) {
if (fs.existsSync(pkgDir)) {
fs.rmSync(pkgDir, { recursive: true, force: true })
log(`[auto-update-checker] Package removed: ${pkgDir}`)
packageRemoved = true
}
}
if (fs.existsSync(pkgJsonPath)) {

View File

@@ -9,6 +9,8 @@ type SessionNotificationConfig = {
idleConfirmationDelay: number
skipIfIncompleteTodos: boolean
maxTrackedSessions: number
/** Grace period in ms to ignore late-arriving activity events after scheduling (default: 100) */
activityGracePeriodMs?: number
}
export function createIdleNotificationScheduler(options: {
@@ -24,6 +26,9 @@ export function createIdleNotificationScheduler(options: {
const sessionActivitySinceIdle = new Set<string>()
const notificationVersions = new Map<string, number>()
const executingNotifications = new Set<string>()
const scheduledAt = new Map<string, number>()
const activityGracePeriodMs = options.config.activityGracePeriodMs ?? 100
function cleanupOldSessions(): void {
const maxSessions = options.config.maxTrackedSessions
@@ -43,6 +48,10 @@ export function createIdleNotificationScheduler(options: {
const sessionsToRemove = Array.from(executingNotifications).slice(0, executingNotifications.size - maxSessions)
sessionsToRemove.forEach((id) => executingNotifications.delete(id))
}
if (scheduledAt.size > maxSessions) {
const sessionsToRemove = Array.from(scheduledAt.keys()).slice(0, scheduledAt.size - maxSessions)
sessionsToRemove.forEach((id) => scheduledAt.delete(id))
}
}
function cancelPendingNotification(sessionID: string): void {
@@ -51,11 +60,17 @@ export function createIdleNotificationScheduler(options: {
clearTimeout(timer)
pendingTimers.delete(sessionID)
}
scheduledAt.delete(sessionID)
sessionActivitySinceIdle.add(sessionID)
notificationVersions.set(sessionID, (notificationVersions.get(sessionID) ?? 0) + 1)
}
function markSessionActivity(sessionID: string): void {
const scheduledTime = scheduledAt.get(sessionID)
if (scheduledTime && Date.now() - scheduledTime < activityGracePeriodMs) {
return
}
cancelPendingNotification(sessionID)
if (!executingNotifications.has(sessionID)) {
notifiedSessions.delete(sessionID)
@@ -65,22 +80,26 @@ export function createIdleNotificationScheduler(options: {
async function executeNotification(sessionID: string, version: number): Promise<void> {
if (executingNotifications.has(sessionID)) {
pendingTimers.delete(sessionID)
scheduledAt.delete(sessionID)
return
}
if (notificationVersions.get(sessionID) !== version) {
pendingTimers.delete(sessionID)
scheduledAt.delete(sessionID)
return
}
if (sessionActivitySinceIdle.has(sessionID)) {
sessionActivitySinceIdle.delete(sessionID)
pendingTimers.delete(sessionID)
scheduledAt.delete(sessionID)
return
}
if (notifiedSessions.has(sessionID)) {
pendingTimers.delete(sessionID)
scheduledAt.delete(sessionID)
return
}
@@ -113,6 +132,7 @@ export function createIdleNotificationScheduler(options: {
} finally {
executingNotifications.delete(sessionID)
pendingTimers.delete(sessionID)
scheduledAt.delete(sessionID)
if (sessionActivitySinceIdle.has(sessionID)) {
notifiedSessions.delete(sessionID)
sessionActivitySinceIdle.delete(sessionID)
@@ -126,6 +146,7 @@ export function createIdleNotificationScheduler(options: {
if (executingNotifications.has(sessionID)) return
sessionActivitySinceIdle.delete(sessionID)
scheduledAt.set(sessionID, Date.now())
const currentVersion = (notificationVersions.get(sessionID) ?? 0) + 1
notificationVersions.set(sessionID, currentVersion)
@@ -144,6 +165,7 @@ export function createIdleNotificationScheduler(options: {
sessionActivitySinceIdle.delete(sessionID)
notificationVersions.delete(sessionID)
executingNotifications.delete(sessionID)
scheduledAt.delete(sessionID)
}
return {

View File

@@ -195,8 +195,9 @@ describe("session-notification", () => {
setMainSession(mainSessionID)
const hook = createSessionNotification(createMockPluginInput(), {
idleConfirmationDelay: 100, // Long delay
idleConfirmationDelay: 100,
skipIfIncompleteTodos: false,
activityGracePeriodMs: 0,
})
// when - session goes idle
@@ -272,6 +273,7 @@ describe("session-notification", () => {
const hook = createSessionNotification(createMockPluginInput(), {
idleConfirmationDelay: 50,
skipIfIncompleteTodos: false,
activityGracePeriodMs: 0,
})
// when - session goes idle, then message.updated fires
@@ -306,6 +308,7 @@ describe("session-notification", () => {
const hook = createSessionNotification(createMockPluginInput(), {
idleConfirmationDelay: 50,
skipIfIncompleteTodos: false,
activityGracePeriodMs: 0,
})
// when - session goes idle, then tool.execute.before fires
@@ -509,4 +512,75 @@ describe("session-notification", () => {
}
}
})
test("should ignore activity events within grace period", async () => {
// given - main session is set
const mainSessionID = "main-grace"
setMainSession(mainSessionID)
const hook = createSessionNotification(createMockPluginInput(), {
idleConfirmationDelay: 50,
skipIfIncompleteTodos: false,
activityGracePeriodMs: 100,
})
// when - session goes idle
await hook({
event: {
type: "session.idle",
properties: { sessionID: mainSessionID },
},
})
// when - activity happens immediately (within grace period)
await hook({
event: {
type: "tool.execute.before",
properties: { sessionID: mainSessionID },
},
})
// Wait for idle delay to pass
await new Promise((resolve) => setTimeout(resolve, 100))
// then - notification SHOULD be sent (activity was within grace period, ignored)
expect(notificationCalls.length).toBeGreaterThanOrEqual(1)
})
test("should cancel notification for activity after grace period", async () => {
// given - main session is set
const mainSessionID = "main-grace-cancel"
setMainSession(mainSessionID)
const hook = createSessionNotification(createMockPluginInput(), {
idleConfirmationDelay: 200,
skipIfIncompleteTodos: false,
activityGracePeriodMs: 50,
})
// when - session goes idle
await hook({
event: {
type: "session.idle",
properties: { sessionID: mainSessionID },
},
})
// when - wait for grace period to pass
await new Promise((resolve) => setTimeout(resolve, 60))
// when - activity happens after grace period
await hook({
event: {
type: "tool.execute.before",
properties: { sessionID: mainSessionID },
},
})
// Wait for original delay to pass
await new Promise((resolve) => setTimeout(resolve, 200))
// then - notification should NOT be sent (activity cancelled it after grace period)
expect(notificationCalls).toHaveLength(0)
})
})

View File

@@ -24,6 +24,8 @@ interface SessionNotificationConfig {
/** Maximum number of sessions to track before cleanup (default: 100) */
maxTrackedSessions?: number
enforceMainSessionFilter?: boolean
/** Grace period in ms to ignore late-arriving activity events after scheduling (default: 100) */
activityGracePeriodMs?: number
}
export function createSessionNotification(
ctx: PluginInput,

View File

@@ -1,4 +1,4 @@
import { describe, it, expect } from "bun:test"
import { describe, it, expect, beforeEach, afterEach } from "bun:test"
import { applyToolConfig } from "./tool-config-handler"
import type { OhMyOpenCodeConfig } from "../config"
@@ -56,6 +56,109 @@ describe("applyToolConfig", () => {
})
})
describe("#given OPENCODE_CONFIG_CONTENT has question set to deny", () => {
let originalConfigContent: string | undefined
let originalCliRunMode: string | undefined
beforeEach(() => {
originalConfigContent = process.env.OPENCODE_CONFIG_CONTENT
originalCliRunMode = process.env.OPENCODE_CLI_RUN_MODE
})
afterEach(() => {
if (originalConfigContent === undefined) {
delete process.env.OPENCODE_CONFIG_CONTENT
} else {
process.env.OPENCODE_CONFIG_CONTENT = originalConfigContent
}
if (originalCliRunMode === undefined) {
delete process.env.OPENCODE_CLI_RUN_MODE
} else {
process.env.OPENCODE_CLI_RUN_MODE = originalCliRunMode
}
})
describe("#when config explicitly denies question permission", () => {
it.each(["sisyphus", "hephaestus", "prometheus"])(
"#then should deny question for %s even without CLI_RUN_MODE",
(agentName) => {
process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({
permission: { question: "deny" },
})
delete process.env.OPENCODE_CLI_RUN_MODE
const params = createParams({ agents: [agentName] })
applyToolConfig(params)
const agent = params.agentResult[agentName] as {
permission: Record<string, unknown>
}
expect(agent.permission.question).toBe("deny")
},
)
})
describe("#when config does not deny question permission", () => {
it.each(["sisyphus", "hephaestus", "prometheus"])(
"#then should allow question for %s in interactive mode",
(agentName) => {
process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({
permission: { question: "allow" },
})
delete process.env.OPENCODE_CLI_RUN_MODE
const params = createParams({ agents: [agentName] })
applyToolConfig(params)
const agent = params.agentResult[agentName] as {
permission: Record<string, unknown>
}
expect(agent.permission.question).toBe("allow")
},
)
})
describe("#when CLI_RUN_MODE is true and config does not deny", () => {
it.each(["sisyphus", "hephaestus", "prometheus"])(
"#then should deny question for %s via CLI_RUN_MODE",
(agentName) => {
process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({
permission: {},
})
process.env.OPENCODE_CLI_RUN_MODE = "true"
const params = createParams({ agents: [agentName] })
applyToolConfig(params)
const agent = params.agentResult[agentName] as {
permission: Record<string, unknown>
}
expect(agent.permission.question).toBe("deny")
},
)
})
describe("#when config deny overrides CLI_RUN_MODE allow", () => {
it.each(["sisyphus", "hephaestus", "prometheus"])(
"#then should deny question for %s when config says deny regardless of CLI_RUN_MODE",
(agentName) => {
process.env.OPENCODE_CONFIG_CONTENT = JSON.stringify({
permission: { question: "deny" },
})
process.env.OPENCODE_CLI_RUN_MODE = "false"
const params = createParams({ agents: [agentName] })
applyToolConfig(params)
const agent = params.agentResult[agentName] as {
permission: Record<string, unknown>
}
expect(agent.permission.question).toBe("deny")
},
)
})
})
describe("#given task_system is disabled", () => {
describe("#when applying tool config", () => {
it.each([

View File

@@ -3,6 +3,17 @@ import { getAgentDisplayName } from "../shared/agent-display-names";
type AgentWithPermission = { permission?: Record<string, unknown> };
function getConfigQuestionPermission(): string | null {
const configContent = process.env.OPENCODE_CONFIG_CONTENT;
if (!configContent) return null;
try {
const parsed = JSON.parse(configContent);
return parsed?.permission?.question ?? null;
} catch {
return null;
}
}
function agentByKey(agentResult: Record<string, unknown>, key: string): AgentWithPermission | undefined {
return (agentResult[key] ?? agentResult[getAgentDisplayName(key)]) as
| AgentWithPermission
@@ -32,7 +43,11 @@ export function applyToolConfig(params: {
};
const isCliRunMode = process.env.OPENCODE_CLI_RUN_MODE === "true";
const questionPermission = isCliRunMode ? "deny" : "allow";
const configQuestionPermission = getConfigQuestionPermission();
const questionPermission =
configQuestionPermission === "deny" ? "deny" :
isCliRunMode ? "deny" :
"allow";
const librarian = agentByKey(params.agentResult, "librarian");
if (librarian) {