Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/mms/MmsProfileServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1955,6 +1955,9 @@ export class MmsProfileServices {
this.personalBots?.threadRunEnded(payload.threadId)
this.threadWakes.threadRunEnded(payload.threadId)
})
// Retry clears why a thread's worktree could not be set up: a bot's job still open on its failed run (a restart lost
// the run's end) reads it first and ends with why, and the retried run's work opens a follow-up job.
this.orchestrator.on('setup-retry', (payload: { threadId: string }) => this.personalBots?.checkJobs(payload.threadId))
// Any Stop that reaches a thread, and every subagent below it, ends its watch at once.
this.orchestrator.on('threads-stopped', (payload: { threadIds: string[] }) => this.pullRequestWatch.onStopped(payload.threadIds))
// An archived thread's watch ends as archived, not as stopped (`OrchestratorService.archiveThread`).
Expand Down
38 changes: 33 additions & 5 deletions src/mms/bots/activation/BotEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ import { botDeviceAllowed, DEFAULT_BOT_DEVICE_ACCESS } from '../../../shared/bot
import { BOT_COMMANDS_OPEN, BOT_HELD_POWER_TEXT, subagentHold, type BotHeldPower, type BotRuntimeHold, type BotSubagentHold } from '../../../shared/bots/personal/subagentHold'
import type { BotAuthority, BotCheck, BotCheckDenied, BotMcpTool, BotSubagents, BotSubagentView, BotThreadRole, BotThreads, NormalisedCall, WallReason } from '../../../shared/bots/personal/authority'
import { launchedActive, type BotChatMessage, type BotChip, type BotError, type BotLaunchedThread, type BotPermissionItem } from '../../../shared/bots/personal/chat'
import { jobAskerOf, jobStateOf, jobStep, resultLine, type JobThreadView } from '../jobs'
import { BOT_JOB_ENDED, jobLine, jobNoticeInput, jobNoticeLabel, relatedJobsLine, THREAD_MESSAGE_KEY_PREFIX, threadMessageInput, threadMessageLabel, type BotJob, type BotJobState } from '../../../shared/bots/personal/jobs'
import { endedLine, jobAskerOf, jobStateOf, jobStep, type JobThreadView } from '../jobs'
import { BOT_JOB_ENDED, jobLine, jobNoticeInput, jobNoticeLabel, relatedJobsLine, THREAD_MESSAGE_KEY_PREFIX, threadMessageInput, threadMessageLabel, type BotJob, type BotJobState, type JobSetupFailure } from '../../../shared/bots/personal/jobs'
import { threadLink } from '../../../shared/threadLink'
import { isStricter, narrowPermissionMode, type PermissionMode } from '../../../shared/permissionMode'
import {
Expand Down Expand Up @@ -10384,6 +10384,27 @@ export class BotEngine implements BotTurnDispatcher, BotThreads {
}
}

/**
* The run that started job `jobId` never started its agent: setting up its thread's worktree failed (`thread_create`
* follows the run it started instead of waiting on it). The job ends as failed with why, once: a job that already
* moved on its own (`checkJobs` read the failure when the run ended) or ended is left as it is. A Retry that already
* started a newer run does not hide this run's failure; that run's work opens a follow-up job (`followUpJob`).
* Never throws.
*/
jobSetupFailed(botId: string, jobId: string, failure: JobSetupFailure): void {
let job: BotJob | undefined
try {
job = this.store.job(jobId)
} catch {
return
}
if (!job || job.botId !== botId || job.endedAt || BOT_JOB_ENDED.has(job.state)) return
const seen: JobThreadView = { status: 'failed', setupFailure: failure }
void this.deliverJobNotice(job, 'failed', endedLine(seen), seen).catch((error: unknown) => {
console.warn('a bot job\'s notice could not be delivered', { jobId, error: error instanceof Error ? error.message : String(error) })
})
}

