mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
refactor(goals): replace the Manager session-goal API with OpenCode built-in /goal
This commit is contained in:
1 parent
c8647c1eec
commit
cbe92c92ad
84 files changed
+2099
-6321
No files matched your search
@@ -1,171 +0,0 @@
|
||||
import {
|
||||
SESSION_GOAL_POLL_INTERVAL_MS,
|
||||
isOpenSessionGoal,
|
||||
isTerminalSessionGoal,
|
||||
type SessionGoal,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
const BACKGROUND_POLL_INTERVAL_MS = 15000
|
||||
const MAX_ERROR_BACKOFF_MS = 30000
|
||||
const REQUEST_TIMEOUT_MS = 10000
|
||||
|
||||
export type GoalStoreDeps = {
|
||||
load: (sessionID: string, signal: AbortSignal) => Promise<SessionGoal | null>
|
||||
onOutcome: (goal: SessionGoal) => void
|
||||
pollIntervalMs?: number
|
||||
}
|
||||
|
||||
export type GoalStore = {
|
||||
watch(sessionID: string, listener: (goal: SessionGoal | null) => void): () => void
|
||||
set(goal: SessionGoal): void
|
||||
}
|
||||
|
||||
interface GoalEntry {
|
||||
readonly sessionID: string
|
||||
goal: SessionGoal | null
|
||||
listeners: Set<(goal: SessionGoal | null) => void>
|
||||
timer: ReturnType<typeof setTimeout> | null
|
||||
abort: AbortController | null
|
||||
loading: boolean
|
||||
version: number
|
||||
errorBackoffMs: number
|
||||
outcomeGoalId: number | null
|
||||
}
|
||||
|
||||
export function createGoalStore(deps: GoalStoreDeps): GoalStore {
|
||||
const pollIntervalMs = deps.pollIntervalMs ?? SESSION_GOAL_POLL_INTERVAL_MS
|
||||
const entries = new Map<string, GoalEntry>()
|
||||
|
||||
function entryFor(sessionID: string): GoalEntry {
|
||||
const existing = entries.get(sessionID)
|
||||
if (existing) return existing
|
||||
const entry: GoalEntry = {
|
||||
sessionID,
|
||||
goal: null,
|
||||
listeners: new Set(),
|
||||
timer: null,
|
||||
abort: null,
|
||||
loading: false,
|
||||
version: 0,
|
||||
errorBackoffMs: 0,
|
||||
outcomeGoalId: null,
|
||||
}
|
||||
entries.set(sessionID, entry)
|
||||
return entry
|
||||
}
|
||||
|
||||
function clearTimer(entry: GoalEntry): void {
|
||||
if (entry.timer === null) return
|
||||
clearTimeout(entry.timer)
|
||||
entry.timer = null
|
||||
}
|
||||
|
||||
function isCurrent(entry: GoalEntry): boolean {
|
||||
return entries.get(entry.sessionID) === entry
|
||||
}
|
||||
|
||||
function hasListeners(entry: GoalEntry): boolean {
|
||||
return entry.listeners.size > 0
|
||||
}
|
||||
|
||||
function baseDelay(entry: GoalEntry): number {
|
||||
return hasListeners(entry) ? pollIntervalMs : BACKGROUND_POLL_INTERVAL_MS
|
||||
}
|
||||
|
||||
function wantsFollowing(entry: GoalEntry): boolean {
|
||||
return isCurrent(entry) && (hasListeners(entry) || isOpenSessionGoal(entry.goal))
|
||||
}
|
||||
|
||||
function schedule(entry: GoalEntry): void {
|
||||
clearTimer(entry)
|
||||
if (!wantsFollowing(entry)) return
|
||||
const delay = entry.errorBackoffMs > 0 ? Math.min(entry.errorBackoffMs, MAX_ERROR_BACKOFF_MS) : baseDelay(entry)
|
||||
entry.timer = setTimeout(() => {
|
||||
entry.timer = null
|
||||
void loadInto(entry)
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function drop(entry: GoalEntry): void {
|
||||
clearTimer(entry)
|
||||
entry.abort?.abort()
|
||||
entry.abort = null
|
||||
entries.delete(entry.sessionID)
|
||||
}
|
||||
|
||||
function applyGoal(entry: GoalEntry, goal: SessionGoal | null): void {
|
||||
const previous = entry.goal
|
||||
entry.goal = goal
|
||||
for (const listener of entry.listeners) listener(goal)
|
||||
if (goal !== null && entry.outcomeGoalId !== goal.id && isOpenSessionGoal(previous) && isTerminalSessionGoal(goal)) {
|
||||
entry.outcomeGoalId = goal.id
|
||||
deps.onOutcome(goal)
|
||||
}
|
||||
if (isOpenSessionGoal(goal)) {
|
||||
schedule(entry)
|
||||
return
|
||||
}
|
||||
clearTimer(entry)
|
||||
if (!hasListeners(entry)) drop(entry)
|
||||
}
|
||||
|
||||
function fail(entry: GoalEntry): void {
|
||||
const current = entry.errorBackoffMs === 0 ? baseDelay(entry) : entry.errorBackoffMs
|
||||
entry.errorBackoffMs = Math.min(current * 2, MAX_ERROR_BACKOFF_MS)
|
||||
schedule(entry)
|
||||
}
|
||||
|
||||
async function loadInto(entry: GoalEntry): Promise<void> {
|
||||
if (entry.loading || !wantsFollowing(entry)) return
|
||||
entry.loading = true
|
||||
const version = ++entry.version
|
||||
const controller = new AbortController()
|
||||
entry.abort = controller
|
||||
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(REQUEST_TIMEOUT_MS)])
|
||||
|
||||
let goal: SessionGoal | null
|
||||
try {
|
||||
goal = await deps.load(entry.sessionID, signal)
|
||||
} catch {
|
||||
entry.loading = false
|
||||
entry.abort = null
|
||||
if (!isCurrent(entry)) return
|
||||
fail(entry)
|
||||
return
|
||||
}
|
||||
|
||||
entry.loading = false
|
||||
entry.abort = null
|
||||
if (!isCurrent(entry)) return
|
||||
if (version !== entry.version) {
|
||||
schedule(entry)
|
||||
return
|
||||
}
|
||||
entry.errorBackoffMs = 0
|
||||
applyGoal(entry, goal)
|
||||
}
|
||||
|
||||
return {
|
||||
watch(sessionID, listener) {
|
||||
const entry = entryFor(sessionID)
|
||||
entry.listeners.add(listener)
|
||||
if (entry.goal) listener(entry.goal)
|
||||
void loadInto(entry)
|
||||
return () => {
|
||||
if (!entry.listeners.delete(listener)) return
|
||||
if (hasListeners(entry)) return
|
||||
if (isOpenSessionGoal(entry.goal)) {
|
||||
schedule(entry)
|
||||
return
|
||||
}
|
||||
drop(entry)
|
||||
}
|
||||
},
|
||||
set(goal) {
|
||||
const entry = entries.get(goal.sessionId)
|
||||
if (!entry) return
|
||||
entry.version++
|
||||
applyGoal(entry, goal)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -4,14 +4,11 @@ import {
|
||||
MirrorCheckoutsResponseSchema,
|
||||
MirrorWorktreeCreateResponseSchema,
|
||||
MultiRunSchema,
|
||||
SessionGoalSchema,
|
||||
type FuseMultiRunRequest,
|
||||
type LaunchMultiRunRequest,
|
||||
type MirrorCheckoutsResponse,
|
||||
type MirrorWorktreeCreateResponse,
|
||||
type MultiRun,
|
||||
type SessionGoal,
|
||||
type StartSessionGoalRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
|
||||
export interface MirrorBeginOpts {
|
||||
@@ -78,7 +75,7 @@ function createByteCounter(onProgress: (bytesSent: number) => void): TransformSt
|
||||
|
||||
export const MANAGER_FEATURE_MISSING = 'MANAGER_FEATURE_MISSING'
|
||||
|
||||
const DEFAULT_FEATURE_NAME = 'ocm goals and multi-runs'
|
||||
const DEFAULT_FEATURE_NAME = 'ocm multi-runs'
|
||||
const MOVE_FEATURE_NAME = '/ocm-move worktrees'
|
||||
|
||||
function directoryQuery(directory: string | undefined): string {
|
||||
@@ -160,7 +157,7 @@ export class ManagerApi {
|
||||
})
|
||||
if (!res.ok) {
|
||||
const featureLabel = feature === true ? (featureName ?? DEFAULT_FEATURE_NAME) : null
|
||||
throw await this.handleErrorResponse(res, operation, featureLabel, requestInit.signal ?? undefined)
|
||||
throw await this.handleErrorResponse(res, operation, featureLabel)
|
||||
}
|
||||
return parse(await res.json())
|
||||
}
|
||||
@@ -169,11 +166,10 @@ export class ManagerApi {
|
||||
res: Response,
|
||||
operation: string,
|
||||
featureName: string | null,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ManagerApiError> {
|
||||
const error = await formatErrorResponse(res, operation)
|
||||
if (featureName !== null && error.status === 401) {
|
||||
return this.probeFeatureSupport(operation, featureName, error, signal)
|
||||
return this.probeFeatureSupport(operation, featureName, error)
|
||||
}
|
||||
return error
|
||||
}
|
||||
@@ -182,10 +178,9 @@ export class ManagerApi {
|
||||
operation: string,
|
||||
featureName: string,
|
||||
fallback: ManagerApiError,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ManagerApiError> {
|
||||
try {
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/opencode-workspaces`, { headers: this.headers(), signal })
|
||||
const res = await fetch(`${this.baseUrl}/api/internal/opencode-workspaces`, { headers: this.headers() })
|
||||
if (res.ok) {
|
||||
return new ManagerApiError(
|
||||
`${operation} failed: this OpenCode Manager is too old for ${featureName}; upgrade the Manager.`,
|
||||
@@ -382,45 +377,6 @@ export class ManagerApi {
|
||||
return (await res.json()) as MirrorPatchSnapshot
|
||||
}
|
||||
|
||||
getLatestSessionGoal(sessionId: string, signal?: AbortSignal): Promise<SessionGoal | null> {
|
||||
return this.requestJson(
|
||||
`/api/internal/session-goals?sessionId=${encodeURIComponent(sessionId)}`,
|
||||
'read session goal',
|
||||
(body) => SessionGoalSchema.nullable().parse((body as { goal: unknown }).goal),
|
||||
{ signal, feature: true },
|
||||
)
|
||||
}
|
||||
|
||||
startSessionGoal(input: StartSessionGoalRequest): Promise<SessionGoal> {
|
||||
return this.requestJson(
|
||||
'/api/internal/session-goals',
|
||||
'start session goal',
|
||||
(body) => SessionGoalSchema.parse((body as { goal: unknown }).goal),
|
||||
{ method: 'POST', body: JSON.stringify(input), feature: true },
|
||||
)
|
||||
}
|
||||
|
||||
private runSessionGoalAction(id: number, action: 'pause' | 'resume' | 'cancel'): Promise<SessionGoal> {
|
||||
return this.requestJson(
|
||||
`/api/internal/session-goals/${encodeURIComponent(id)}/${action}`,
|
||||
`${action} session goal`,
|
||||
(body) => SessionGoalSchema.parse((body as { goal: unknown }).goal),
|
||||
{ method: 'POST', feature: true },
|
||||
)
|
||||
}
|
||||
|
||||
pauseSessionGoal(id: number): Promise<SessionGoal> {
|
||||
return this.runSessionGoalAction(id, 'pause')
|
||||
}
|
||||
|
||||
resumeSessionGoal(id: number): Promise<SessionGoal> {
|
||||
return this.runSessionGoalAction(id, 'resume')
|
||||
}
|
||||
|
||||
cancelSessionGoal(id: number): Promise<SessionGoal> {
|
||||
return this.runSessionGoalAction(id, 'cancel')
|
||||
}
|
||||
|
||||
listMultiRuns(repoId: number): Promise<MultiRun[]> {
|
||||
return this.requestJson(
|
||||
`/api/internal/multi-runs?repoId=${encodeURIComponent(repoId)}`,
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { TextAttributes } from '@opentui/core'
|
||||
import { useKeyboard } from '@opentui/solid'
|
||||
import { createEffect, createSignal, on, onCleanup, Show } from 'solid-js'
|
||||
import type { Context } from '@opencode/plugin/tui/context'
|
||||
import { isOpenSessionGoal, type SessionGoal } from '@opencode-manager/shared/schemas'
|
||||
import { getGoalOutcomeReason, getGoalOutcomeTitle, getGoalTokenLabel, getGoalTurnLabel } from '@opencode-manager/shared/notifications'
|
||||
import type { GoalDialogProps } from './tui-goal.js'
|
||||
import { DialogShell, TextAreaField, TextField, isSubmitKey, useFieldFocus } from './tui-form.js'
|
||||
import type { DialogTheme } from './tui-form.js'
|
||||
|
||||
const FORM_FIELDS = 3
|
||||
|
||||
export function showGoalDialog(context: Context, props: GoalDialogProps): void {
|
||||
context.ui.dialog.show(() => <GoalDialog context={context} {...props} />)
|
||||
context.ui.dialog.set({ size: 'large' })
|
||||
}
|
||||
|
||||
function GoalDialog(props: GoalDialogProps & { context: Context }) {
|
||||
const theme: DialogTheme = props.context.theme.surface('dialog')
|
||||
const [goal, setGoal] = createSignal<SessionGoal | null>(props.initialGoal)
|
||||
const [busy, setBusy] = createSignal<string | null>(null)
|
||||
const [error, setError] = createSignal<string | null>(null)
|
||||
const [confirmCancel, setConfirmCancel] = createSignal(false)
|
||||
const [objective, setObjective] = createSignal(props.initialObjective)
|
||||
const [maxTurns, setMaxTurns] = createSignal('')
|
||||
const [tokenBudget, setTokenBudget] = createSignal('')
|
||||
|
||||
onCleanup(props.store.watch(props.sessionID, (next) => setGoal(next)))
|
||||
createEffect(on([objective, maxTurns, tokenBudget], () => setError(null), { defer: true }))
|
||||
|
||||
const openGoal = () => {
|
||||
const current = goal()
|
||||
return isOpenSessionGoal(current) ? current : null
|
||||
}
|
||||
const [field, setField] = useFieldFocus(() => FORM_FIELDS, () => openGoal() === null)
|
||||
|
||||
const run = async (label: string, operation: () => Promise<string | null>): Promise<string | null | undefined> => {
|
||||
if (busy()) return undefined
|
||||
setBusy(label)
|
||||
setError(null)
|
||||
const failure = await operation()
|
||||
setBusy(null)
|
||||
setError(failure)
|
||||
return failure
|
||||
}
|
||||
|
||||
const start = async () => {
|
||||
const failure = await run('Starting goal…', () =>
|
||||
props.actions.start({ objective: objective(), maxTurns: maxTurns(), tokenBudget: tokenBudget() }),
|
||||
)
|
||||
if (failure === null) props.context.ui.dialog.clear()
|
||||
}
|
||||
|
||||
useKeyboard((event) => {
|
||||
const current = openGoal()
|
||||
if (!current) {
|
||||
if (!isSubmitKey(event)) return
|
||||
event.preventDefault()
|
||||
void start()
|
||||
return
|
||||
}
|
||||
if (event.name === 'p') {
|
||||
event.preventDefault()
|
||||
setConfirmCancel(false)
|
||||
void run(current.status === 'paused' ? 'Resuming goal…' : 'Pausing goal…', () =>
|
||||
current.status === 'paused' ? props.actions.resume(current) : props.actions.pause(current),
|
||||
)
|
||||
return
|
||||
}
|
||||
if (event.name === 'x') {
|
||||
event.preventDefault()
|
||||
if (!confirmCancel()) {
|
||||
setConfirmCancel(true)
|
||||
return
|
||||
}
|
||||
setConfirmCancel(false)
|
||||
void run('Cancelling goal…', () => props.actions.cancel(current))
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<Show
|
||||
when={openGoal()}
|
||||
fallback={
|
||||
<DialogShell
|
||||
theme={theme}
|
||||
title="Start goal"
|
||||
subtitle="Runs until the Manager's auditor says it is done"
|
||||
busy={busy()}
|
||||
error={error()}
|
||||
hints={[
|
||||
['tab', 'next field'],
|
||||
['ctrl+s', 'start goal'],
|
||||
]}
|
||||
>
|
||||
<text fg={theme.text.muted}>Sends with this session's current agent and model; send a message first to switch.</text>
|
||||
<Show when={goal()}>{(last) => <LastGoal theme={theme} goal={last()} />}</Show>
|
||||
<TextAreaField
|
||||
theme={theme}
|
||||
label="Objective"
|
||||
initialValue={props.initialObjective}
|
||||
placeholder="What should this session accomplish?"
|
||||
height={4}
|
||||
focused={field() === 0}
|
||||
onInput={setObjective}
|
||||
/>
|
||||
<box flexDirection="row" gap={4}>
|
||||
<box flexGrow={1}>
|
||||
<TextField
|
||||
theme={theme}
|
||||
label="Max turns"
|
||||
initialValue=""
|
||||
placeholder="Manager default"
|
||||
focused={field() === 1}
|
||||
onInput={setMaxTurns}
|
||||
onSubmit={() => setField(2)}
|
||||
/>
|
||||
</box>
|
||||
<box flexGrow={1}>
|
||||
<TextField
|
||||
theme={theme}
|
||||
label="Token budget"
|
||||
initialValue=""
|
||||
placeholder="Manager default"
|
||||
focused={field() === 2}
|
||||
onInput={setTokenBudget}
|
||||
onSubmit={() => void start()}
|
||||
/>
|
||||
</box>
|
||||
</box>
|
||||
</DialogShell>
|
||||
}
|
||||
>
|
||||
{(current) => (
|
||||
<DialogShell
|
||||
theme={theme}
|
||||
title="Session goal"
|
||||
busy={busy()}
|
||||
error={error()}
|
||||
hints={[
|
||||
['p', current().status === 'paused' ? 'resume' : 'pause'],
|
||||
['x', 'cancel goal'],
|
||||
]}
|
||||
>
|
||||
<GoalStatus theme={theme} goal={current()} />
|
||||
<Show when={confirmCancel()}>
|
||||
<text fg={theme.text.feedback.warning.base}>Press x again to cancel the goal. This cannot be undone.</text>
|
||||
</Show>
|
||||
</DialogShell>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
function GoalStatus(props: { theme: DialogTheme; goal: SessionGoal }) {
|
||||
const tone = () => (props.goal.status === 'active' ? props.theme.text.feedback.info.base : props.theme.text.feedback.warning.base)
|
||||
return (
|
||||
<box gap={1}>
|
||||
<box flexDirection="row" gap={2} flexWrap="wrap">
|
||||
<text fg={tone()} attributes={TextAttributes.BOLD}>
|
||||
{getGoalOutcomeTitle(props.goal.status)}
|
||||
</text>
|
||||
<text fg={props.theme.text.muted}>{getGoalTurnLabel(props.goal)}</text>
|
||||
<Show when={getGoalTokenLabel(props.goal)}>{(tokens) => <text fg={props.theme.text.muted}>{tokens()}</text>}</Show>
|
||||
<text fg={props.theme.text.muted}>{props.goal.turnState === 'running' ? 'working' : 'waiting'}</text>
|
||||
</box>
|
||||
<text fg={props.theme.text.base}>{props.goal.objective}</text>
|
||||
<Show when={getGoalOutcomeReason(props.goal)}>
|
||||
{(reason) => (
|
||||
<text fg={props.theme.text.muted}>
|
||||
{props.goal.lastVerdict ? `Last verdict: ${props.goal.lastVerdict} · ` : ''}
|
||||
{reason()}
|
||||
</text>
|
||||
)}
|
||||
</Show>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
|
||||
function LastGoal(props: { theme: DialogTheme; goal: SessionGoal }) {
|
||||
return (
|
||||
<text fg={props.theme.text.muted} wrapMode="none" truncate>
|
||||
Last goal: {getGoalOutcomeTitle(props.goal.status)}
|
||||
{getGoalOutcomeReason(props.goal) ? ` · ${getGoalOutcomeReason(props.goal)}` : ''} · {props.goal.objective}
|
||||
</text>
|
||||
)
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
import type { Context, ToastOptions } from '@opencode/plugin/tui/context'
|
||||
import {
|
||||
GOAL_MAX_CONTINUATIONS_MAX,
|
||||
GOAL_MAX_CONTINUATIONS_MIN,
|
||||
StartSessionGoalRequestSchema,
|
||||
isOpenSessionGoal,
|
||||
type SessionGoal,
|
||||
type StartSessionGoalRequest,
|
||||
} from '@opencode-manager/shared/schemas'
|
||||
import {
|
||||
getGoalOutcomeReason,
|
||||
getGoalOutcomeTitle,
|
||||
getGoalTokenLabel,
|
||||
getGoalTurnLabel,
|
||||
} from '@opencode-manager/shared/notifications'
|
||||
import { isManagerRouteMissing } from './manager-api.js'
|
||||
import type { ManagerApi } from './manager-api.js'
|
||||
import { resolveManagerApi } from './manager-auth.js'
|
||||
import { describeCause } from './token-store.js'
|
||||
import { requireSessionTarget, slashArgument } from './tui-dialogs.js'
|
||||
import type { GoalStore } from './goal-store.js'
|
||||
import type { RemoteContext } from './remote-context.js'
|
||||
|
||||
export const GOAL_COMMAND = 'ocm-goal'
|
||||
|
||||
export const GOALS_ATTACH_REQUIRED =
|
||||
'Goals run on OpenCode Manager. Attach with `ocm` (or move this session with /ocm-move) first.'
|
||||
export const GOALS_ROUTE_MISSING = 'This OpenCode Manager does not expose goals to ocm; upgrade the Manager.'
|
||||
|
||||
export type GoalFormInput = {
|
||||
objective: string
|
||||
maxTurns: string
|
||||
tokenBudget: string
|
||||
}
|
||||
|
||||
export type GoalFormResult = { ok: true; request: StartSessionGoalRequest } | { ok: false; error: string }
|
||||
|
||||
/** Goal operations the goal dialog calls. Each resolves to an error message, or null on success. */
|
||||
export type GoalActions = {
|
||||
start(form: GoalFormInput): Promise<string | null>
|
||||
pause(goal: SessionGoal): Promise<string | null>
|
||||
resume(goal: SessionGoal): Promise<string | null>
|
||||
cancel(goal: SessionGoal): Promise<string | null>
|
||||
}
|
||||
|
||||
export type GoalDialogProps = {
|
||||
sessionID: string
|
||||
store: GoalStore
|
||||
initialGoal: SessionGoal | null
|
||||
initialObjective: string
|
||||
actions: GoalActions
|
||||
}
|
||||
|
||||
export type GoalCommandDeps = {
|
||||
remote: RemoteContext | undefined
|
||||
store: GoalStore | undefined
|
||||
showDialog: (props: GoalDialogProps) => void
|
||||
}
|
||||
|
||||
const GOAL_OBJECTIVE_MAX_LENGTH = 60
|
||||
|
||||
/** The objective's first line, cut to a single-line summary with a trailing ellipsis when long. */
|
||||
export function goalObjectiveSummary(objective: string): string {
|
||||
const newline = objective.indexOf('\n')
|
||||
const firstLine = (newline === -1 ? objective : objective.slice(0, newline)).trim()
|
||||
return firstLine.length > GOAL_OBJECTIVE_MAX_LENGTH ? `${firstLine.slice(0, GOAL_OBJECTIVE_MAX_LENGTH)}…` : firstLine
|
||||
}
|
||||
|
||||
export function formatGoalStatus(goal: SessionGoal): string {
|
||||
return [getGoalOutcomeTitle(goal.status), getGoalTurnLabel(goal), getGoalTokenLabel(goal), goalObjectiveSummary(goal.objective)]
|
||||
.filter((part): part is string => part !== null)
|
||||
.join(' · ')
|
||||
}
|
||||
|
||||
export function goalOutcomeToast(goal: SessionGoal): ToastOptions {
|
||||
const variant = goal.status === 'completed' ? 'success' : goal.status === 'blocked' ? 'error' : 'warning'
|
||||
return {
|
||||
variant,
|
||||
title: getGoalOutcomeTitle(goal.status),
|
||||
message: getGoalOutcomeReason(goal) ?? goalObjectiveSummary(goal.objective),
|
||||
}
|
||||
}
|
||||
|
||||
/** Validates the goal dialog fields into a start request; blank limits fall back to the Manager defaults. */
|
||||
export function parseGoalForm(form: GoalFormInput, sessionId: string, directory: string): GoalFormResult {
|
||||
const objective = form.objective.trim()
|
||||
if (!objective) return { ok: false, error: 'Describe what this session should accomplish.' }
|
||||
|
||||
const maxContinuations = parseOptionalInteger(form.maxTurns)
|
||||
if (
|
||||
maxContinuations === null ||
|
||||
(maxContinuations !== undefined &&
|
||||
(maxContinuations < GOAL_MAX_CONTINUATIONS_MIN || maxContinuations > GOAL_MAX_CONTINUATIONS_MAX))
|
||||
) {
|
||||
return { ok: false, error: `Max turns must be a whole number from ${GOAL_MAX_CONTINUATIONS_MIN} to ${GOAL_MAX_CONTINUATIONS_MAX}.` }
|
||||
}
|
||||
|
||||
const tokenBudget = parseOptionalInteger(form.tokenBudget)
|
||||
if (tokenBudget === null || (tokenBudget !== undefined && tokenBudget <= 0)) {
|
||||
return { ok: false, error: 'Token budget must be a positive whole number.' }
|
||||
}
|
||||
|
||||
const parsed = StartSessionGoalRequestSchema.safeParse({
|
||||
sessionId,
|
||||
directory,
|
||||
objective,
|
||||
...(maxContinuations !== undefined ? { maxContinuations } : {}),
|
||||
...(tokenBudget !== undefined ? { tokenBudget } : {}),
|
||||
})
|
||||
if (!parsed.success) return { ok: false, error: parsed.error.issues[0]?.message ?? 'Invalid goal.' }
|
||||
return { ok: true, request: parsed.data }
|
||||
}
|
||||
|
||||
export function describeGoalError(error: unknown): string {
|
||||
if (isManagerRouteMissing(error)) return GOALS_ROUTE_MISSING
|
||||
return describeCause(error)
|
||||
}
|
||||
|
||||
export async function runGoalCommand(context: Context, deps: GoalCommandDeps, input?: string): Promise<void> {
|
||||
try {
|
||||
if (!deps.remote || !deps.store) {
|
||||
context.ui.toast.show({ variant: 'error', message: GOALS_ATTACH_REQUIRED })
|
||||
return
|
||||
}
|
||||
|
||||
const target = requireSessionTarget(context)
|
||||
if (!target) return
|
||||
const { sessionID, directory } = target
|
||||
|
||||
const resolved = await resolveManagerApi(deps.remote.managerUrl)
|
||||
if (!resolved.ok) {
|
||||
context.ui.toast.show({ variant: 'error', message: resolved.message })
|
||||
return
|
||||
}
|
||||
const api = resolved.api
|
||||
const store = deps.store
|
||||
const actions = createGoalActions(context, api, store, sessionID, directory)
|
||||
|
||||
const objective = slashArgument(input, GOAL_COMMAND)
|
||||
const existing = await api.getLatestSessionGoal(sessionID)
|
||||
if (objective && !isOpenSessionGoal(existing)) {
|
||||
const error = await actions.start({ objective, maxTurns: '', tokenBudget: '' })
|
||||
if (error) context.ui.toast.show({ variant: 'error', message: error })
|
||||
return
|
||||
}
|
||||
|
||||
deps.showDialog({ sessionID, store, initialGoal: existing, initialObjective: objective, actions })
|
||||
} catch (error) {
|
||||
context.ui.toast.show({ variant: 'error', message: describeGoalError(error) })
|
||||
}
|
||||
}
|
||||
|
||||
function createGoalActions(context: Context, api: ManagerApi, store: GoalStore, sessionID: string, directory: string): GoalActions {
|
||||
const run = async (operation: () => Promise<SessionGoal>): Promise<string | null> => {
|
||||
try {
|
||||
store.set(await operation())
|
||||
return null
|
||||
} catch (error) {
|
||||
return describeGoalError(error)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
async start(form) {
|
||||
const parsed = parseGoalForm(form, sessionID, directory)
|
||||
if (!parsed.ok) return parsed.error
|
||||
return startGoal(context, api, store, parsed.request)
|
||||
},
|
||||
pause: (goal) => run(() => api.pauseSessionGoal(goal.id)),
|
||||
resume: (goal) => run(() => api.resumeSessionGoal(goal.id)),
|
||||
cancel: (goal) => run(() => api.cancelSessionGoal(goal.id)),
|
||||
}
|
||||
}
|
||||
|
||||
async function startGoal(context: Context, api: ManagerApi, store: GoalStore, request: StartSessionGoalRequest): Promise<string | null> {
|
||||
let goal: SessionGoal
|
||||
try {
|
||||
goal = await api.startSessionGoal(request)
|
||||
} catch (error) {
|
||||
return describeGoalError(error)
|
||||
}
|
||||
store.set(goal)
|
||||
|
||||
try {
|
||||
await context.client.session.prompt({
|
||||
sessionID: request.sessionId,
|
||||
text: request.objective,
|
||||
delivery: context.data.session.status(request.sessionId) === 'running' ? 'queue' : undefined,
|
||||
})
|
||||
return null
|
||||
} catch (error) {
|
||||
const cancelled = await api.cancelSessionGoal(goal.id).catch(() => undefined)
|
||||
if (cancelled) store.set(cancelled)
|
||||
return `The goal was cancelled because the objective could not be sent: ${describeCause(error)}`
|
||||
}
|
||||
}
|
||||
|
||||
function parseOptionalInteger(value: string): number | undefined | null {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return undefined
|
||||
return /^\d+$/.test(trimmed) ? Number(trimmed) : null
|
||||
}
|
||||
@@ -14,25 +14,20 @@ import { setPendingWarp, runPendingWarp } from './warp.js'
|
||||
import { pushPhaseProgress, importProgress } from './move-progress.js'
|
||||
import { warmRepoProxy } from './repo-proxy.js'
|
||||
import type { MoveProgress } from './move-progress.js'
|
||||
import { GOAL_COMMAND, runGoalCommand } from './tui-goal.js'
|
||||
import type { GoalDialogProps } from './tui-goal.js'
|
||||
import { MULTI_RUN_COMMAND, runMultiRunCommand } from './tui-multi-run.js'
|
||||
import type { MultiRunLaunchDialogProps, MultiRunsDialogProps } from './tui-multi-run.js'
|
||||
import { runOcmSwitch } from './tui-ocm.js'
|
||||
import type { GoalStore } from './goal-store.js'
|
||||
import type { RemoteContext } from './remote-context.js'
|
||||
|
||||
export type MoveProgressSetter = (progress: MoveProgress | null) => void
|
||||
|
||||
export type OcmDialogs = {
|
||||
goal: (props: GoalDialogProps) => void
|
||||
multiRunLaunch: (props: MultiRunLaunchDialogProps) => void
|
||||
multiRuns: (props: MultiRunsDialogProps) => void
|
||||
}
|
||||
|
||||
export type OcmFeatures = {
|
||||
remote: RemoteContext | undefined
|
||||
goals: GoalStore | undefined
|
||||
dialogs: OcmDialogs
|
||||
}
|
||||
|
||||
@@ -62,16 +57,6 @@ export async function setupOcm(context: Context, setMoveProgress: MoveProgressSe
|
||||
slash: { name: 'ocm' },
|
||||
run: () => runOcmSwitch(context, { remote: features.remote }),
|
||||
},
|
||||
{
|
||||
id: 'ocm.goal',
|
||||
title: 'Goal',
|
||||
description: 'Start, pause, resume, or cancel a Manager goal for this session',
|
||||
group: 'OpenCode Manager',
|
||||
palette: true,
|
||||
slash: { name: GOAL_COMMAND, arguments: true },
|
||||
run: (input) =>
|
||||
runGoalCommand(context, { remote: features.remote, store: features.goals, showDialog: features.dialogs.goal }, input),
|
||||
},
|
||||
{
|
||||
id: 'ocm.multirun',
|
||||
title: 'Multi-run',
|
||||
|
||||
+3
-52
@@ -1,18 +1,13 @@
|
||||
/** @jsxImportSource @opentui/solid */
|
||||
import { createSignal, createEffect, onCleanup, Show } from 'solid-js'
|
||||
import { Plugin } from '@opencode/plugin/tui'
|
||||
import type { HueScale } from '@opencode/theme/tui'
|
||||
import { setupOcm } from './tui-plugin.js'
|
||||
import { showGoalDialog } from './tui-goal-dialog.js'
|
||||
import { showMultiRunLaunchDialog, showMultiRunsDialog } from './tui-multi-run-dialogs.js'
|
||||
import { formatMoveProgress } from './move-progress.js'
|
||||
import type { MoveProgress } from './move-progress.js'
|
||||
import { readRemoteContext, remoteDisplayName } from './remote-context.js'
|
||||
import { readState } from './state.js'
|
||||
import { createGoalStore } from './goal-store.js'
|
||||
import type { GoalStore } from './goal-store.js'
|
||||
import { formatGoalStatus, goalOutcomeToast } from './tui-goal.js'
|
||||
import { resolveManagerApi } from './manager-auth.js'
|
||||
import { isOpenSessionGoal, type SessionGoal } from '@opencode-manager/shared/schemas'
|
||||
|
||||
const SPINNER_INTERVAL_MS = 80
|
||||
|
||||
@@ -42,9 +37,10 @@ export default Plugin.define({
|
||||
const remote = readRemoteContext(process.env)
|
||||
if (remote) {
|
||||
const managerLabel = remoteDisplayName(remote, readState())
|
||||
const namedHues: Readonly<Record<string, HueScale | undefined>> = context.theme.hue
|
||||
const indicator = () => (
|
||||
<box flexDirection="row" flexShrink={0} gap={1}>
|
||||
<text fg={context.theme.hue.orange?.[400] ?? context.theme.text.feedback.warning.base}>{managerLabel}</text>
|
||||
<text fg={namedHues.orange?.[400] ?? context.theme.text.feedback.warning.base}>{managerLabel}</text>
|
||||
{remote.repoName && <text fg={context.theme.text.muted}> · {remote.repoName}</text>}
|
||||
</box>
|
||||
)
|
||||
@@ -53,54 +49,9 @@ export default Plugin.define({
|
||||
context.ui.slot({ append: 'home.footer.status', render: indicator })
|
||||
}
|
||||
|
||||
const goals = remote
|
||||
? createGoalStore({
|
||||
load: async (sessionID, signal) => {
|
||||
const resolved = await resolveManagerApi(remote.managerUrl)
|
||||
if (!resolved.ok) throw new Error(resolved.message)
|
||||
return resolved.api.getLatestSessionGoal(sessionID, signal)
|
||||
},
|
||||
onOutcome: (goal) => {
|
||||
context.ui.toast.show({ ...goalOutcomeToast(goal), sessionID: goal.sessionId })
|
||||
},
|
||||
})
|
||||
: undefined
|
||||
|
||||
const GoalLine = (props: { sessionID: string; store: GoalStore }) => {
|
||||
const [goal, setGoal] = createSignal<SessionGoal | null>(null)
|
||||
createEffect(() => {
|
||||
const unsubscribe = props.store.watch(props.sessionID, (next) => setGoal(next))
|
||||
onCleanup(unsubscribe)
|
||||
})
|
||||
const openGoal = () => {
|
||||
const current = goal()
|
||||
return isOpenSessionGoal(current) ? current : null
|
||||
}
|
||||
return (
|
||||
<Show when={openGoal()}>
|
||||
{(current) => (
|
||||
<box flexDirection="row" flexShrink={0}>
|
||||
<text wrapMode="none" fg={current().status === 'active' ? context.theme.hue.accent[200] : context.theme.text.muted}>
|
||||
{formatGoalStatus(current())}
|
||||
</text>
|
||||
</box>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
if (goals) {
|
||||
context.ui.slot({
|
||||
append: 'session.composer.top',
|
||||
render: (input) => <GoalLine sessionID={input.sessionID} store={goals} />,
|
||||
})
|
||||
}
|
||||
|
||||
return setupOcm(context, setMoveProgress, {
|
||||
remote,
|
||||
goals,
|
||||
dialogs: {
|
||||
goal: (props) => showGoalDialog(context, props),
|
||||
multiRunLaunch: (props) => showMultiRunLaunchDialog(context, props),
|
||||
multiRuns: (props) => showMultiRunsDialog(context, props),
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user