feat: agent and CLI control plane for sessions, worktrees, and scheduled tasks (#2408)
Add a shared OpenChamber control service with two thin adapters — a native `openchamber` tool injected into managed OpenCode, and new CLI commands — so users can manage parallel sessions, worktrees, and scheduled tasks conversationally through agents or from the terminal. Control plane: - New openchamber-control service owning a fixed action contract: projects.list, models.list, session list/create/send/fork/status/messages, and schedule list/create/run/delete/toggle. Session and worktree deletion and project registration are deliberately not exposed. - New openchamber-sessions module owning create/worktree/prompt orchestration, Goal Mode dispatch, wait semantics (initial idle never counts as completion; timeout and cancellation are failures), and explicit partial-failure results. - Scheduled-task logic extracted into a service shared by routes, CLI, and the agent tool. Agent tool: - Managed OpenCode gets a materialized plugin registering one typed tool with a loopback-only callback, per-child ephemeral bearer (timing-safe, never persisted or logged), and abort propagation into the service. - The ~1.5k-token schema applies progressive disclosure: short descriptions, server-side validation returning actionable usage errors, and intent guardrails — created sessions/tasks are user-facing work (not age self-delegation); worktree/goal/agent/variant/wait are omit-by-default; dispatches produce no completion notification, and later result r to session.messages, which now returns the authoritative sessionStatus. - session.create without a user-named model picks from favorites/re send/fork omit the selection and the service reuses the target session's last user-message model, agent, and variant before falling back t - An "Agent control tool" setting (default on, Save + Reload to apply) disables plugin injection entirely. CLI: - New `openchamber session`, `schedule`, `projects`, and `models` commands with automatic instance targeting, --wait/--timeout/--last-assist worktree flags, and Goal Mode, preserving interactive, non-TTY, --quiet, and --json contracts. The control HTTP timeout derives from the w instead of the 4-second default. UI: - New built-in "Schedule a Task" starter (/schedule-task) running a dialogue that defines a task and offers to create it via the tool after explicit confirmation; Craft a Goal and Feature Planning gain the handoff offer, and guided starters reserve the question tool for concrete option choices. Localized in all 10 locales, migrated into custom starter lists, hidden on VS Code. - Sidebar shows CLI/agent-created sessions live via the control eve - openchamber tool calls render with per-action titles and metadata.
This commit is contained in:
committed by
GitHub
parent
484fe8bc18
commit
e908db637b
@@ -28,6 +28,7 @@ This module provides OpenCode server integration utilities for the web server ru
|
||||
- `packages/web/server/lib/opencode/opencode-resolution-runtime.js`: OpenCode binary resolution snapshot runtime for settings routes and diagnostics.
|
||||
- `packages/web/server/lib/opencode/tunnel-wiring-runtime.js`: tunnel service/routes composition runtime and active-port wiring for main server startup.
|
||||
- `packages/web/server/lib/opencode/startup-pipeline-runtime.js`: server startup tail orchestration runtime for terminal/proxy/static/start-listen flow.
|
||||
- `packages/web/server/lib/agent-tool/runtime.js`: managed OpenCode custom-tool materialization, environment injection, loopback authentication, and fixed CLI action dispatch.
|
||||
- `packages/web/server/lib/opencode/server-utils-runtime.js`: shared server runtime utilities for OpenCode proxy wiring, OpenCode port/readiness helpers, and snapshot fetchers.
|
||||
- `packages/web/server/lib/opencode/openchamber-routes.js`: OpenChamber update and models metadata route registration.
|
||||
- `packages/web/server/lib/opencode/pwa-manifest-routes.js`: PWA manifest route registration with recent-session shortcut resolution and short-lived caching.
|
||||
@@ -113,6 +114,11 @@ The runtime maintains active-session count incrementally from idempotent activit
|
||||
- `waitForPortRelease(port, timeoutMs, hostname?)`
|
||||
- `killProcessOnPort(port)`
|
||||
|
||||
Managed OpenCode launch also merges the environment returned by the agent-tool
|
||||
runtime. PATH and `OPENCODE_SERVER_PASSWORD` remain lifecycle-owned and cannot
|
||||
be replaced by injected values. External OpenCode processes receive no
|
||||
OpenChamber tool injection.
|
||||
|
||||
## Public exports (env-runtime.js)
|
||||
- `createOpenCodeEnvRuntime(dependencies)`: creates runtime that owns OpenCode CLI environment and binary discovery state.
|
||||
- OpenCode CLI resolution order is persisted settings, environment overrides, bundled Desktop CLI when available, PATH, known install locations, then platform shell discovery.
|
||||
@@ -311,6 +317,10 @@ The runtime maintains active-session count incrementally from idempotent activit
|
||||
- Returned API:
|
||||
- `run(options)`
|
||||
|
||||
The pipeline binds the OpenChamber listener and publishes its active port
|
||||
before starting managed OpenCode. The managed custom tool therefore receives
|
||||
an authoritative loopback callback URL even when OpenChamber binds port `0`.
|
||||
|
||||
## Public exports (openchamber-routes.js)
|
||||
- `registerOpenChamberRoutes(app, dependencies)`: registers OpenChamber endpoints:
|
||||
- `GET /api/openchamber/update-check`
|
||||
|
||||
@@ -7,6 +7,7 @@ export const createBootstrapRuntime = (dependencies) => {
|
||||
registerTtsRoutes,
|
||||
registerNotificationRoutes,
|
||||
registerOpenChamberRoutes,
|
||||
registerAgentToolRoutes = () => {},
|
||||
express,
|
||||
} = dependencies;
|
||||
|
||||
@@ -59,6 +60,7 @@ export const createBootstrapRuntime = (dependencies) => {
|
||||
fetchFreeZenModels,
|
||||
getCachedZenModels,
|
||||
setAutoAcceptSession,
|
||||
agentToolRuntime,
|
||||
} = options;
|
||||
|
||||
const uiAuthController = createUiAuth({
|
||||
@@ -85,6 +87,8 @@ export const createBootstrapRuntime = (dependencies) => {
|
||||
|
||||
registerCommonRequestMiddleware(app, { express, verboseRequestLogs });
|
||||
|
||||
registerAgentToolRoutes(app, { express, agentToolRuntime });
|
||||
|
||||
registerAuthAndAccessRoutes(app, {
|
||||
express,
|
||||
tunnelAuthController,
|
||||
|
||||
@@ -11,6 +11,8 @@ import { registerConfigEntityRoutes } from './config-entity-routes.js';
|
||||
import { registerSettingsUtilityRoutes } from './core-routes.js';
|
||||
import { registerProjectIconRoutes } from './project-icon-routes.js';
|
||||
import { registerScheduledTaskRoutes } from '../scheduled-tasks/routes.js';
|
||||
import { registerOpenChamberSessionRoutes } from '../openchamber-sessions/routes.js';
|
||||
import { registerOpenChamberControlRoutes } from '../openchamber-control/routes.js';
|
||||
import { registerSkillRoutes } from './skill-routes.js';
|
||||
import { registerPluginRoutes } from './plugin-routes.js';
|
||||
import { getNpmInfo, clearCache as clearNpmCache } from './npm-registry.js';
|
||||
@@ -97,8 +99,13 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
||||
buildAugmentedPath,
|
||||
projectConfigRuntime,
|
||||
scheduledTasksRuntime,
|
||||
scheduledTaskService,
|
||||
openChamberSessionService,
|
||||
openChamberControlService,
|
||||
waitForOpenCodeReady,
|
||||
getOpenChamberEventClients,
|
||||
writeSseEvent,
|
||||
emitSessionCreatedEvent,
|
||||
permissionAutoAcceptRuntime,
|
||||
} = routeDependencies;
|
||||
|
||||
@@ -146,10 +153,24 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
||||
sanitizeProjects,
|
||||
projectConfigRuntime,
|
||||
scheduledTasksRuntime,
|
||||
scheduledTaskService,
|
||||
getOpenChamberEventClients,
|
||||
writeSseEvent,
|
||||
});
|
||||
|
||||
registerOpenChamberSessionRoutes(app, {
|
||||
readSettingsFromDiskMigrated,
|
||||
sanitizeProjects,
|
||||
validateDirectoryPath,
|
||||
buildOpenCodeUrl,
|
||||
getOpenCodeAuthHeaders,
|
||||
waitForOpenCodeReady,
|
||||
emitSessionCreatedEvent,
|
||||
sessionService: openChamberSessionService,
|
||||
});
|
||||
|
||||
registerOpenChamberControlRoutes(app, { controlService: openChamberControlService });
|
||||
|
||||
registerConfigEntityRoutes(app, {
|
||||
resolveProjectDirectory,
|
||||
resolveOptionalProjectDirectory,
|
||||
|
||||
@@ -38,6 +38,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
||||
buildAugmentedPath,
|
||||
buildManagedOpenCodePath,
|
||||
getManagedOpenCodeShellEnvSnapshot,
|
||||
getManagedOpenCodeEnv = async () => ({}),
|
||||
getActiveSessionCount = () => 0,
|
||||
} = deps;
|
||||
|
||||
@@ -474,14 +475,16 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
||||
await applyOpencodeBinaryFromSettings({ strict: true });
|
||||
ensureOpencodeCliEnv();
|
||||
const openCodePassword = await ensureLocalOpenCodeServerPassword({ rotateManaged: true });
|
||||
const envPath = typeof buildManagedOpenCodePath === 'function'
|
||||
? buildManagedOpenCodePath()
|
||||
: typeof buildAugmentedPath === 'function'
|
||||
? buildAugmentedPath()
|
||||
: process.env.PATH;
|
||||
let envPath = process.env.PATH;
|
||||
if (typeof buildManagedOpenCodePath === 'function') {
|
||||
envPath = buildManagedOpenCodePath();
|
||||
} else if (typeof buildAugmentedPath === 'function') {
|
||||
envPath = buildAugmentedPath();
|
||||
}
|
||||
const shellEnv = typeof getManagedOpenCodeShellEnvSnapshot === 'function'
|
||||
? getManagedOpenCodeShellEnvSnapshot() || {}
|
||||
: {};
|
||||
const managedOpenCodeEnv = await getManagedOpenCodeEnv();
|
||||
|
||||
try {
|
||||
const serverInstance = await createManagedOpenCodeServerProcess({
|
||||
@@ -493,6 +496,7 @@ export const createOpenCodeLifecycleRuntime = (deps) => {
|
||||
env: {
|
||||
...shellEnv,
|
||||
...process.env,
|
||||
...managedOpenCodeEnv,
|
||||
PATH: envPath,
|
||||
OPENCODE_SERVER_PASSWORD: openCodePassword,
|
||||
},
|
||||
|
||||
@@ -128,6 +128,34 @@ describe('OpenCode lifecycle', () => {
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('adds managed OpenChamber tool environment without allowing it to replace launch invariants', async () => {
|
||||
const child = createMockChild();
|
||||
spawnMock.mockImplementationOnce(() => {
|
||||
queueMicrotask(() => {
|
||||
child.stdout.emit('data', 'opencode server listening on http://127.0.0.1:45678\n');
|
||||
});
|
||||
return child;
|
||||
});
|
||||
const getManagedOpenCodeEnv = vi.fn(async () => ({
|
||||
OPENCODE_CONFIG_CONTENT: '{"plugin":["file:///tool.js"]}',
|
||||
OPENCHAMBER_AGENT_TOOL_TOKEN: 'ephemeral',
|
||||
PATH: '/untrusted/path',
|
||||
OPENCODE_SERVER_PASSWORD: 'untrusted-password',
|
||||
}));
|
||||
|
||||
const runtime = createRuntime({ getManagedOpenCodeEnv });
|
||||
const server = await runtime.startOpenCode();
|
||||
const [, , options] = spawnMock.mock.calls[0];
|
||||
|
||||
expect(getManagedOpenCodeEnv).toHaveBeenCalledOnce();
|
||||
expect(options.env.OPENCODE_CONFIG_CONTENT).toBe('{"plugin":["file:///tool.js"]}');
|
||||
expect(options.env.OPENCHAMBER_AGENT_TOOL_TOKEN).toBe('ephemeral');
|
||||
expect(options.env.PATH).toBe('/home/user/.bun/bin:/usr/local/bin:/usr/bin');
|
||||
expect(options.env.OPENCODE_SERVER_PASSWORD).toBe('password');
|
||||
|
||||
await server.close();
|
||||
});
|
||||
|
||||
it('falls back to buildAugmentedPath when buildManagedOpenCodePath is not provided', async () => {
|
||||
delete process.env.OPENCODE_BINARY;
|
||||
const child = createMockChild();
|
||||
|
||||
@@ -248,6 +248,12 @@ export const createSettingsHelpers = (dependencies) => {
|
||||
}
|
||||
result.draftStarters = starters;
|
||||
}
|
||||
if (typeof candidate.draftStartersCraftGoalAdded === 'boolean') {
|
||||
result.draftStartersCraftGoalAdded = candidate.draftStartersCraftGoalAdded;
|
||||
}
|
||||
if (typeof candidate.draftStartersScheduleTaskAdded === 'boolean') {
|
||||
result.draftStartersScheduleTaskAdded = candidate.draftStartersScheduleTaskAdded;
|
||||
}
|
||||
|
||||
|
||||
if (typeof candidate.uiFont === 'string' && candidate.uiFont.length > 0) {
|
||||
@@ -479,6 +485,9 @@ export const createSettingsHelpers = (dependencies) => {
|
||||
if (typeof candidate.showOpenCodeUpdateNotifications === 'boolean') {
|
||||
result.showOpenCodeUpdateNotifications = candidate.showOpenCodeUpdateNotifications;
|
||||
}
|
||||
if (typeof candidate.agentControlToolEnabled === 'boolean') {
|
||||
result.agentControlToolEnabled = candidate.agentControlToolEnabled;
|
||||
}
|
||||
if (typeof candidate.openCodeUpdateToastDismissedVersion === 'string') {
|
||||
const version = candidate.openCodeUpdateToastDismissedVersion.trim();
|
||||
result.openCodeUpdateToastDismissedVersion = version.slice(0, VERSION_STRING_MAX_LENGTH);
|
||||
|
||||
@@ -98,8 +98,6 @@ export const createStartupPipelineRuntime = (dependencies) => {
|
||||
});
|
||||
|
||||
setupProxy(app);
|
||||
scheduleOpenCodeApiDetection();
|
||||
void bootstrapOpenCodeAtStartup();
|
||||
|
||||
if (apiOnly) {
|
||||
staticRoutesRuntime.registerApiOnlyFallbackRoutes(app);
|
||||
@@ -132,6 +130,8 @@ export const createStartupPipelineRuntime = (dependencies) => {
|
||||
onTunnelReady,
|
||||
});
|
||||
tunnelRuntimeContext.setActivePort(startupResult.activePort);
|
||||
scheduleOpenCodeApiDetection();
|
||||
void bootstrapOpenCodeAtStartup();
|
||||
|
||||
serverStartupRuntime.attachProcessHandlers({ attachSignals });
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { createStartupPipelineRuntime } from './startup-pipeline-runtime.js';
|
||||
|
||||
describe('startup pipeline runtime', () => {
|
||||
it('publishes the listening port before bootstrapping managed OpenCode', async () => {
|
||||
const order = [];
|
||||
const runtime = createStartupPipelineRuntime({
|
||||
createTerminalRuntime: () => ({}),
|
||||
createDictationRuntime: () => ({}),
|
||||
createMessageStreamWsRuntime: () => ({}),
|
||||
createServerStartupRuntime: () => ({
|
||||
resolveBindHost: () => '127.0.0.1',
|
||||
startListeningAndMaybeTunnel: async () => {
|
||||
order.push('listen');
|
||||
return { activePort: 3901 };
|
||||
},
|
||||
attachProcessHandlers: vi.fn(),
|
||||
}),
|
||||
});
|
||||
|
||||
await runtime.run({
|
||||
app: {},
|
||||
setupProxy: vi.fn(),
|
||||
staticRoutesRuntime: { registerStaticRoutes: vi.fn() },
|
||||
apiOnly: false,
|
||||
tunnelRuntimeContext: {
|
||||
setActivePort: (port) => order.push(`port:${port}`),
|
||||
},
|
||||
scheduleOpenCodeApiDetection: () => order.push('detect'),
|
||||
bootstrapOpenCodeAtStartup: () => order.push('bootstrap'),
|
||||
process: {},
|
||||
crypto: {},
|
||||
server: {},
|
||||
attachSignals: false,
|
||||
});
|
||||
|
||||
expect(order).toEqual(['listen', 'port:3901', 'detect', 'bootstrap']);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user