mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
* feat(sandbox): add KVM-backed agent sandboxing via microsandbox * feat(sandbox): route host-shell surfaces into microVM via shell wrapper * feat(sandbox): route host-shell surfaces into microVM via shell wrapper * fix(sandbox): harden enforcement validation and backup handling * fix(sandbox): bound lifecycle queue and harden install/backup paths Bound the OpenCode supervisor lifecycle queue to one running plus one pending operation so repeated restarts cannot stack unbounded HTTP requests, while exempting stop() so shutdown is never dropped. Reject enforcement backups that carry no recoverable removed sections, matching the existing fail-closed handling of unparseable backups. Install OpenCode through a private mktemp staging directory instead of the predictable /tmp/opencode path. Use named path/os imports in the files added by this branch. * refactor(sandbox): remove OpenCode version allowlist gating under enforcement * fix(settings): use resolved opencode binary and verify installed version * refactor(sandbox): scope enforcement to agent bash tool only * fix(sandbox): plan bash against factory directory and attest runtime tmpfs; align permission reply API * fix(sandbox): pin neutral entrypoint and persist opencode upgrades across rebuilds * fix(sandbox): align canonical spec with msb 0.6.8 runtime defaults * feat(sandbox): show unwrapped sandboxed bash commands in message UI * refactor(sandbox): pin shell shim to sandbox agent bash without rewriting commands * feat(sandbox): route notifications through a host-side manager tool * feat(sandbox): route all assistant capabilities through the ocm tool Add an allow-listed request action to the generated ocm plugin so agents reach settings, assistant reload, repos, git-info, workspaces, and schedules through the tool instead of curling the internal API with a bearer token, which is impossible under sandboxing. Rewrite the curl-based skills to use the ocm request action and drop the apiBaseUrl plumbing. Remove the now-unread .opencode/internal-token file and the sandbox tmpfs mask that hid it; attestation now rejects any tmpfs other than the runtime /tmp mount. * fix(sidebar): wire new-session and new-schedule actions to every page AssistantRedirect never registered a listener for the sidebar's new-session event, so the desktop sidebar CTA on /assistant was a no-op; the Schedules pages had the same gap for new-schedule. Make useSidebarAction the single source of truth for action keys and event dispatch, and warn when an action is dispatched with no mounted handler so an unhandled CTA fails loudly instead of silently. Wire the missing listeners to the existing per-page handlers. * feat(sandbox): forward git credentials into the microVM and add sandbox guest image * feat(sandbox): add git credential forwarding toggle to settings
752 lines
31 KiB
TypeScript
752 lines
31 KiB
TypeScript
import { describe, expect, it, beforeEach, afterEach } from 'bun:test'
|
|
import path from 'path'
|
|
import { access, readFile, writeFile } from 'fs/promises'
|
|
import { Hono } from 'hono'
|
|
import { ensureAssistantMode, getAssistantModeStatus, buildSchedulesSkill, buildReposSkill, buildSettingsSkill, buildAssistantDefaultAgentMd, buildAssistantOpenCodeConfig, buildAssistantRepo, installAssistantWorkspace } from '../../src/services/assistant-mode'
|
|
import { createTempAssistantWorkspace, createTestDb, mockRepo } from '../helpers/assistant-workspace'
|
|
import { createInternalRoutes } from '../../src/routes/internal'
|
|
import { ScheduleService } from '../../src/services/schedules'
|
|
import { NotificationService } from '../../src/services/notification'
|
|
import { SettingsService } from '../../src/services/settings'
|
|
import { getOrCreateInternalToken } from '../../src/services/internal-token'
|
|
import { createOpenCodeClient } from '../../src/services/opencode/client'
|
|
import { getRepoById } from '../../src/db/queries'
|
|
import type { ScheduleWorktreeManager } from '../../src/services/schedule-worktree'
|
|
|
|
describe('buildSchedulesSkill', () => {
|
|
it('instructs the agent to use the ocm tool request action', () => {
|
|
const skill = buildSchedulesSkill()
|
|
expect(skill).toContain('"action": "request"')
|
|
expect(skill).toContain('"method": "GET"')
|
|
expect(skill).toContain('"path": "/schedules/all"')
|
|
expect(skill).not.toContain('curl')
|
|
})
|
|
|
|
it('documents repoId 0 for Assistant schedules', () => {
|
|
const skill = buildSchedulesSkill()
|
|
expect(skill).toContain('Use repo ID `0` for the built-in Assistant')
|
|
expect(skill).toContain('/repos/0/schedules')
|
|
})
|
|
})
|
|
|
|
describe('buildReposSkill', () => {
|
|
it('instructs the agent to use the ocm tool request action', () => {
|
|
const skill = buildReposSkill()
|
|
expect(skill).toContain('"action": "request"')
|
|
expect(skill).toContain('"method": "GET"')
|
|
expect(skill).toContain('"path": "/repos"')
|
|
})
|
|
|
|
it('contains GET /repos endpoint documentation', () => {
|
|
const skill = buildReposSkill()
|
|
expect(skill).toContain('GET /repos')
|
|
})
|
|
|
|
it('does not instruct reading the internal token or sending a bearer header', () => {
|
|
const skill = buildReposSkill()
|
|
expect(skill).not.toContain('Authorization: Bearer')
|
|
expect(skill).not.toContain('.opencode/internal-token')
|
|
expect(skill).not.toContain('curl')
|
|
})
|
|
|
|
it('does not contain a localhost base URL', () => {
|
|
const skill = buildReposSkill()
|
|
expect(skill).not.toContain('localhost')
|
|
})
|
|
})
|
|
|
|
describe('buildSettingsSkill', () => {
|
|
it('instructs the agent to use the ocm tool request action', () => {
|
|
const skill = buildSettingsSkill()
|
|
expect(skill).toContain('"action": "request"')
|
|
expect(skill).toContain('"path": "/settings?userId=default"')
|
|
expect(skill).not.toContain('curl')
|
|
})
|
|
|
|
it('includes tts and stt in allowed non-secret preferences', () => {
|
|
const skill = buildSettingsSkill()
|
|
expect(skill).toContain('tts')
|
|
expect(skill).toContain('stt')
|
|
expect(skill).toContain('enabled')
|
|
expect(skill).toContain('provider')
|
|
expect(skill).toContain('autoPlay')
|
|
expect(skill).toContain('voice')
|
|
expect(skill).toContain('model')
|
|
expect(skill).toContain('speed')
|
|
expect(skill).toContain('language')
|
|
})
|
|
|
|
it('documents the POST /assistant/reload endpoint', () => {
|
|
const skill = buildSettingsSkill()
|
|
expect(skill).toContain('/assistant/reload')
|
|
expect(skill).toContain('Always confirm with the user before reloading')
|
|
expect(skill).toContain('5 requests per minute')
|
|
})
|
|
|
|
it('still lists apiKey and endpoint as forbidden', () => {
|
|
const skill = buildSettingsSkill()
|
|
expect(skill).toContain('tts.apiKey')
|
|
expect(skill).toContain('tts.endpoint')
|
|
expect(skill).toContain('stt.apiKey')
|
|
expect(skill).toContain('stt.endpoint')
|
|
expect(skill).toContain('DO NOT attempt to set')
|
|
})
|
|
})
|
|
|
|
describe('buildAssistantDefaultAgentMd', () => {
|
|
it('contains description and mode in frontmatter', () => {
|
|
const content = buildAssistantDefaultAgentMd()
|
|
expect(content).toContain('description: Default OpenCode Manager assistant workspace agent')
|
|
expect(content).toContain('mode: primary')
|
|
})
|
|
|
|
it('references workspace skills', () => {
|
|
const content = buildAssistantDefaultAgentMd()
|
|
expect(content).toContain('repo-management')
|
|
expect(content).toContain('schedule-management')
|
|
expect(content).toContain('notifications')
|
|
expect(content).toContain('manager-settings')
|
|
})
|
|
|
|
it('contains reload guidance in the agent prompt', () => {
|
|
const content = buildAssistantDefaultAgentMd()
|
|
expect(content).toContain('/assistant/reload')
|
|
expect(content).toContain('Always ask the user before reloading')
|
|
})
|
|
|
|
it('does not contain v file', () => {
|
|
const content = buildAssistantDefaultAgentMd()
|
|
expect(content).not.toContain('v file')
|
|
})
|
|
})
|
|
|
|
describe('buildAssistantOpenCodeConfig', () => {
|
|
it('includes default_agent and agent.assistant with primary mode and no embedded persona', () => {
|
|
const config = buildAssistantOpenCodeConfig()
|
|
expect(config.default_agent).toBe('assistant')
|
|
expect(config.agent?.assistant).toEqual({ mode: 'primary' })
|
|
expect(config.agent?.assistant?.prompt).toBeUndefined()
|
|
expect(config.agent?.assistant?.description).toBeUndefined()
|
|
expect(config.agent?.assistant?.permission).toBeUndefined()
|
|
})
|
|
})
|
|
|
|
describe('ensureAssistantMode', () => {
|
|
let ws: Awaited<ReturnType<typeof createTempAssistantWorkspace>>
|
|
|
|
beforeEach(async () => {
|
|
ws = await createTempAssistantWorkspace()
|
|
})
|
|
afterEach(async () => { await ws.cleanup() })
|
|
|
|
it('creates AGENTS.md, opencode.json, and SKILL.md on first run', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
const agentsMd = await readFile(path.join(ws.assistantDir, 'AGENTS.md'), 'utf8')
|
|
const opencodeJson = await readFile(path.join(ws.assistantDir, 'opencode.json'), 'utf8')
|
|
const skill = await readFile(path.join(ws.assistantDir, '.opencode/skills/schedule-management/SKILL.md'), 'utf8')
|
|
const repoSkill = await readFile(path.join(ws.assistantDir, '.opencode/skills/repo-management/SKILL.md'), 'utf8')
|
|
const assistantAgent = await readFile(path.join(ws.assistantDir, '.opencode/agents/assistant.md'), 'utf8')
|
|
|
|
expect(agentsMd).toContain('.opencode/agents/assistant.md')
|
|
expect(agentsMd).not.toContain('Self-Editing Rules')
|
|
const parsedConfig = JSON.parse(opencodeJson)
|
|
expect(parsedConfig.default_agent).toBe('assistant')
|
|
expect(parsedConfig).not.toHaveProperty('mcp')
|
|
expect(parsedConfig.agent?.assistant).toEqual({ mode: 'primary' })
|
|
expect(parsedConfig.agent?.assistant?.prompt).toBeUndefined()
|
|
expect(parsedConfig.agent?.assistant?.description).toBeUndefined()
|
|
expect(parsedConfig.agent?.assistant?.permission).toBeUndefined()
|
|
expect(skill).toContain('"action": "request"')
|
|
expect(skill).not.toContain('curl')
|
|
expect(skill).not.toContain('Authorization: Bearer')
|
|
expect(repoSkill).toContain('GET /repos')
|
|
expect(repoSkill).not.toContain('Authorization: Bearer')
|
|
expect(repoSkill).not.toContain('.opencode/internal-token')
|
|
expect(assistantAgent).toContain('mode: primary')
|
|
expect(assistantAgent).toContain('Default OpenCode Manager assistant workspace agent')
|
|
expect(assistantAgent).not.toContain('v file')
|
|
await expect(access(path.join(ws.assistantDir, '.opencode/internal-token'))).rejects.toThrow()
|
|
})
|
|
|
|
it('does not create a .opencode/internal-token file', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
await expect(access(path.join(ws.assistantDir, '.opencode/internal-token'))).rejects.toThrow()
|
|
})
|
|
|
|
it('writes all files needed before OpenCode assistant session launch', async () => {
|
|
const result = await ensureAssistantMode(mockRepo)
|
|
|
|
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
|
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
|
|
const schedulesSkillPath = path.join(ws.assistantDir, '.opencode/skills/schedule-management/SKILL.md')
|
|
const notificationsSkillPath = path.join(ws.assistantDir, '.opencode/skills/notifications/SKILL.md')
|
|
const settingsSkillPath = path.join(ws.assistantDir, '.opencode/skills/manager-settings/SKILL.md')
|
|
const reposSkillPath = path.join(ws.assistantDir, '.opencode/skills/repo-management/SKILL.md')
|
|
const assistantAgentPath = path.join(ws.assistantDir, '.opencode/agents/assistant.md')
|
|
|
|
const opencodeJsonContent = await readFile(opencodeJsonPath, 'utf8')
|
|
const opencodeJson = JSON.parse(opencodeJsonContent)
|
|
|
|
expect(opencodeJson.default_agent).toBe('assistant')
|
|
expect(opencodeJson.instructions).toEqual(['AGENTS.md'])
|
|
expect(opencodeJson.permission).toEqual({
|
|
read: 'allow',
|
|
edit: 'allow',
|
|
glob: 'allow',
|
|
grep: 'allow',
|
|
list: 'allow',
|
|
bash: 'allow',
|
|
external_directory: 'ask',
|
|
})
|
|
expect(opencodeJson.agent?.assistant).toEqual({ mode: 'primary' })
|
|
expect(opencodeJson.agent?.assistant?.prompt).toBeUndefined()
|
|
expect(opencodeJson.agent?.assistant?.description).toBeUndefined()
|
|
expect(opencodeJson.agent?.assistant?.permission).toBeUndefined()
|
|
|
|
const agentsMdContent = await readFile(agentsMdPath, 'utf8')
|
|
expect(agentsMdContent).toContain('Assistant Mode Workspace')
|
|
expect(agentsMdContent).toContain('.opencode/agents/assistant.md')
|
|
expect(agentsMdContent).not.toContain('Self-Editing Rules')
|
|
expect(agentsMdContent).not.toContain('Schedule Management')
|
|
expect(agentsMdContent).not.toContain('Notifications')
|
|
expect(agentsMdContent).not.toContain('Settings Management')
|
|
expect(agentsMdContent).not.toContain('Repo Management')
|
|
|
|
const schedulesSkillContent = await readFile(schedulesSkillPath, 'utf8')
|
|
expect(schedulesSkillContent).toContain('name: schedule-management')
|
|
expect(schedulesSkillContent).toContain('Manage schedule jobs')
|
|
expect(schedulesSkillContent).toContain('Use repo ID `0` for the built-in Assistant')
|
|
expect(schedulesSkillContent).toContain('/repos/0/schedules')
|
|
|
|
const notificationsSkillContent = await readFile(notificationsSkillPath, 'utf8')
|
|
expect(notificationsSkillContent).toContain('name: notifications')
|
|
expect(notificationsSkillContent).toContain('Send push notifications')
|
|
|
|
const settingsSkillContent = await readFile(settingsSkillPath, 'utf8')
|
|
expect(settingsSkillContent).toContain('name: manager-settings')
|
|
expect(settingsSkillContent).toContain('Read and modify')
|
|
|
|
const reposSkillContent = await readFile(reposSkillPath, 'utf8')
|
|
expect(reposSkillContent).toContain('name: repo-management')
|
|
expect(reposSkillContent).toContain('List repos available')
|
|
|
|
const assistantAgentContent = await readFile(assistantAgentPath, 'utf8')
|
|
expect(assistantAgentContent).toContain('mode: primary')
|
|
expect(assistantAgentContent).toContain('Self-Editing')
|
|
expect(assistantAgentContent).toContain('repo-management')
|
|
expect(assistantAgentContent).toContain('schedule-management')
|
|
expect(assistantAgentContent).toContain('notifications')
|
|
expect(assistantAgentContent).toContain('manager-settings')
|
|
|
|
expect(result.files.opencodeJson?.exists).toBe(true)
|
|
expect(result.files.agentsMd?.exists).toBe(true)
|
|
expect(result.repoManagementSkill?.path).toBe(reposSkillPath)
|
|
expect(result.repoManagementSkill?.created).toBe(true)
|
|
expect(result.defaultAgent?.name).toBe('assistant')
|
|
expect(result.defaultAgent?.path).toBe(assistantAgentPath)
|
|
expect(result.defaultAgent?.exists).toBe(true)
|
|
expect(result.defaultAgent?.created).toBe(true)
|
|
})
|
|
|
|
it('reports repo management skill status from getAssistantModeStatus', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
|
|
const status = await getAssistantModeStatus(mockRepo)
|
|
|
|
expect(status.repoManagementSkill?.path).toBe(path.join(ws.assistantDir, '.opencode/skills/repo-management/SKILL.md'))
|
|
expect(status.repoManagementSkill?.created).toBe(false)
|
|
})
|
|
|
|
it('preserves custom assistant agent content on subsequent ensureAssistantMode calls', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
const assistantAgentPath = path.join(ws.assistantDir, '.opencode/agents/assistant.md')
|
|
|
|
const customContent = '---\ndescription: Custom assistant\nmode: primary\n---\n\nCustom assistant instructions.'
|
|
await writeFile(assistantAgentPath, customContent)
|
|
|
|
const result2 = await ensureAssistantMode(mockRepo)
|
|
|
|
const preservedContent = await readFile(assistantAgentPath, 'utf8')
|
|
expect(preservedContent).toBe(customContent)
|
|
expect(result2.defaultAgent?.created).toBe(false)
|
|
})
|
|
|
|
it('repairs existing assistant opencode config missing configured assistant agent', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
|
await writeFile(opencodeJsonPath, JSON.stringify({
|
|
model: 'provider/model',
|
|
instructions: ['AGENTS.md'],
|
|
default_agent: 'build',
|
|
agent: {
|
|
custom: { mode: 'primary', prompt: 'Custom agent' },
|
|
},
|
|
skills: { paths: ['.opencode/skills'] },
|
|
}, null, 2))
|
|
|
|
const result = await ensureAssistantMode(mockRepo)
|
|
const repaired = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
|
|
|
|
expect(repaired.default_agent).toBe('assistant')
|
|
expect(repaired.agent.assistant).toEqual({ mode: 'primary', disable: false })
|
|
expect(repaired.agent.assistant.prompt).toBeUndefined()
|
|
expect(repaired.agent.custom.prompt).toBe('Custom agent')
|
|
expect(repaired.model).toBe('provider/model')
|
|
expect(repaired.skills.paths).toEqual(['.opencode/skills'])
|
|
expect(result.files.opencodeJson?.created).toBe(true)
|
|
})
|
|
|
|
it('preserves custom assistant config while making it selectable', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
|
await writeFile(opencodeJsonPath, JSON.stringify({
|
|
default_agent: 'assistant',
|
|
agent: {
|
|
assistant: {
|
|
mode: 'subagent',
|
|
prompt: 'Custom assistant prompt',
|
|
description: 'Custom assistant',
|
|
permission: { bash: 'ask' },
|
|
},
|
|
},
|
|
}, null, 2))
|
|
|
|
const result = await ensureAssistantMode(mockRepo)
|
|
const repaired = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
|
|
|
|
expect(repaired.agent.assistant.prompt).toBe('Custom assistant prompt')
|
|
expect(repaired.agent.assistant.description).toBe('Custom assistant')
|
|
expect(repaired.agent.assistant.permission.bash).toBe('ask')
|
|
expect(repaired.agent.assistant.mode).toBe('primary')
|
|
expect(repaired.agent.assistant.disable).toBe(false)
|
|
expect(result.files.opencodeJson?.created).toBe(true)
|
|
})
|
|
|
|
it('migrates generated legacy AGENTS.md and assistant.md to the new split', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
|
|
const legacyAgentsMd = `# Assistant Mode Instructions
|
|
|
|
This folder is the shared Assistant mode workspace for OpenCode Manager.
|
|
|
|
## Purpose
|
|
|
|
Assistant mode provides an isolated space for:
|
|
- Self-editing agent instructions and preferences
|
|
- Customized workflows specific to this assistant workspace
|
|
- Iterative improvement of assistant behavior
|
|
|
|
## Self-Editing Rules
|
|
|
|
The agent MAY self-edit the following files within this workspace:
|
|
- \`AGENTS.md\` - Assistant instructions, persona, and durable preferences
|
|
- \`opencode.json\` - OpenCode configuration for this workspace
|
|
|
|
## Constraints
|
|
|
|
- Changes outside this workspace require explicit user direction
|
|
- Self-edits should be concise and auditable
|
|
- Preserve user-customized content when modifying files
|
|
- Always ask for confirmation before making significant changes
|
|
|
|
## Guidelines
|
|
|
|
1. Keep instructions clear and actionable
|
|
2. Update AGENTS.md when learning durable preferences
|
|
3. Maintain version control awareness
|
|
4. Document significant changes in commit messages
|
|
|
|
## Repo Management
|
|
|
|
This workspace includes a skill at \`.opencode/skills/repo-management/SKILL.md\` for listing repos available to OpenCode Manager via the internal HTTP API. Load it before the schedule-management skill when you don't know the repo ID.
|
|
|
|
## Schedule Management
|
|
|
|
This workspace ships with a workspace-scoped skill at \`.opencode/skills/schedule-management/SKILL.md\` that documents how to list, create, update, delete, run, inspect, and cancel schedule jobs and runs across any repo via the internal HTTP API. Load it whenever the user asks about schedules.
|
|
|
|
## Notifications
|
|
|
|
This workspace includes a skill at \`.opencode/skills/notifications/SKILL.md\` for sending push notifications to the user's registered devices via the internal HTTP API. Load it when you need to notify the user about important events.
|
|
|
|
## Settings Management
|
|
|
|
This workspace includes a skill at \`.opencode/skills/manager-settings/SKILL.md\` for reading and safely modifying user preferences via the internal HTTP API. Load it when you need to inspect or update UI settings.
|
|
`
|
|
|
|
const legacyAssistantAgent = `---
|
|
description: Default OpenCode Manager assistant workspace agent
|
|
mode: primary
|
|
permission:
|
|
read: allow
|
|
edit: allow
|
|
glob: allow
|
|
grep: allow
|
|
list: allow
|
|
bash: allow
|
|
external_directory: ask
|
|
---
|
|
|
|
You are the default Assistant Mode agent for OpenCode Manager.
|
|
|
|
This workspace is the shared assistant workspace. Help the user manage repos, schedules, notifications, settings, and assistant behavior safely.
|
|
|
|
Use the workspace skills when relevant:
|
|
- Load repo-management before schedule-management when you need a repo ID.
|
|
- Load schedule-management for schedule jobs and runs.
|
|
- Load notifications when the user should be notified about important events.
|
|
- Load manager-settings when reading or safely updating UI preferences.
|
|
|
|
Preserve user-customized workspace files unless the user explicitly asks you to change them.
|
|
Ask before destructive operations or changes outside this assistant workspace.
|
|
`
|
|
|
|
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
|
|
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
|
const assistantAgentPath = path.join(ws.assistantDir, '.opencode/agents/assistant.md')
|
|
const legacyAssistantPrompt = legacyAssistantAgent.split('---\n\n')[1]?.trimEnd()
|
|
|
|
if (legacyAssistantPrompt === undefined) throw new Error('Legacy assistant prompt fixture is invalid')
|
|
|
|
await writeFile(agentsMdPath, legacyAgentsMd)
|
|
await writeFile(assistantAgentPath, legacyAssistantAgent)
|
|
await writeFile(opencodeJsonPath, JSON.stringify({
|
|
default_agent: 'assistant',
|
|
instructions: ['AGENTS.md'],
|
|
permission: {
|
|
read: 'allow',
|
|
edit: 'allow',
|
|
glob: 'allow',
|
|
grep: 'allow',
|
|
list: 'allow',
|
|
bash: 'allow',
|
|
external_directory: 'ask',
|
|
},
|
|
agent: {
|
|
assistant: {
|
|
description: 'Default OpenCode Manager assistant workspace agent',
|
|
mode: 'primary',
|
|
prompt: legacyAssistantPrompt,
|
|
permission: {
|
|
read: 'allow',
|
|
edit: 'allow',
|
|
glob: 'allow',
|
|
grep: 'allow',
|
|
list: 'allow',
|
|
bash: 'allow',
|
|
external_directory: 'ask',
|
|
},
|
|
},
|
|
},
|
|
}, null, 2))
|
|
|
|
const result = await ensureAssistantMode(mockRepo)
|
|
|
|
const updatedAgentsMd = await readFile(agentsMdPath, 'utf8')
|
|
const updatedAssistantAgent = await readFile(assistantAgentPath, 'utf8')
|
|
const updatedOpenCodeJson = JSON.parse(await readFile(opencodeJsonPath, 'utf8'))
|
|
|
|
expect(updatedAgentsMd).toContain('Assistant Mode Workspace')
|
|
expect(updatedAgentsMd).toContain('.opencode/agents/assistant.md')
|
|
expect(updatedAgentsMd).not.toContain('Self-Editing Rules')
|
|
|
|
expect(updatedAssistantAgent).toContain('Self-Editing')
|
|
expect(updatedAssistantAgent).toContain('/assistant/reload')
|
|
expect(updatedAssistantAgent).toContain('Always ask the user before reloading')
|
|
expect(updatedAssistantAgent).toContain('repo-management')
|
|
expect(updatedAssistantAgent).toContain('schedule-management')
|
|
expect(updatedAssistantAgent).toContain('notifications')
|
|
expect(updatedAssistantAgent).toContain('manager-settings')
|
|
|
|
expect(updatedOpenCodeJson.agent.assistant.prompt).toBeUndefined()
|
|
expect(updatedOpenCodeJson.agent.assistant.description).toBeUndefined()
|
|
expect(updatedOpenCodeJson.agent.assistant.permission).toBeUndefined()
|
|
expect(updatedOpenCodeJson.agent.assistant.mode).toBe('primary')
|
|
|
|
expect(result.files.agentsMd?.created).toBe(true)
|
|
expect(result.files.opencodeJson?.created).toBe(true)
|
|
expect(result.defaultAgent?.created).toBe(true)
|
|
})
|
|
|
|
it('migrates previous-generation generated AGENTS.md that still mentions the internal token', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
|
|
|
|
const previousAgentsMd = `# Assistant Mode Workspace
|
|
|
|
This directory is the shared Assistant Mode workspace for OpenCode Manager.
|
|
|
|
## Directory Contents
|
|
|
|
- \`opencode.json\` configures this workspace and selects the default assistant agent.
|
|
- \`.opencode/agents/assistant.md\` contains the default assistant agent instructions, behavior, durable preferences, and self-editing rules.
|
|
- \`.opencode/skills/\` contains managed workspace skills for repos, schedules, notifications, and settings.
|
|
- \`.opencode/internal-token\` is managed by OpenCode Manager for internal API authentication.
|
|
|
|
Assistant-specific instructions belong in \`.opencode/agents/assistant.md\`.
|
|
`
|
|
await writeFile(agentsMdPath, previousAgentsMd)
|
|
|
|
const result = await ensureAssistantMode(mockRepo)
|
|
|
|
const updatedAgentsMd = await readFile(agentsMdPath, 'utf8')
|
|
expect(updatedAgentsMd).toContain('Assistant Mode Workspace')
|
|
expect(updatedAgentsMd).toContain('.opencode/agents/assistant.md')
|
|
expect(updatedAgentsMd).not.toContain('.opencode/internal-token')
|
|
expect(result.files.agentsMd?.created).toBe(true)
|
|
})
|
|
|
|
it('preserves custom AGENTS.md content on subsequent ensureAssistantMode calls', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
|
|
|
|
const customContent = '# Custom Assistant Workspace\n\nThis is my custom AGENTS.md content.'
|
|
await writeFile(agentsMdPath, customContent)
|
|
|
|
const result = await ensureAssistantMode(mockRepo)
|
|
|
|
const preservedContent = await readFile(agentsMdPath, 'utf8')
|
|
expect(preservedContent).toBe(customContent)
|
|
expect(result.files.agentsMd?.created).toBe(false)
|
|
})
|
|
|
|
it('warns when managed updates apply but customized legacy AGENTS.md is preserved', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
|
|
const assistantAgentPath = path.join(ws.assistantDir, '.opencode/agents/assistant.md')
|
|
|
|
await writeFile(agentsMdPath, `# Assistant Mode Instructions
|
|
|
|
This folder is the shared Assistant mode workspace for OpenCode Manager.
|
|
|
|
## Self-Editing Rules
|
|
|
|
The agent MAY self-edit the following files within this workspace:
|
|
- \`AGENTS.md\` - Assistant instructions, persona, and durable preferences
|
|
`)
|
|
await writeFile(assistantAgentPath, `---
|
|
description: Default OpenCode Manager assistant workspace agent
|
|
mode: primary
|
|
permission:
|
|
read: allow
|
|
edit: allow
|
|
glob: allow
|
|
grep: allow
|
|
list: allow
|
|
bash: allow
|
|
external_directory: ask
|
|
---
|
|
|
|
You are the default Assistant Mode agent for OpenCode Manager.
|
|
|
|
This workspace is the shared assistant workspace. Help the user manage repos, schedules, notifications, settings, and assistant behavior safely.
|
|
|
|
Use the workspace skills when relevant:
|
|
- Load repo-management before schedule-management when you need a repo ID.
|
|
- Load schedule-management for schedule jobs and runs.
|
|
- Load notifications when the user should be notified about important events.
|
|
- Load manager-settings when reading or safely updating UI preferences.
|
|
|
|
Preserve user-customized workspace files unless the user explicitly asks you to change them.
|
|
Ask before destructive operations or changes outside this assistant workspace.
|
|
`)
|
|
|
|
const result = await ensureAssistantMode(mockRepo)
|
|
|
|
const preservedAgentsMd = await readFile(agentsMdPath, 'utf8')
|
|
expect(preservedAgentsMd).toContain('Self-Editing Rules')
|
|
expect(result.files.agentsMd?.created).toBe(false)
|
|
expect(result.defaultAgent?.created).toBe(true)
|
|
expect(result.warnings?.[0]?.code).toBe('assistant-agents-md-preserved')
|
|
expect(result.warnings?.[0]?.message).toContain('manually delete AGENTS.md')
|
|
})
|
|
|
|
it('overwrites custom AGENTS.md when overwriteAgentsMd is true', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
|
|
|
|
const customContent = '# Custom Assistant Workspace\n\nThis is my custom AGENTS.md content.'
|
|
await writeFile(agentsMdPath, customContent)
|
|
|
|
const result = await ensureAssistantMode(mockRepo, { overwriteAgentsMd: true })
|
|
|
|
const updatedContent = await readFile(agentsMdPath, 'utf8')
|
|
expect(updatedContent).toContain('Assistant Mode Workspace')
|
|
expect(updatedContent).toContain('.opencode/agents/assistant.md')
|
|
expect(updatedContent).not.toBe(customContent)
|
|
expect(result.files.agentsMd?.created).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('assistant-mode end-to-end', () => {
|
|
let ws: Awaited<ReturnType<typeof createTempAssistantWorkspace>>
|
|
let db: ReturnType<typeof createTestDb>
|
|
|
|
beforeEach(async () => {
|
|
ws = await createTempAssistantWorkspace()
|
|
db = createTestDb()
|
|
})
|
|
afterEach(async () => { await ws.cleanup() })
|
|
|
|
it('the database internal token authenticates a request to /api/internal/schedules/all', async () => {
|
|
await ensureAssistantMode(mockRepo)
|
|
|
|
const token = getOrCreateInternalToken(db)
|
|
|
|
const stubWorktreeManager = { prepare: () => Promise.resolve(null), finalize: () => Promise.resolve({ commitHash: null }) } as unknown as ScheduleWorktreeManager
|
|
const scheduleService = new ScheduleService(db, createOpenCodeClient(), stubWorktreeManager)
|
|
const notificationService = new NotificationService(db)
|
|
const settingsService = new SettingsService(db)
|
|
const app = new Hono()
|
|
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, createOpenCodeClient()))
|
|
|
|
const unauth = await app.request('/api/internal/schedules/all')
|
|
expect(unauth.status).toBe(401)
|
|
|
|
const authed = await app.request('/api/internal/schedules/all', {
|
|
headers: { authorization: `Bearer ${token}` },
|
|
})
|
|
expect(authed.status).toBe(200)
|
|
const body = await authed.json() as { jobs: unknown[] }
|
|
expect(Array.isArray(body.jobs)).toBe(true)
|
|
})
|
|
})
|
|
|
|
describe('buildAssistantRepo', () => {
|
|
it('returns the synthetic assistant repo with id 0', () => {
|
|
const repo = buildAssistantRepo()
|
|
expect(repo.id).toBe(0)
|
|
expect(repo.localPath).toBe('assistant')
|
|
expect(repo.cloneStatus).toBe('ready')
|
|
expect(repo.repoUrl).toBeUndefined()
|
|
expect(repo.isWorktree).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('installAssistantWorkspace', () => {
|
|
let ws: Awaited<ReturnType<typeof createTempAssistantWorkspace>>
|
|
let db: ReturnType<typeof createTestDb>
|
|
|
|
beforeEach(async () => {
|
|
ws = await createTempAssistantWorkspace()
|
|
db = createTestDb()
|
|
})
|
|
afterEach(async () => { await ws.cleanup() })
|
|
|
|
it('provisions the assistant workspace files without contacting OpenCode', async () => {
|
|
const result = await installAssistantWorkspace({ db })
|
|
|
|
const opencodeJson = await readFile(path.join(ws.assistantDir, 'opencode.json'), 'utf8')
|
|
expect(JSON.parse(opencodeJson).default_agent).toBe('assistant')
|
|
|
|
const agentsMd = await readFile(path.join(ws.assistantDir, 'AGENTS.md'), 'utf8')
|
|
expect(agentsMd).toContain('Assistant Mode Workspace')
|
|
|
|
const assistantAgent = await readFile(path.join(ws.assistantDir, '.opencode/agents/assistant.md'), 'utf8')
|
|
expect(assistantAgent).toContain('mode: primary')
|
|
|
|
expect(result.files.opencodeJson?.exists).toBe(true)
|
|
expect(result.files.agentsMd?.exists).toBe(true)
|
|
expect(result.defaultAgent?.exists).toBe(true)
|
|
expect(result.repoId).toBe(0)
|
|
|
|
const assistantRepo = getRepoById(db, 0)
|
|
expect(assistantRepo?.id).toBe(0)
|
|
expect(assistantRepo?.localPath).toBe('assistant')
|
|
expect(assistantRepo?.fullPath).toBe(ws.assistantDir)
|
|
expect(assistantRepo?.cloneStatus).toBe('ready')
|
|
expect(assistantRepo?.defaultBranch).toBe('main')
|
|
})
|
|
|
|
it('repairs an assistant row created with a non-zero id', async () => {
|
|
db.prepare(`
|
|
INSERT INTO repos (
|
|
id,
|
|
repo_url,
|
|
local_path,
|
|
source_path,
|
|
branch,
|
|
default_branch,
|
|
clone_status,
|
|
cloned_at,
|
|
last_accessed_at,
|
|
is_worktree,
|
|
is_local
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
`).run(99, null, 'assistant', null, null, 'main', 'ready', Date.now(), Date.now(), 0, 0)
|
|
db.prepare(`
|
|
INSERT INTO schedule_jobs (
|
|
repo_id,
|
|
name,
|
|
description,
|
|
enabled,
|
|
interval_minutes,
|
|
schedule_mode,
|
|
cron_expression,
|
|
timezone,
|
|
agent_slug,
|
|
prompt,
|
|
model,
|
|
skill_metadata,
|
|
created_at,
|
|
updated_at,
|
|
last_run_at,
|
|
next_run_at
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
`).run(99, 'Assistant job', null, 1, 60, 'interval', null, null, null, 'hello', null, null, Date.now(), Date.now(), null, null)
|
|
|
|
await installAssistantWorkspace({ db })
|
|
|
|
expect(getRepoById(db, 99)).toBeNull()
|
|
const assistantRepo = getRepoById(db, 0)
|
|
expect(assistantRepo?.localPath).toBe('assistant')
|
|
|
|
const migratedJob = db.prepare('SELECT repo_id FROM schedule_jobs WHERE name = ?').get('Assistant job') as { repo_id: number }
|
|
expect(migratedJob.repo_id).toBe(0)
|
|
})
|
|
|
|
it('is idempotent — second call does not recreate files and content is unchanged', async () => {
|
|
await installAssistantWorkspace({ db })
|
|
|
|
const opencodeJsonPath = path.join(ws.assistantDir, 'opencode.json')
|
|
const agentsMdPath = path.join(ws.assistantDir, 'AGENTS.md')
|
|
const assistantAgentPath = path.join(ws.assistantDir, '.opencode/agents/assistant.md')
|
|
|
|
const firstContent = {
|
|
opencodeJson: await readFile(opencodeJsonPath, 'utf8'),
|
|
agentsMd: await readFile(agentsMdPath, 'utf8'),
|
|
assistantAgent: await readFile(assistantAgentPath, 'utf8'),
|
|
}
|
|
|
|
const result = await installAssistantWorkspace({ db })
|
|
|
|
const secondContent = {
|
|
opencodeJson: await readFile(opencodeJsonPath, 'utf8'),
|
|
agentsMd: await readFile(agentsMdPath, 'utf8'),
|
|
assistantAgent: await readFile(assistantAgentPath, 'utf8'),
|
|
}
|
|
|
|
expect(secondContent.opencodeJson).toBe(firstContent.opencodeJson)
|
|
expect(secondContent.agentsMd).toBe(firstContent.agentsMd)
|
|
expect(secondContent.assistantAgent).toBe(firstContent.assistantAgent)
|
|
|
|
expect(result.files.opencodeJson?.created).toBe(false)
|
|
expect(result.files.agentsMd?.created).toBe(false)
|
|
expect(result.defaultAgent?.created).toBe(false)
|
|
})
|
|
})
|
|
|
|
describe('assistant mode directory contract', () => {
|
|
it('resolves the assistant directory and .opencode directory under the workspace', async () => {
|
|
const ws = await createTempAssistantWorkspace()
|
|
try {
|
|
const { getAssistantModePath, getAssistantOpenCodeDir } = await import('@opencode-manager/shared/config/env')
|
|
const { getAssistantModeDirectory } = await import('../../src/services/assistant-mode')
|
|
|
|
expect(getAssistantModeDirectory()).toBe(getAssistantModePath())
|
|
expect(getAssistantOpenCodeDir()).toBe(path.join(ws.assistantDir, '.opencode'))
|
|
} finally {
|
|
await ws.cleanup()
|
|
}
|
|
})
|
|
})
|