mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(sandbox): route notifications through a host-side manager tool
This commit is contained in:
1 parent
098816f7cc
commit
f6c368265f
8 files changed
+517
-51
No files matched your search
@@ -12,11 +12,12 @@ import {
|
||||
fileExists,
|
||||
ensureDirectoryExists,
|
||||
} from './file-operations'
|
||||
import { OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, OpenCodeConfigSchema } from '@opencode-manager/shared/schemas'
|
||||
import { ASSISTANT_REPO_ID, ASSISTANT_REPO_PATH, ASSISTANT_OPENCODE_DIR_NAME } from '@opencode-manager/shared/utils'
|
||||
import { getAssistantModePath, getReposPath, ENV } from '@opencode-manager/shared/config/env'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import { getOrCreateInternalToken } from './internal-token'
|
||||
import { MANAGER_TOOL_NAME } from './opencode-manager-tool-plugin'
|
||||
import { ensureAssistantRepo } from '../db/queries'
|
||||
|
||||
|
||||
@@ -438,77 +439,61 @@ Always confirm destructive operations (\`DELETE\` jobs, \`cancel\` runs) with th
|
||||
`
|
||||
}
|
||||
|
||||
export function buildNotificationsSkill(baseUrl: string): string {
|
||||
const internalBaseUrl = toLocalhostInternalBaseUrl(baseUrl)
|
||||
|
||||
export function buildNotificationsSkill(): string {
|
||||
return `---
|
||||
name: notifications
|
||||
description: Send push notifications to the user's registered devices via the internal HTTP API
|
||||
description: Send push notifications to the user's registered devices with the ${MANAGER_TOOL_NAME} tool
|
||||
---
|
||||
|
||||
## When to Load
|
||||
|
||||
Load this skill when you need to notify the user about important events, completed tasks, or questions that require their attention.
|
||||
|
||||
## Authentication
|
||||
## Tool
|
||||
|
||||
All API calls require a bearer token. Read the token from \`.opencode/internal-token\` (relative to the assistant workspace cwd) and pass it as:
|
||||
Use the \`${MANAGER_TOOL_NAME}\` tool with the \`send_notification\` action. The tool runs inside OpenCode Manager, so it needs no token, no base URL, and no network access from the shell. It works the same in a normal session, a sandboxed session, and a scheduled run.
|
||||
|
||||
\`\`\`
|
||||
Authorization: Bearer <token>
|
||||
\`\`\`
|
||||
The tool declares its arguments as a typed schema, so the editor and the model both see the exact shape and the tool call is rejected before it runs if it does not match.
|
||||
|
||||
## Base URL
|
||||
|
||||
\`${internalBaseUrl}\`
|
||||
|
||||
## Endpoint
|
||||
|
||||
### POST /notifications/send
|
||||
|
||||
Send a push notification to all of the user's registered devices.
|
||||
|
||||
**Query Parameters:**
|
||||
- \`userId\` (optional): User ID. Defaults to \`"default"\`.
|
||||
|
||||
**Request Body:**
|
||||
**Arguments:**
|
||||
\`\`\`ts
|
||||
{
|
||||
title: string // 1-120 characters
|
||||
body: string // 1-500 characters
|
||||
url?: string // Optional: deep link to navigate to (1-500 chars)
|
||||
tag?: string // Optional: notification tag for deduplication (max 80 chars)
|
||||
priority?: 'normal' | 'high' // Defaults to 'normal'
|
||||
action: 'send_notification',
|
||||
params: {
|
||||
title: string // 1-${ASSISTANT_NOTIFICATION_LIMITS.TITLE_MAX} characters
|
||||
body: string // 1-${ASSISTANT_NOTIFICATION_LIMITS.BODY_MAX} characters
|
||||
url?: string // Optional: deep link to navigate to (1-${ASSISTANT_NOTIFICATION_LIMITS.URL_MAX} chars)
|
||||
tag?: string // Optional: notification tag for deduplication (max ${ASSISTANT_NOTIFICATION_LIMITS.TAG_MAX} chars)
|
||||
priority?: 'normal' | 'high' // Defaults to 'normal'
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
**Example:**
|
||||
\`\`\`bash
|
||||
curl -X POST -H "Authorization: Bearer <token>" \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{"title":"Task Complete","body":"The build has finished successfully","url":"/repos/my-repo","priority":"high"}' \\
|
||||
"${internalBaseUrl}/notifications/send?userId=default"
|
||||
\`\`\`
|
||||
|
||||
**Response:**
|
||||
\`\`\`ts
|
||||
\`\`\`json
|
||||
{
|
||||
delivered: number // Number of successfully delivered notifications
|
||||
expired: number // Number of expired subscriptions removed
|
||||
failed: number // Number of failed deliveries
|
||||
noSubscriptions: boolean // True if user has no registered devices
|
||||
"action": "send_notification",
|
||||
"params": {
|
||||
"title": "Task Complete",
|
||||
"body": "The build has finished successfully",
|
||||
"url": "/repos/my-repo",
|
||||
"priority": "high"
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
|
||||
The tool reports how many devices the notification was delivered to, and says so explicitly when the user has no registered devices.
|
||||
|
||||
## Rate Limiting
|
||||
|
||||
The endpoint enforces a rate limit of **10 requests per minute per token**. If exceeded, you'll receive a \`429 Too Many Requests\` response with a \`Retry-After\` header.
|
||||
Sending is rate limited to **10 notifications per minute**. Beyond that the tool fails with a \`429\` status; wait before retrying.
|
||||
|
||||
## Notes
|
||||
|
||||
- Notifications are only sent if the user has registered devices (browser push subscriptions)
|
||||
- If VAPID is not configured on the server, the endpoint returns \`503 Service Unavailable\`
|
||||
- If VAPID is not configured on the server, the tool fails with a \`503\` status
|
||||
- Use \`priority: 'high'\` for urgent notifications that should interrupt the user
|
||||
- Do not call the internal HTTP API with \`curl\` for notifications; the tool is the supported path
|
||||
`
|
||||
}
|
||||
|
||||
@@ -834,7 +819,7 @@ export async function ensureAssistantMode(
|
||||
}
|
||||
|
||||
const notificationsSkillPath = getNotificationsSkillPath(assistantDir)
|
||||
const notificationsSkillContent = buildNotificationsSkill(deps.apiBaseUrl)
|
||||
const notificationsSkillContent = buildNotificationsSkill()
|
||||
const existingNotificationsSkillContent = await fileExists(notificationsSkillPath) ? await readFileContent(notificationsSkillPath) : undefined
|
||||
const notificationsSkillCreated = !hasSameContentHash(existingNotificationsSkillContent, notificationsSkillContent)
|
||||
if (notificationsSkillCreated) {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS } from '@opencode-manager/shared/schemas'
|
||||
|
||||
export const MANAGER_TOOL_NAME = 'ocm'
|
||||
|
||||
export const MANAGER_TOOL_REQUEST_TIMEOUT_MS = 15000
|
||||
|
||||
export function buildManagerToolPluginSource(): string {
|
||||
return `import { z } from 'zod'
|
||||
|
||||
var REQUEST_TIMEOUT_MS = ${MANAGER_TOOL_REQUEST_TIMEOUT_MS}
|
||||
|
||||
async function postInternalApi(routePath, body) {
|
||||
var baseUrl = process.env.OCM_INTERNAL_API_URL
|
||||
var token = process.env.OCM_INTERNAL_TOKEN
|
||||
if (!baseUrl || !token) {
|
||||
throw new Error('The OpenCode Manager internal API is not configured for this OpenCode server.')
|
||||
}
|
||||
var response
|
||||
try {
|
||||
response = await fetch(baseUrl + routePath, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', Authorization: 'Bearer ' + token },
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
})
|
||||
} catch (error) {
|
||||
throw new Error('The OpenCode Manager request failed: ' + (error instanceof Error ? error.message : String(error)))
|
||||
}
|
||||
var text = await response.text()
|
||||
if (!response.ok) {
|
||||
throw new Error('The OpenCode Manager request failed with status ' + response.status + (text ? ': ' + text : ''))
|
||||
}
|
||||
try {
|
||||
return JSON.parse(text)
|
||||
} catch (error) {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
var ACTIONS = {
|
||||
send_notification: {
|
||||
params: z.object({
|
||||
title: z.string().min(1).max(${ASSISTANT_NOTIFICATION_LIMITS.TITLE_MAX}).describe('The notification title.'),
|
||||
body: z.string().min(1).max(${ASSISTANT_NOTIFICATION_LIMITS.BODY_MAX}).describe('The notification body.'),
|
||||
url: z.string().min(1).max(${ASSISTANT_NOTIFICATION_LIMITS.URL_MAX}).optional().describe('A deep link to open, such as /repos/my-repo.'),
|
||||
tag: z.string().max(${ASSISTANT_NOTIFICATION_LIMITS.TAG_MAX}).optional().describe('A deduplication key for replacing an earlier notification.'),
|
||||
priority: z.enum(['normal', 'high']).optional().describe('Use high for something that should interrupt the user.'),
|
||||
}).describe('Send a push notification to every device the user has registered.'),
|
||||
run: async function (params) {
|
||||
var result = await postInternalApi('/notifications/send', params)
|
||||
if (result.noSubscriptions === true) {
|
||||
return 'No devices are registered for push notifications, so nothing was delivered.'
|
||||
}
|
||||
return 'Notification sent: ' + (result.delivered || 0) + ' delivered, ' + (result.failed || 0) + ' failed.'
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var ACTION_NAMES = Object.keys(ACTIONS)
|
||||
|
||||
export default async function () {
|
||||
return {
|
||||
tool: {
|
||||
${MANAGER_TOOL_NAME}: {
|
||||
description: [
|
||||
'Perform an OpenCode Manager action.',
|
||||
'The action runs inside OpenCode Manager itself, so it needs no token and no network access from the agent shell, and it works in sandboxed sessions and scheduled runs.',
|
||||
'Actions:',
|
||||
'- send_notification: send a push notification to every device the user has registered.',
|
||||
].join('\\n'),
|
||||
args: {
|
||||
action: z.enum(ACTION_NAMES).describe('The OpenCode Manager action to perform.'),
|
||||
params: z.union(ACTION_NAMES.map(function (name) { return ACTIONS[name].params })).describe('The parameters for the chosen action.'),
|
||||
},
|
||||
execute: async function (args) {
|
||||
if (!Object.prototype.hasOwnProperty.call(ACTIONS, args.action)) {
|
||||
throw new Error('Unknown OpenCode Manager action: ' + String(args.action) + '. Supported actions: ' + ACTION_NAMES.join(', ') + '.')
|
||||
}
|
||||
var action = ACTIONS[args.action]
|
||||
return await action.run(action.params.parse(args.params))
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
`
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { join } from 'path'
|
||||
import { writeFileAtomic } from '../../utils/fs-safe'
|
||||
import { buildGhEnvPluginSource } from '../opencode-gh-env-plugin'
|
||||
import { buildManagerToolPluginSource } from '../opencode-manager-tool-plugin'
|
||||
import { buildSandboxPluginSource } from '../opencode-sandbox-plugin'
|
||||
import { ensureSandboxShellShim } from '../sandbox/shell-shim'
|
||||
|
||||
@@ -11,6 +12,7 @@ type ManagedOpenCodePlugin = {
|
||||
|
||||
const MANAGED_OPENCODE_PLUGINS: readonly ManagedOpenCodePlugin[] = [
|
||||
{ filename: 'ocm-gh-env.js', buildSource: () => buildGhEnvPluginSource() },
|
||||
{ filename: 'ocm-manager.js', buildSource: () => buildManagerToolPluginSource() },
|
||||
{ filename: 'ocm-sandbox.js', buildSource: ({ shellShimPath }) => buildSandboxPluginSource(shellShimPath) },
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
|
||||
import { promises as fs } from 'fs'
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
|
||||
import { spawn, spawnSync } from 'child_process'
|
||||
import http from 'http'
|
||||
import type { AddressInfo } from 'net'
|
||||
import path from 'path'
|
||||
import os from 'os'
|
||||
import { pathToFileURL } from 'url'
|
||||
import { ASSISTANT_NOTIFICATION_LIMITS, AssistantNotificationRequestSchema } from '@opencode-manager/shared/schemas'
|
||||
import { MANAGER_TOOL_NAME } from '../../src/services/opencode-manager-tool-plugin'
|
||||
import { installManagedPlugins, getOpenCodePluginDir } from '../../src/services/opencode/plugin-registry'
|
||||
|
||||
type ZodLike = { safeParse: (value: unknown) => { success: boolean } }
|
||||
|
||||
type ToolDefinition = {
|
||||
description: string
|
||||
args: Record<string, ZodLike>
|
||||
execute: (args: unknown) => Promise<string>
|
||||
}
|
||||
|
||||
type PluginHooks = { tool: Record<string, ToolDefinition | undefined> }
|
||||
|
||||
async function loadTool(configHome: string): Promise<ToolDefinition> {
|
||||
const file = path.join(getOpenCodePluginDir(configHome), 'ocm-manager.js')
|
||||
const mod = await import(`${pathToFileURL(file).href}?t=${Date.now()}`)
|
||||
const hooks = await (mod.default as () => Promise<PluginHooks>)()
|
||||
const tool = hooks.tool[MANAGER_TOOL_NAME]
|
||||
if (!tool) throw new Error(`The generated plugin does not register a "${MANAGER_TOOL_NAME}" tool`)
|
||||
return tool
|
||||
}
|
||||
|
||||
function jsonResponse(body: unknown, { ok = true, status = 200 } = {}) {
|
||||
return vi.fn().mockResolvedValue({
|
||||
ok,
|
||||
status,
|
||||
text: async () => JSON.stringify(body),
|
||||
})
|
||||
}
|
||||
|
||||
describe('ocm-manager plugin', () => {
|
||||
let configHome: string
|
||||
|
||||
beforeEach(async () => {
|
||||
configHome = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-manager-'))
|
||||
await installManagedPlugins(configHome)
|
||||
process.env.OCM_INTERNAL_API_URL = 'http://localhost:5003/api/internal'
|
||||
process.env.OCM_INTERNAL_TOKEN = 'secret-token'
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
vi.unstubAllGlobals()
|
||||
delete process.env.OCM_INTERNAL_API_URL
|
||||
delete process.env.OCM_INTERNAL_TOKEN
|
||||
await fs.rm(configHome, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('registers the manager tool with typed Zod args', async () => {
|
||||
const tool = await loadTool(configHome)
|
||||
|
||||
expect(tool.description).toContain('send_notification')
|
||||
expect(tool.args.action?.safeParse('send_notification').success).toBe(true)
|
||||
expect(tool.args.action?.safeParse('drop_database').success).toBe(false)
|
||||
expect(tool.args.params?.safeParse({ title: 't', body: 'b' }).success).toBe(true)
|
||||
expect(tool.args.params?.safeParse({ title: 't', body: 'b', priority: 'urgent' }).success).toBe(false)
|
||||
})
|
||||
|
||||
it('enforces the notification limits the internal API enforces', async () => {
|
||||
const tool = await loadTool(configHome)
|
||||
const withinLimits = { title: 'x'.repeat(ASSISTANT_NOTIFICATION_LIMITS.TITLE_MAX), body: 'b' }
|
||||
const overLimit = { title: 'x'.repeat(ASSISTANT_NOTIFICATION_LIMITS.TITLE_MAX + 1), body: 'b' }
|
||||
|
||||
expect(AssistantNotificationRequestSchema.safeParse(withinLimits).success).toBe(true)
|
||||
expect(tool.args.params?.safeParse(withinLimits).success).toBe(true)
|
||||
expect(AssistantNotificationRequestSchema.safeParse(overLimit).success).toBe(false)
|
||||
expect(tool.args.params?.safeParse(overLimit).success).toBe(false)
|
||||
})
|
||||
|
||||
it('sends a notification through the internal API with the host token', async () => {
|
||||
const fetchMock = jsonResponse({ delivered: 2, expired: 0, failed: 0, noSubscriptions: false })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const tool = await loadTool(configHome)
|
||||
|
||||
const result = await tool.execute({
|
||||
action: 'send_notification',
|
||||
params: { title: 'Storm watch', body: 'Formation odds crossed 40%', priority: 'high' },
|
||||
})
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [url, init] = fetchMock.mock.calls[0] ?? []
|
||||
expect(url).toBe('http://localhost:5003/api/internal/notifications/send')
|
||||
expect(init.method).toBe('POST')
|
||||
expect(init.headers.Authorization).toBe('Bearer secret-token')
|
||||
expect(JSON.parse(init.body)).toEqual({ title: 'Storm watch', body: 'Formation odds crossed 40%', priority: 'high' })
|
||||
expect(result).toBe('Notification sent: 2 delivered, 0 failed.')
|
||||
})
|
||||
|
||||
it('reports when the user has no registered devices', async () => {
|
||||
vi.stubGlobal('fetch', jsonResponse({ delivered: 0, expired: 0, failed: 0, noSubscriptions: true }))
|
||||
const tool = await loadTool(configHome)
|
||||
|
||||
await expect(tool.execute({ action: 'send_notification', params: { title: 't', body: 'b' } }))
|
||||
.resolves.toBe('No devices are registered for push notifications, so nothing was delivered.')
|
||||
})
|
||||
|
||||
it('surfaces the API status and body when the request is rejected', async () => {
|
||||
vi.stubGlobal('fetch', jsonResponse({ error: 'Rate limit exceeded' }, { ok: false, status: 429 }))
|
||||
const tool = await loadTool(configHome)
|
||||
|
||||
await expect(tool.execute({ action: 'send_notification', params: { title: 't', body: 'b' } }))
|
||||
.rejects.toThrow(/429.*Rate limit exceeded/)
|
||||
})
|
||||
|
||||
it('fails when the internal API is not configured', async () => {
|
||||
delete process.env.OCM_INTERNAL_TOKEN
|
||||
const fetchMock = jsonResponse({})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const tool = await loadTool(configHome)
|
||||
|
||||
await expect(tool.execute({ action: 'send_notification', params: { title: 't', body: 'b' } }))
|
||||
.rejects.toThrow('The OpenCode Manager internal API is not configured for this OpenCode server.')
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects unknown actions and invalid params without calling the API', async () => {
|
||||
const fetchMock = jsonResponse({})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const tool = await loadTool(configHome)
|
||||
|
||||
await expect(tool.execute({ action: 'constructor', params: {} })).rejects.toThrow(/Unknown OpenCode Manager action/)
|
||||
await expect(tool.execute({ action: 'send_notification', params: { title: 't' } })).rejects.toThrow()
|
||||
expect(fetchMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
function resolveOpencodeBinary(): string | null {
|
||||
const candidates = [
|
||||
process.env.OPENCODE_BIN,
|
||||
'opencode',
|
||||
'/usr/local/bin/opencode',
|
||||
'/opt/opencode/bin/opencode',
|
||||
].filter((value): value is string => typeof value === 'string' && value.length > 0)
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const result = spawnSync(candidate, ['--version'], { encoding: 'utf8', timeout: 5000 })
|
||||
if (result.status === 0 && result.stdout && result.stdout.trim().length > 0) {
|
||||
return candidate
|
||||
}
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
const SHIPPED_OPENCODE_BIN = resolveOpencodeBinary()
|
||||
|
||||
type ChatRequest = { messages?: unknown[]; tools?: { function?: { name?: string; parameters?: unknown } }[] }
|
||||
|
||||
describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the shipped OpenCode binary', () => {
|
||||
let root: string
|
||||
|
||||
function startInternalApiServer(requests: string[]) {
|
||||
const server = http.createServer((req, res) => {
|
||||
let body = ''
|
||||
req.on('data', (chunk: Buffer) => {
|
||||
body += chunk.toString()
|
||||
})
|
||||
req.on('end', () => {
|
||||
if (req.method === 'POST' && req.url?.endsWith('/notifications/send')) {
|
||||
requests.push(JSON.stringify({ auth: req.headers.authorization, body }))
|
||||
}
|
||||
res.writeHead(200, { 'content-type': 'application/json' })
|
||||
res.end(JSON.stringify({ delivered: 1, expired: 0, failed: 0, noSubscriptions: false }))
|
||||
})
|
||||
})
|
||||
return new Promise<{ server: http.Server; port: number }>((resolve) => {
|
||||
server.listen(0, '127.0.0.1', () => resolve({ server, port: (server.address() as AddressInfo).port }))
|
||||
})
|
||||
}
|
||||
|
||||
function startLlmServer(offeredTools: ChatRequest['tools'][], toolResults: string[]) {
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method === 'GET' && req.url?.endsWith('/models')) {
|
||||
res.writeHead(200, { 'content-type': 'application/json' })
|
||||
res.end(JSON.stringify({ object: 'list', data: [{ id: 'mock-model', object: 'model' }] }))
|
||||
return
|
||||
}
|
||||
if (req.method !== 'POST' || !req.url?.endsWith('/chat/completions')) {
|
||||
res.writeHead(404)
|
||||
res.end()
|
||||
return
|
||||
}
|
||||
let body = ''
|
||||
req.on('data', (chunk: Buffer) => {
|
||||
body += chunk.toString()
|
||||
})
|
||||
req.on('end', () => {
|
||||
const parsed = JSON.parse(body || '{}') as ChatRequest
|
||||
offeredTools.push(parsed.tools ?? [])
|
||||
const messages = parsed.messages ?? []
|
||||
const toolMessages = messages.filter((m) => (m as { role?: string }).role === 'tool')
|
||||
for (const message of toolMessages) {
|
||||
toolResults.push(String((message as { content?: unknown }).content ?? ''))
|
||||
}
|
||||
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' })
|
||||
const writeChunk = (obj: unknown) => res.write(`data: ${JSON.stringify(obj)}\n\n`)
|
||||
const base = { id: 'chatcmpl-e2e', object: 'chat.completion.chunk', created: 1, model: 'mock-model' }
|
||||
const hasTools = Array.isArray(parsed.tools) && parsed.tools.length > 0
|
||||
|
||||
if (hasTools && toolMessages.length === 0) {
|
||||
const args = JSON.stringify({
|
||||
action: 'send_notification',
|
||||
params: { title: 'Storm watch', body: 'Formation odds crossed 40%', priority: 'high' },
|
||||
})
|
||||
writeChunk({
|
||||
...base,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
role: 'assistant',
|
||||
content: null,
|
||||
tool_calls: [{ index: 0, id: 'call_1', type: 'function', function: { name: MANAGER_TOOL_NAME, arguments: '' } }],
|
||||
},
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
})
|
||||
writeChunk({
|
||||
...base,
|
||||
choices: [{ index: 0, delta: { tool_calls: [{ index: 0, function: { arguments: args } }] }, finish_reason: null }],
|
||||
})
|
||||
writeChunk({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] })
|
||||
} else {
|
||||
writeChunk({ ...base, choices: [{ index: 0, delta: { role: 'assistant', content: '' }, finish_reason: null }] })
|
||||
writeChunk({ ...base, choices: [{ index: 0, delta: { content: 'FINAL' }, finish_reason: null }] })
|
||||
writeChunk({ ...base, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })
|
||||
}
|
||||
res.write('data: [DONE]\n\n')
|
||||
res.end()
|
||||
})
|
||||
})
|
||||
return new Promise<{ server: http.Server; port: number }>((resolve) => {
|
||||
server.listen(0, '127.0.0.1', () => resolve({ server, port: (server.address() as AddressInfo).port }))
|
||||
})
|
||||
}
|
||||
|
||||
function writeOpenCodeConfig(configHome: string, llmPort: number) {
|
||||
writeFileSync(
|
||||
path.join(configHome, 'opencode', 'opencode.json'),
|
||||
JSON.stringify({
|
||||
provider: {
|
||||
mock: {
|
||||
npm: '@ai-sdk/openai-compatible',
|
||||
name: 'Mock',
|
||||
options: { baseURL: `http://127.0.0.1:${llmPort}/v1`, apiKey: 'mock-key' },
|
||||
models: { 'mock-model': { name: 'Mock Model' } },
|
||||
},
|
||||
},
|
||||
model: 'mock/mock-model',
|
||||
permission: { bash: 'allow', read: 'allow', edit: 'allow', write: 'allow' },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
function runOpencode(workDir: string, env: Record<string, string>) {
|
||||
return new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve, reject) => {
|
||||
const child = spawn(SHIPPED_OPENCODE_BIN as string, ['run', '--auto', '--format', 'json', 'notify the user'], {
|
||||
cwd: workDir,
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
env,
|
||||
})
|
||||
let stdout = ''
|
||||
let stderr = ''
|
||||
child.stdout?.on('data', (chunk: Buffer) => {
|
||||
stdout += chunk.toString()
|
||||
})
|
||||
child.stderr?.on('data', (chunk: Buffer) => {
|
||||
stderr += chunk.toString()
|
||||
})
|
||||
const timer = setTimeout(() => {
|
||||
child.kill('SIGKILL')
|
||||
resolve({ status: null, stdout, stderr })
|
||||
}, 90000)
|
||||
child.on('close', (code) => {
|
||||
clearTimeout(timer)
|
||||
resolve({ status: code, stdout, stderr })
|
||||
})
|
||||
child.on('error', (error) => {
|
||||
clearTimeout(timer)
|
||||
reject(error)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(path.join(os.tmpdir(), 'ocm-manager-e2e-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('offers the tool to the model and sends the notification from the Manager process', async () => {
|
||||
const configHome = path.join(root, 'config')
|
||||
const workDir = path.join(root, 'work')
|
||||
mkdirSync(path.join(configHome, 'opencode', 'plugin'), { recursive: true })
|
||||
mkdirSync(workDir, { recursive: true })
|
||||
|
||||
const apiRequests: string[] = []
|
||||
const offeredTools: ChatRequest['tools'][] = []
|
||||
const toolResults: string[] = []
|
||||
const api = await startInternalApiServer(apiRequests)
|
||||
const llm = await startLlmServer(offeredTools, toolResults)
|
||||
writeOpenCodeConfig(configHome, llm.port)
|
||||
await installManagedPlugins(configHome)
|
||||
|
||||
try {
|
||||
const result = await runOpencode(workDir, {
|
||||
...process.env,
|
||||
HOME: root,
|
||||
XDG_CONFIG_HOME: configHome,
|
||||
PWD: workDir,
|
||||
OCM_SANDBOX_ENFORCED: 'false',
|
||||
OCM_INTERNAL_API_URL: `http://127.0.0.1:${api.port}/api/internal`,
|
||||
OCM_INTERNAL_TOKEN: 'test-token',
|
||||
})
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
|
||||
const managerTool = offeredTools.flatMap((tools) => tools ?? []).find((t) => t.function?.name === MANAGER_TOOL_NAME)
|
||||
expect(managerTool?.function?.parameters).toMatchObject({
|
||||
type: 'object',
|
||||
properties: {
|
||||
action: { type: 'string', enum: ['send_notification'] },
|
||||
params: {
|
||||
anyOf: [
|
||||
{
|
||||
type: 'object',
|
||||
required: ['title', 'body'],
|
||||
properties: {
|
||||
title: { type: 'string', minLength: 1, maxLength: ASSISTANT_NOTIFICATION_LIMITS.TITLE_MAX },
|
||||
body: { type: 'string', minLength: 1, maxLength: ASSISTANT_NOTIFICATION_LIMITS.BODY_MAX },
|
||||
url: { type: 'string', maxLength: ASSISTANT_NOTIFICATION_LIMITS.URL_MAX },
|
||||
tag: { type: 'string', maxLength: ASSISTANT_NOTIFICATION_LIMITS.TAG_MAX },
|
||||
priority: { type: 'string', enum: ['normal', 'high'] },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
required: ['action', 'params'],
|
||||
})
|
||||
|
||||
expect(apiRequests).toHaveLength(1)
|
||||
const request = JSON.parse(apiRequests[0] as string) as { auth: string; body: string }
|
||||
expect(request.auth).toBe('Bearer test-token')
|
||||
expect(JSON.parse(request.body)).toEqual({ title: 'Storm watch', body: 'Formation odds crossed 40%', priority: 'high' })
|
||||
expect(toolResults.some((output) => output.includes('Notification sent: 1 delivered, 0 failed.'))).toBe(true)
|
||||
} finally {
|
||||
api.server.close()
|
||||
llm.server.close()
|
||||
}
|
||||
}, 120000)
|
||||
})
|
||||
@@ -14,13 +14,28 @@ Include the token in requests:
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
## The `ocm` Tool
|
||||
|
||||
The Manager installs a generated plugin (`ocm-manager.js`) that gives every agent an `ocm` tool. The tool calls this API from inside the Manager's own OpenCode process, so it needs no token, no base URL, and no network access from the agent shell.
|
||||
|
||||
That makes it the only path that works everywhere: a scheduled run executes in a throwaway worktree with no `.opencode/internal-token`, and a sandboxed `bash` call runs in a microVM where `localhost` is the guest, not the Manager.
|
||||
|
||||
```ts
|
||||
{
|
||||
action: 'send_notification',
|
||||
params: { title: string, body: string, url?: string, tag?: string, priority?: 'normal' | 'high' }
|
||||
}
|
||||
```
|
||||
|
||||
The bearer-token endpoints below remain available for agents running in the assistant workspace without sandboxing.
|
||||
|
||||
## Endpoints
|
||||
|
||||
### Notifications
|
||||
|
||||
**POST `/api/internal/notifications/send`**
|
||||
|
||||
Send push notifications to the user's registered devices.
|
||||
Send push notifications to the user's registered devices. Prefer the `ocm` tool with the `send_notification` action.
|
||||
|
||||
**Request Body:**
|
||||
```ts
|
||||
|
||||
@@ -21,7 +21,7 @@ Four skills are provisioned automatically when assistant mode is initialized:
|
||||
| Skill | What it teaches |
|
||||
|-------|----------------|
|
||||
| `schedule-management` | Create, list, update, delete, and run scheduled jobs |
|
||||
| `notifications` | Send push notifications to registered user devices |
|
||||
| `notifications` | Send push notifications to registered user devices with the `ocm` tool |
|
||||
| `manager-settings` | Read and patch user preferences, and reload the assistant workspace |
|
||||
| `repo-management` | List all managed repositories |
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ The microVM sees repositories through bind mounts at the same paths used by the
|
||||
| OpenCode file tools | No |
|
||||
| Manager-side git operations | No |
|
||||
| Plugins and custom tools | No; normal OpenCode behavior |
|
||||
| The `ocm` tool (`ocm-manager.js`) | No; runs in the Manager's OpenCode process |
|
||||
| Local MCP servers | No; normal OpenCode behavior |
|
||||
| Formatters, LSP servers, and hooks | No; normal OpenCode behavior |
|
||||
| Custom provider modules | No; normal OpenCode behavior |
|
||||
@@ -89,6 +90,8 @@ The microVM receives writable bind mounts for:
|
||||
|
||||
The assistant workspace's `repos/assistant/.opencode` directory falls beneath the repository mount but is hidden in the guest behind a `tmpfs` mask so its internal API token cannot be read by agent commands.
|
||||
|
||||
Because of that mask, and because `localhost` inside the microVM is the guest rather than the Manager, an agent command cannot call the internal API with `curl`. Agents reach the Manager through the `ocm` tool instead, which executes in the Manager's own OpenCode process and never exposes the token to the guest.
|
||||
|
||||
The microVM also mounts a runtime-owned tmpfs at `/tmp`. It is sized to one quarter of the microVM memory, clamped to 1-512 MiB, so agent commands get writable scratch space that is not backed by a host filesystem.
|
||||
|
||||
The following remain outside the microVM:
|
||||
|
||||
@@ -3,11 +3,18 @@ import { UserPreferencesSchema } from './settings'
|
||||
|
||||
export const AssistantNotificationPrioritySchema = z.enum(['normal', 'high'])
|
||||
|
||||
export const ASSISTANT_NOTIFICATION_LIMITS = {
|
||||
TITLE_MAX: 120,
|
||||
BODY_MAX: 500,
|
||||
URL_MAX: 500,
|
||||
TAG_MAX: 80,
|
||||
} as const
|
||||
|
||||
export const AssistantNotificationRequestSchema = z.object({
|
||||
title: z.string().min(1).max(120),
|
||||
body: z.string().min(1).max(500),
|
||||
url: z.string().min(1).max(500).optional(),
|
||||
tag: z.string().max(80).optional(),
|
||||
title: z.string().min(1).max(ASSISTANT_NOTIFICATION_LIMITS.TITLE_MAX),
|
||||
body: z.string().min(1).max(ASSISTANT_NOTIFICATION_LIMITS.BODY_MAX),
|
||||
url: z.string().min(1).max(ASSISTANT_NOTIFICATION_LIMITS.URL_MAX).optional(),
|
||||
tag: z.string().max(ASSISTANT_NOTIFICATION_LIMITS.TAG_MAX).optional(),
|
||||
priority: AssistantNotificationPrioritySchema.default('normal'),
|
||||
})
|
||||
|
||||
|
||||
Reference in new issue
Block a user