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:
Bohdan Triapitsyn
2026-07-24 21:54:28 +03:00
committed by GitHub
parent 484fe8bc18
commit e908db637b
85 changed files with 5375 additions and 298 deletions
@@ -66,8 +66,9 @@ before touching the filesystem). Rationale: metadata rides every
- UI display fetches content via the GET route
(`useGoalObjectiveContent`); in VS Code the route is unavailable, so the
strip degrades to the audit note (display-only fallback by design).
- Scheduled goal tasks write the file server-side directly via
`objectives.js`.
- Server-created goals write the file through `create.js`, which also owns
objective fitting, inline fallback, metadata creation, and the synthetic
first-turn reminder shared by scheduled tasks and CLI-created sessions.
## Flow
@@ -174,6 +175,24 @@ stamp `metadata.openchamber.goal` onto the fresh session (objective = the
expanded task prompt) and attach the goal-mode intro part to the prompt.
The loop here picks it up from session events like any other goal.
## CLI-created goals
`openchamber session create --prompt <text> --goal` uses the explicit
`POST /api/openchamber/sessions` orchestration route. The server creates the
session, fits and stores the expanded prompt as its objective, patches active
goal metadata, appends the synthetic goal reminder, and only then dispatches
the prompt. `--goal-token-budget` applies the same optional budget contract as
scheduled goals. Slash commands retain command dispatch semantics and cannot
carry the synthetic prompt part; the goal metadata is still installed before
the command runs.
`openchamber session send --goal` and `openchamber session fork --goal` use
the same server-owned prompt orchestration. Send installs a fresh goal on the
target session; fork first uses the official OpenCode fork operation (at the
optional message boundary), then installs the goal on the new session. Both
preserve the objective-file-before-metadata and metadata-before-dispatch
ordering used by create and scheduled goals.
## Limitations
- Web-server feature: VS Code (extension-only) renders goal state via
@@ -0,0 +1,112 @@
import { GOAL_OBJECTIVE_CHAR_LIMIT, writeObjective } from './objectives.js';
const TRIM_MARKER = '\n\n[… objective trimmed for the auditor — the full prompt was delivered in the chat message …]\n\n';
export const buildGoalIntroText = (tokenBudget) => {
const budgetLine = tokenBudget
? ` A token budget of ${tokenBudget} tokens applies to this goal.`
: '';
return '<system-reminder>\n'
+ 'Goal mode is active for this session. The user message above defines the goal objective. '
+ 'Work toward it across turns; whenever you stop before the objective is verifiably complete, the system will automatically prompt you to continue. '
+ 'Progress is evaluated independently after each turn, so end every turn with a clear, factual statement of what is done, what was verified, and what remains.'
+ budgetLine
+ '\n</system-reminder>';
};
const fitObjective = async ({ objective, directory, providerID, modelID, warn }) => {
if (objective.length <= GOAL_OBJECTIVE_CHAR_LIMIT) return objective;
let distilled = null;
try {
const { generateSmallModelText } = await import('../small-model/index.js');
const generated = await generateSmallModelText({
restrictToPreferredProvider: true,
prompt: objective,
system: [
'You distill a large task description into the COMPLETION CRITERIA a progress auditor will judge against.',
'Return ONLY the criteria text — no preamble, no headers, no markdown fences.',
'Capture: the end goals, what must exist and work when the task is fully done, and how each major part is verified. Omit implementation steps.',
'Preserve verbatim any file paths, commands, and identifiers that define the task.',
'Stay under 4000 characters.',
'Write in the same language as the task text.',
].join('\n'),
directory,
preferredProviderID: providerID,
preferredModelID: modelID,
});
distilled = typeof generated?.text === 'string' ? generated.text.trim() : null;
} catch (error) {
warn('goal objective distillation failed', error);
}
if (distilled) return distilled.slice(0, GOAL_OBJECTIVE_CHAR_LIMIT);
const half = Math.max(0, Math.floor((GOAL_OBJECTIVE_CHAR_LIMIT - TRIM_MARKER.length) / 2));
return `${objective.slice(0, half)}${TRIM_MARKER}${objective.slice(-half)}`;
};
export const createSessionGoal = async ({
baseUrl,
authHeaders,
sessionID,
directory,
objective,
tokenBudget = null,
providerID,
modelID,
onWarning,
}) => {
const warn = (message, error) => {
if (typeof onWarning === 'function') {
onWarning(message, error);
return;
}
console.warn(`[session-goal] ${message}:`, error?.message || error);
};
const objectiveText = await fitObjective({
objective: String(objective ?? '').trim(),
directory,
providerID,
modelID,
warn,
});
if (!objectiveText) throw new Error('goal objective is required');
let objectiveFile = false;
try {
await writeObjective(sessionID, objectiveText);
objectiveFile = true;
} catch (error) {
warn('goal objective file write failed, falling back to inline', error);
}
const now = Date.now();
const goal = {
id: `${now.toString(36)}${Math.random().toString(36).slice(2, 8)}`,
objective: objectiveFile ? '' : objectiveText.slice(0, GOAL_OBJECTIVE_CHAR_LIMIT),
objectiveFile,
status: 'active',
tokenBudget: tokenBudget || null,
tokensUsed: 0,
turnsUsed: 0,
blockedStreak: 0,
note: '',
statusReason: '',
lastAccountedMessageID: '',
createdAt: now,
updatedAt: now,
};
const url = new URL(`${baseUrl}/session/${encodeURIComponent(sessionID)}`);
url.searchParams.set('directory', directory);
const response = await fetch(url.toString(), {
method: 'PATCH',
headers: {
...authHeaders,
'content-type': 'application/json',
accept: 'application/json',
},
body: JSON.stringify({ metadata: { openchamber: { goal } } }),
});
if (!response.ok) throw new Error(`goal metadata patch failed (${response.status})`);
return goal;
};
@@ -0,0 +1,80 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const writeObjectiveMock = vi.fn(async () => undefined);
const generateSmallModelTextMock = vi.fn(async () => ({ text: '' }));
vi.mock('./objectives.js', () => ({
GOAL_OBJECTIVE_CHAR_LIMIT: 5_000,
writeObjective: writeObjectiveMock,
}));
vi.mock('../small-model/index.js', () => ({
generateSmallModelText: generateSmallModelTextMock,
}));
const { buildGoalIntroText, createSessionGoal } = await import('./create.js');
describe('session goal creation', () => {
beforeEach(() => {
writeObjectiveMock.mockReset().mockResolvedValue(undefined);
generateSmallModelTextMock.mockReset().mockResolvedValue({ text: '' });
});
it('writes the objective before patching active goal metadata', async () => {
const fetchMock = vi.fn(async () => ({ ok: true }));
const originalFetch = globalThis.fetch;
globalThis.fetch = fetchMock;
try {
const goal = await createSessionGoal({
baseUrl: 'http://opencode.test',
authHeaders: { Authorization: 'Bearer test' },
sessionID: 'ses_123',
directory: '/repo/app',
objective: 'Finish and verify the migration',
tokenBudget: 200_000,
providerID: 'openai',
modelID: 'gpt-5.5',
});
expect(writeObjectiveMock).toHaveBeenCalledWith('ses_123', 'Finish and verify the migration');
expect(writeObjectiveMock.mock.invocationCallOrder[0]).toBeLessThan(fetchMock.mock.invocationCallOrder[0]);
expect(goal).toMatchObject({ objective: '', objectiveFile: true, status: 'active', tokenBudget: 200_000 });
expect(fetchMock).toHaveBeenCalledWith(
'http://opencode.test/session/ses_123?directory=%2Frepo%2Fapp',
expect.objectContaining({ method: 'PATCH' }),
);
} finally {
globalThis.fetch = originalFetch;
}
});
it('falls back to inline metadata when objective storage fails', async () => {
writeObjectiveMock.mockRejectedValueOnce(new Error('disk unavailable'));
const fetchMock = vi.fn(async () => ({ ok: true }));
const originalFetch = globalThis.fetch;
globalThis.fetch = fetchMock;
try {
await createSessionGoal({
baseUrl: 'http://opencode.test',
authHeaders: {},
sessionID: 'ses_123',
directory: '/repo/app',
objective: 'Finish the migration',
onWarning: vi.fn(),
});
const payload = JSON.parse(fetchMock.mock.calls[0][1].body);
expect(payload.metadata.openchamber.goal).toMatchObject({
objective: 'Finish the migration',
objectiveFile: false,
});
} finally {
globalThis.fetch = originalFetch;
}
});
it('builds the same goal intro with an optional budget', () => {
expect(buildGoalIntroText(null)).toContain('Goal mode is active for this session.');
expect(buildGoalIntroText(200_000)).toContain('A token budget of 200000 tokens applies to this goal.');
});
});