/** The jobs not ended on `threadId` look at their thread now. Never throws. */
checkJobs(threadId: string): void {
// The local thread store has no view of a remote worker. Its absence here doesn't prove the worker stopped.
Expand Down Expand Up @@ -10424,7 +10445,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads {
private stepJob(job: BotJob, seen: JobThreadView): void {
const step = jobStep(job, jobStateOf(seen.status))
if (!step) return
const line = BOT_JOB_ENDED.has(step.state) ? resultLine(seen.result) : undefined
const line = BOT_JOB_ENDED.has(step.state) ? endedLine(seen) : undefined
if (!step.notice) {
if (this.store.moveJob(job.id, job.state, step.state)) this.changed({ botId: job.botId })
return
Expand All @@ -10447,7 +10468,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads {
return
}
const next: BotJob = { ...job, state, ...(line ? { line } : {}), ...(seen.title?.trim() ? { title: jobLine(seen.title, 200) } : {}) }
const input = jobNoticeInput(next, BOT_JOB_ENDED.has(state) ? { result: seen.result } : { asks: seen.asks, onHold: seen.status === 'on_hold' })
const input = jobNoticeInput(next, BOT_JOB_ENDED.has(state) ? { result: seen.result, ...(seen.setupFailure ? { setupFailure: seen.setupFailure } : {}) } : { asks: seen.asks, onHold: seen.status === 'on_hold' })
const paused = Boolean(registry.pausedReason)
const activationId = newActivationId()
let refused: BotEngineError | undefined
Expand All @@ -10458,7 +10479,9 @@ export class BotEngine implements BotTurnDispatcher, BotThreads {
if (!paused) refused = this.queueChatInTx(job.botId, `job:${job.id}:${activationId}`, input, activationId, this.jobDevice(job), { fast: state === 'needs_input' })
// Nothing shows in the chat: the notice is the bot's to act on, and only what it says reaches the owner.
if (!paused && !refused) return true
this.chat.post({ id: `bm_job_${job.id}_${activationId}`, botId: job.botId, author: 'bot', kind: 'run_report', text: `${jobNoticeLabel(next)}: ${threadLink(job.threadId)}. I didn't follow up on this: ${paused ? 'I\'m paused.' : refused!.message}`, external: true, lane: 'chat' })
// A run that never started says why, as the job's line keeps it: the owner sees it with no turn of the bot's.
const why = state === 'failed' && seen.setupFailure && line ? ` ${line}` : ''
this.chat.post({ id: `bm_job_${job.id}_${activationId}`, botId: job.botId, author: 'bot', kind: 'run_report', text: `${jobNoticeLabel(next)}: ${threadLink(job.threadId)}.${why} I didn't follow up on this: ${paused ? 'I\'m paused.' : refused!.message}`, external: true, lane: 'chat' })
return false
})
if (started === undefined) return
Expand Down Expand Up @@ -11078,6 +11101,11 @@ export class BotEngine implements BotTurnDispatcher, BotThreads {
},
jobs: {
open: (botId, from, input) => this.openJob(botId, from, input),
setupFailed: (botId, jobId, failure) => this.jobSetupFailed(botId, jobId, failure),
launched: (botId, threadId) => {
const job = this.store.firstJobOn(botId, threadId)
return job ? { jobId: job.id } : undefined
},
message: (botId, threadId, input) => this.threadMessage(botId, threadId, input)
},
wakes: {
Expand Down
12 changes: 11 additions & 1 deletion src/mms/bots/jobs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { BotLaunchedThread } from '../../shared/bots/personal/chat'
import { jobLine, type BotJob, type BotJobAsker, type BotJobState, type BotThreadAsk } from '../../shared/bots/personal/jobs'
import { jobLine, type BotJob, type BotJobAsker, type BotJobState, type BotThreadAsk, type JobSetupFailure } from '../../shared/bots/personal/jobs'
import { modelFacingReplyText } from '../../shared/applets'
import type { ChatMessage } from '../../shared/types'
import type { BotActivationRow } from './store/BotStore'
Expand All @@ -18,6 +18,8 @@ export interface JobThreadView {
result?: string
/** The thread's own requests waiting for a person (not its subagents'), oldest first, when it waits for one. */
asks?: BotThreadAsk[]
/** Why its last run never started: setting up its worktree failed (`Thread.setupFailure` of that run). */
setupFailure?: JobSetupFailure
}

/**
Expand Down Expand Up @@ -50,6 +52,14 @@ export function jobStep(job: Pick<BotJob, 'state'>, next: BotJobState | undefine
return { state: next, notice: next !== 'running' }
}

/**
* The line a job keeps once its thread ended as `seen` says (`BotJob.line`): why its run never started when its worktree
* could not be set up (Mousse's plain reason, never Git's output), else the first line of its answer (`resultLine`).
*/
export function endedLine(seen: Pick<JobThreadView, 'result' | 'setupFailure'>): string | undefined {
return seen.setupFailure?.reason.trim() ? jobLine(seen.setupFailure.reason) : resultLine(seen.result)
}

/** A line that only lays the answer out: a heading, a rule, or a code fence. */
const LAYOUT_LINE = /^(?:#{1,6}(?:\s|$)|([-*_=])(?:\s*\1){2,}$|```|~~~)/

Expand Down
7 changes: 6 additions & 1 deletion src/mms/bots/launchedThreads.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export interface LaunchedThreadMeta {
archivedAt?: string
/** `Thread.lineage`: set on a subagent's thread, naming the thread that started it. */
lineage?: ThreadLineage
/** `Thread.setupFailure`: why its last message could not start (a job's notice says it). */
setupFailure?: Thread['setupFailure']
}

/** How a thread's last run ended, when none runs now: finished, failed, stopped (or cut off), or it never ran. */
Expand Down Expand Up @@ -355,7 +357,10 @@ export function jobThreadIn(profile: Parameters<typeof launchedThreadsIn>[0] & {
// The reply that run ended on, by its id, never a progress message or an earlier turn's reply (`jobResultOf`).
const result = run ? jobResultOf(profile.recorded?.(threadId, run.runId), profile.messages?.(threadId) ?? [], run.runId) : undefined
const asks = listed.status === 'needs_input' ? profile.pending?.(threadId).map(threadAsk) : undefined
return { status: listed.status, ...(title ? { title } : {}), ...(result?.trim() ? { result } : {}), ...(asks?.length ? { asks } : {}) }
// That run never started: its worktree could not be set up, and the thread keeps why for that run (a Retry clears it).
const failure = listed.status === 'failed' && run && thread.setupFailure?.runId === run.runId ? thread.setupFailure : undefined
const setupFailure = failure ? { reason: failure.reason, ...(failure.detail ? { detail: failure.detail } : {}), retryable: failure.retryable } : undefined
return { status: listed.status, ...(title ? { title } : {}), ...(result?.trim() ? { result } : {}), ...(asks?.length ? { asks } : {}), ...(setupFailure ? { setupFailure } : {}) }
}

/**
Expand Down
11 changes: 11 additions & 0 deletions src/mms/bots/seams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { BotModelRows, BotPickMiss } from '../../shared/bots/personal/model
import type { BotQuestionAsk, BotQuestionStatus } from '../../shared/bots/personal/questions'
import type { BotCard } from '../../shared/bots/personal/cards'
import type { BotWakeEvent } from '../../shared/bots/personal/wakes'
import type { JobSetupFailure } from '../../shared/bots/personal/jobs'
import type { BotSandboxPolicy } from '../../shared/bots/personal/sandbox'
import type { BotJournalKind, BotJournalWho, BotMemoryEntry, BotMemoryForgetResult, BotMemoryListing } from '../../shared/bots/personal/memory'
import type { Enforceability, ProviderSelection, RunPolicy } from '../../shared/harness/types'
Expand Down Expand Up @@ -234,6 +235,16 @@ export interface BotToolHost {
*/
jobs?: {
open(botId: string, from: string, input: { threadId: string; title: string; project?: string; sent: string }): { jobId: string }
/**
* The run that started job `jobId` never started its agent: its thread's worktree could not be set up. The job ends
* as failed with why, once, unless it already moved or ended. Absent: the caller waits for setup instead.
*/
setupFailed?(botId: string, jobId: string, failure: JobSetupFailure): void
/**
* The job the call that started `threadId` opened, ended or not, for a retry of that call (its first reply was lost):
* the same job as the first answer named. Undefined when it opened none.
*/
launched?(botId: string, threadId: string): { jobId: string } | undefined
/**
* A message thread `threadId`, which bot `botId` started, sends the bot while it works (`message_parent`): a notice
* turn in the bot's chat, keyed by `requestKey` so a retry replays. Throws, with why in words for the thread, when
Expand Down
6 changes: 6 additions & 0 deletions src/mms/bots/store/BotStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2306,6 +2306,12 @@ export class BotStore {
return this.all('SELECT * FROM bot_jobs WHERE thread_id = ? AND ended_at IS NULL ORDER BY created_at', threadId).map(jobOf)
}

/** The bot's first job on `threadId`, ended or not: the one the call that started the thread opened. */
firstJobOn(botId: string, threadId: string): BotJob | undefined {
const row = this.get('SELECT * FROM bot_jobs WHERE bot_id = ? AND thread_id = ? ORDER BY created_at, rowid LIMIT 1', botId, threadId)
return row ? jobOf(row) : undefined
}

/** The bot's newest job on `threadId`, ended or not. */
latestJobOn(botId: string, threadId: string): BotJob | undefined {
const row = this.get('SELECT * FROM bot_jobs WHERE bot_id = ? AND thread_id = ? ORDER BY created_at DESC, rowid DESC LIMIT 1', botId, threadId)
Expand Down
6 changes: 6 additions & 0 deletions src/mms/orchestrator/OrchestratorService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11186,6 +11186,12 @@ export class OrchestratorService extends EventEmitter {
rmSync(claimed, { force: true })
}
if (typeof kept.content !== 'string' || !kept.content) throw new DomainRpcError('nothing_to_retry', 'The message to send again could not be read.', { threadId })
// Whoever follows the failed run reads why before it is cleared (a bot's job, when a restart lost its earlier read).
try {
this.emit('setup-retry', { threadId })
} catch (error) {
console.warn('a setup retry could not be told', { threadId, error: error instanceof Error ? error.message : String(error) })
}
this.threadStore.setThreadSetupFailure(threadId, undefined)
const input: OrchestratorSendRequest = {
content: kept.content,
Expand Down
44 changes: 42 additions & 2 deletions src/mms/run/mcp/appTools/thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1177,6 +1177,41 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B
return undefined
}
}
/**
* A retry of a personal bot's `thread_create` whose first reply was lost: the job that first call opened on the thread,
* so the retry names the same job. Nothing when the ledger is not here or kept none.
*/
const launchedJob = (threadId: string, ctx: ToolCallContext): { job: { jobId: string; next: string } } | undefined => {
const deps = bots?.()
const activation = deps?.host.activationOf(ctx.caller.threadId)
if (!deps?.host.jobs?.launched || !activation) return undefined
try {
const found = deps.host.jobs.launched(activation.botId, threadId)
return found ? { job: { jobId: found.jobId, next: BOT_JOB_NEXT } } : undefined
} catch {
return undefined
}
}
/**
* The first run of a thread a personal bot started, which job `jobId` of its ledger follows: the bot is answered without
* waiting for the thread's folder to be set up, and a worktree that could not be set up for that run ends the job as
* failed with why (`jobs.setupFailed`), once. False when the ledger can't take it: the caller waits for setup instead.
*/
const followJobSetup = (threadId: string, sent: { runId?: string; queued?: boolean; replayed?: boolean }, jobId: string, ctx: ToolCallContext): boolean => {
const deps = bots?.()
const jobs = deps?.host.jobs
const activation = deps?.host.activationOf(ctx.caller.threadId)
if (!jobs?.setupFailed || !activation || !host.waitForSetup) return false
// As `setupOf`: only a run that started now has a setup to follow.
if (!sent.runId || sent.queued || sent.replayed) return true
void host.waitForSetup(threadId, sent.runId).then((setup) => {
const failure = setup.status === 'failed' ? setup.failure : undefined
if (failure) jobs.setupFailed!(activation.botId, jobId, { reason: failure.reason, ...(failure.detail ? { detail: failure.detail } : {}), retryable: failure.retryable })
}).catch((error: unknown) => {
console.warn('a bot thread\'s setup could not be followed', { threadId, error: error instanceof Error ? error.message : String(error) })
})
return true
}
/**
* The parent `message_parent` reaches from `threadId`: a subagent's parent thread, or the personal bot that started the
* thread. Nothing else is a parent: a thread another agent launched with thread_create has none to message.
Expand Down Expand Up @@ -2976,6 +3011,7 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B
? `${botRequestPrefix('thread_create', ctx.caller.threadId, ctx.turn.bot!.activationId)}${toolRequestId(args, ctx)}`
: `thread_create:${ctx.caller.threadId}:${toolRequestId(args, ctx)}`)
if (saved?.launch.threadId) return json({
...launchedJob(saved.launch.threadId, ctx),
threadId: saved.launch.threadId, link: threadLink(saved.launch.threadId), replayed: true, ask: saved.launch.ask, attempt: requestKey
})
let created: AgentCreatedThread
Expand All @@ -3002,11 +3038,15 @@ export function threadTools(host: AppToolHost, engine: RunEngine, bots?: () => B
title: created.title, project: projectName(created.projectId) ?? undefined,
sent: saved.launch.payload.firstMessage, ...(created.firstMessage?.sent === true ? {} : { uncertain: true })
})
const job = saved
const opened = saved
? savedJob && { job: { ...savedJob, next: BOT_JOB_NEXT } }
: firstSent ? botJob(created.threadId, created.title, created.projectId, args.firstMessage as string, ctx) : undefined
// A retry of the call names the job the first call opened.
const job = opened ?? (created.replayed ? launchedJob(created.threadId, ctx) : undefined)
const told = job ?? (notify && firstSent ? await botNotify(created.threadId, created.title, args.firstMessage as string, ctx) : {})
const setup = firstSent && created.firstMessage?.sent === true ? await setupOf(host, created.threadId, created.firstMessage) : {}
// A job the ledger keeps is the answer: the bot hears of a worktree that could not be set up in its job's notice.
const followed = firstSent && job && created.firstMessage?.sent === true && followJobSetup(created.threadId, created.firstMessage, job.job.jobId, ctx)
const setup = firstSent && created.firstMessage?.sent === true && !followed ? await setupOf(host, created.threadId, created.firstMessage) : {}
return json({
...told,
...setup,
Expand Down
Loading
Loading