Files
Bohdan Triapitsyn e908db637b 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.
2026-07-24 21:54:28 +03:00

196 lines
8.4 KiB
JavaScript

import { TunnelCliError, EXIT_CODE } from './cli-errors.js';
import { resolveTargetPort } from './cli-api-target.js';
import { parseGoalTokenBudget } from './cli-goal.js';
import { requestControlAction } from './cli-control.js';
import {
intro as clackIntro,
outro as clackOutro,
isJsonMode,
isQuietMode,
printJson,
logStatus,
} from '../cli-output.js';
const asNonEmptyString = (value) => {
if (typeof value !== 'string') return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
};
const assertRequired = (value, flagName) => {
const normalized = asNonEmptyString(value);
if (!normalized) {
throw new TunnelCliError(`Missing required ${flagName}.`, EXIT_CODE.USAGE_ERROR);
}
return normalized;
};
const formatGoal = (execution) => {
if (execution?.goalEnabled !== true) return 'goal:no';
return Number.isFinite(execution.goalTokenBudget)
? `goal:yes budget:${execution.goalTokenBudget}`
: 'goal:yes';
};
const formatSchedule = (schedule) => {
if (!schedule || typeof schedule !== 'object') return 'unknown';
if (schedule.kind === 'daily') return `daily ${Array.isArray(schedule.times) ? schedule.times.join(',') : ''}`.trim();
if (schedule.kind === 'weekly') return `weekly days:${Array.isArray(schedule.weekdays) ? schedule.weekdays.join(',') : ''} time:${Array.isArray(schedule.times) ? schedule.times.join(',') : ''}`;
if (schedule.kind === 'once') return `once ${schedule.date || ''} ${schedule.time || ''}`.trim();
if (schedule.kind === 'cron') return `cron ${schedule.cron || ''}`.trim();
return schedule.kind || 'unknown';
};
const outputTasks = (options, tasks) => {
const normalizedTasks = Array.isArray(tasks) ? tasks : [];
if (isJsonMode(options)) {
printJson({ tasks: normalizedTasks });
return;
}
if (isQuietMode(options)) {
for (const task of normalizedTasks) {
process.stdout.write(`${task.id} enabled:${task.enabled === false ? 'no' : 'yes'} ${formatGoal(task.execution)} status:${task.state?.lastStatus || 'idle'} ${formatSchedule(task.schedule)} ${task.name || ''}\n`);
}
return;
}
clackIntro('Scheduled Tasks');
if (normalizedTasks.length === 0) {
logStatus('info', 'No scheduled tasks found');
clackOutro('0 tasks');
return;
}
for (const task of normalizedTasks) {
const status = task.enabled === false ? 'warning' : 'success';
const detail = `id: ${task.id}; ${formatGoal(task.execution)}; status: ${task.state?.lastStatus || 'idle'}; ${formatSchedule(task.schedule)}`;
logStatus(status, task.name || task.id, detail);
}
clackOutro(`${normalizedTasks.length} task(s)`);
};
async function scheduleCommand(options = {}, action = 'help') {
if (action === 'help') {
process.stdout.write(`OpenChamber Schedule Commands\n\nUSAGE:\n openchamber schedule status [OPTIONS]\n openchamber schedule list (--project <projectId> | --dir <path>) [OPTIONS]\n openchamber schedule create (--project <projectId> | --dir <path>) --name <name> --prompt <prompt> --model <provider/model> (--daily <HH:mm> | --weekly <0,1,2> --time <HH:mm> | --once <YYYY-MM-DD> --time <HH:mm> | --cron <expr>) [OPTIONS]\n openchamber schedule run (--project <projectId> | --dir <path>) --task <taskId> [OPTIONS]\n openchamber schedule delete (--project <projectId> | --dir <path>) --task <taskId> [OPTIONS]\n openchamber schedule enable (--project <projectId> | --dir <path>) --task <taskId> [OPTIONS]\n openchamber schedule disable (--project <projectId> | --dir <path>) --task <taskId> [OPTIONS]\n\nOPTIONS:\n --project <projectId> Project id from openchamber projects\n --dir <path> Resolve project by directory\n -p, --port <port> OpenChamber server port\n --timezone <zone> IANA timezone for created tasks\n --agent <id> Agent to use when running task\n --variant <id> Model variant to use when running task\n --goal Continue the scheduled session toward a goal\n --goal-token-budget <n> Goal token budget (1000-100000000; requires --goal)\n --disabled Create task disabled\n --json Output machine-readable JSON\n -q, --quiet Print concise output\n`);
return;
}
const port = await resolveTargetPort(options);
const target = {
...(asNonEmptyString(options.project) ? { projectId: options.project.trim() } : {}),
...(asNonEmptyString(options.directory) ? { directory: options.directory.trim() } : {}),
};
if (action === 'status') {
const body = await requestControlAction(port, 'schedule.status', {}, options);
if (isJsonMode(options)) {
printJson(body || {});
return;
}
if (isQuietMode(options)) {
process.stdout.write(`enabled:${body?.enabledScheduledTasksCount ?? 0} running:${body?.runningScheduledTasksCount ?? 0}\n`);
return;
}
clackIntro('Scheduled Task Status');
logStatus(body?.hasEnabledScheduledTasks ? 'success' : 'info', `enabled: ${body?.enabledScheduledTasksCount ?? 0}`);
logStatus(body?.hasRunningScheduledTasks ? 'success' : 'info', `running: ${body?.runningScheduledTasksCount ?? 0}`);
clackOutro('status loaded');
return;
}
if (action === 'list') {
const body = await requestControlAction(port, 'schedule.list', target, options);
outputTasks(options, body?.tasks);
return;
}
if (action === 'create') {
const goalTokenBudget = parseGoalTokenBudget(options);
const input = {
...target,
name: options.name,
prompt: options.prompt,
model: options.model,
daily: options.daily,
weekly: options.weekly,
once: options.once,
time: options.time,
cron: options.cron,
timezone: options.timezone,
agent: options.agent,
variant: options.variant,
goal: options.goal === true,
...(goalTokenBudget !== undefined ? { goalTokenBudget } : {}),
disabled: options.disabled === true,
};
const body = await requestControlAction(port, 'schedule.create', input, options);
if (isJsonMode(options)) {
printJson({ task: body?.task, created: body?.created === true });
return;
}
if (isQuietMode(options)) {
process.stdout.write(`${body?.task?.id || ''}\n`);
return;
}
clackIntro('Scheduled Task Created');
logStatus('success', body?.task?.name || options.name, `id: ${body?.task?.id || 'unknown'}; ${formatGoal(body?.task?.execution)}; ${formatSchedule(body?.task?.schedule)}`);
clackOutro('created');
return;
}
if (action === 'run') {
const taskID = assertRequired(options.task, '--task');
const body = await requestControlAction(port, 'schedule.run', { ...target, taskId: taskID }, options);
if (isJsonMode(options)) {
printJson({ task: body?.task, sessionId: body?.sessionId });
return;
}
if (isQuietMode(options)) {
process.stdout.write(`${body?.sessionId || ''}\n`);
return;
}
clackIntro('Scheduled Task Run');
logStatus('success', body?.task?.name || taskID, `session: ${body?.sessionId || 'unknown'}`);
clackOutro('started');
return;
}
if (action === 'delete') {
const taskID = assertRequired(options.task, '--task');
const body = await requestControlAction(port, 'schedule.delete', { ...target, taskId: taskID }, options);
if (isJsonMode(options)) {
printJson({ deleted: true, tasks: body?.tasks || [] });
return;
}
if (isQuietMode(options)) {
process.stdout.write(`deleted ${taskID}\n`);
return;
}
clackIntro('Scheduled Task Deleted');
logStatus('success', `deleted ${taskID}`);
clackOutro('deleted');
return;
}
if (action === 'enable' || action === 'disable') {
const taskID = assertRequired(options.task, '--task');
const enabled = action === 'enable';
const { task } = await requestControlAction(port, 'schedule.toggle', { ...target, taskId: taskID, disabled: !enabled }, options);
if (isJsonMode(options)) {
printJson({ task, enabled });
return;
}
if (isQuietMode(options)) {
process.stdout.write(`${taskID} enabled:${enabled ? 'yes' : 'no'}\n`);
return;
}
clackIntro(enabled ? 'Scheduled Task Enabled' : 'Scheduled Task Disabled');
logStatus('success', task?.name || taskID, `enabled: ${enabled ? 'yes' : 'no'}`);
clackOutro(enabled ? 'enabled' : 'disabled');
return;
}
throw new TunnelCliError(`Unknown schedule command '${action}'.`, EXIT_CODE.USAGE_ERROR);
}
export { scheduleCommand, formatGoal };