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
12 changes: 9 additions & 3 deletions docs/designs/capability-requests.md
Original file line number Diff line number Diff line change
Expand Up @@ -744,9 +744,15 @@ to anyone, so the daemon offers it none of the three. They ride one D→C reques
level. The CP refuses any save or delete below that level itself, whichever daemon sends it.
- **Where it posts.** A new task in a chat conversation posts each run into that conversation unless the agent
says `postHere: false`; elsewhere it is headless. An edit keeps the cron's target unless told otherwise.
- **One-shot tasks.** `runAt` (an ISO-8601 instant with an offset, at least a minute ahead) is stored as the
wall-clock time in the cron's timezone (`2026-11-12T09:00:00`), which croner fires once. The CP deletes a
one-shot cron, with its run history, when its run's completion report arrives. Retirement is fenced twice:
- **Recurring only.** `saveSchedule` takes a cron expression that repeats; the daemon refuses a date-time
before the CP is asked. One thing at a set time is `followUp`'s (assistant-mode.md §5.12): it comes back to
the conversation that asked, with what was said there, and is listed and ended with that conversation's
tasks. Offering a second tool for the same request sent it to a fresh turn outside the conversation, listed
only with the agent's schedules.
- **One-shot crons.** `cron/self` still takes `runAt` (an ISO-8601 instant with an offset, at least a minute
ahead) from a daemon that predates the rule above, and one-shot crons saved earlier still fire. It is stored
as the wall-clock time in the cron's timezone (`2026-11-12T09:00:00`), which croner fires once. The CP
deletes a one-shot cron, with its run history, when its run's completion report arrives. Retirement is fenced twice:
the schedule's single moment must be at or before the reported fire, and the delete compares that
definition in the same transaction, so a save that lands in between wins and the new schedule keeps its own
later fire. A one-shot whose time passed while no daemon served it (beyond the scheduler's catch-up grace)
Expand Down
2 changes: 1 addition & 1 deletion evals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ Each of these replays a bad case that was fixed once, against a real subject. Th
| -------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------ |
| `evals/test/thread-chatter-real.test.ts` | #4186: answering people's untagged chatter after one tag | `.artifacts/evaluation/thread-chatter/summary.json` |
| `evals/test/webchat-addressed-real.test.ts` | #2865: a second webchat agent answering a post addressed to another | `.artifacts/evaluation/webchat-addressed/summary.json` |
| `evals/test/follow-up-choice-real.test.ts` | #4577: the wrong kind of follow-up, or one taken or ended unasked | `.artifacts/evaluation/follow-up-choice/summary.json` |
| `evals/test/follow-up-choice-real.test.ts` | #4577: a wrong follow-up or schedule, or one taken or ended unasked | `.artifacts/evaluation/follow-up-choice/summary.json` |
| `evals/test/webchat-night-collection-real.test.ts` | Night reports answered in prose instead of `sendMessage {sessionId}` | `.artifacts/evaluation/night-collection/summary.json` |

```bash
Expand Down
123 changes: 107 additions & 16 deletions evals/response-choice/follow-up-choice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { prepareGameSubject, preflightRealSubject, type GameSubjectSpec } from '
import { compileTopology } from '../games/topology.js'
import type { CompiledRoom } from '../games/types.js'
import { ArenaWorld } from '../games/world.js'
import type { AgentCronReq, AgentCronResult, AgentCronView } from '../../packages/protocol/src/index.js'

export type FollowUpMode = 'do' | 'remind' | 'watch'

Expand All @@ -25,6 +26,8 @@ export interface FollowUpLine {
followUp: FollowUpMode | 'none'
/** Whether `stopTask` is expected to be called in this message's turn; unset when either is fine, as when an agent replaces a follow-up it set wrongly. */
stopTask?: boolean
/** Whether `saveSchedule` is expected in this message's turn; unset, it is not. */
schedule?: boolean
}

const PERSON = 'U0ARENAUSRA'
Expand Down Expand Up @@ -69,6 +72,30 @@ export const FOLLOW_UP_SCENARIOS: Record<string, FollowUpLine[]> = {
{ text: REMIND_REPORT, followUp: 'remind' },
{ text: '{bot} also remind me tomorrow at 3pm UTC to call the vendor.', followUp: 'remind' },
{ text: '{bot} cancel the reminder.', followUp: 'none', stopTask: false }
],
// Work that repeats is a schedule: a follow-up comes back once.
'repeat-do': [
{
text: '{bot} every weekday at 9am UTC, count the files in your workspace and tell me here how many there are.',
followUp: 'none',
schedule: true
}
],
// A reminder that repeats is a schedule too: `remind` posts once.
'repeat-remind': [
{
text: '{bot} remind me every Monday at 9am UTC to send the weekly report.',
followUp: 'none',
schedule: true
}
],
// A short interval with an end is still a schedule, not a timer inside the runtime.
'repeat-short': [
{
text: '{bot} every 10 minutes for the next hour, count the files in your workspace and tell me here how many there are.',
followUp: 'none',
schedule: true
}
]
}

Expand All @@ -80,6 +107,7 @@ interface LineResult {
messageId: string
followUp: FollowUpMode | 'none'
stopTask?: boolean
schedule?: boolean
admitted: boolean
replies: string[]
}
Expand All @@ -89,6 +117,8 @@ export class FollowUpChoiceGame implements CollaborationGameWorld {
private readonly room: CompiledRoom
private readonly botToken: string
private readonly results: LineResult[] = []
// The agent's own schedules, held here in place of the Control Plane: saved, listed and deleted, never run.
private readonly schedules = new Map<string, AgentCronView>()
private root: string | undefined
private next = 0
private terminalReason: string | undefined
Expand All @@ -106,7 +136,38 @@ export class FollowUpChoiceGame implements CollaborationGameWorld {
if (botUserId === undefined) throw new Error('follow-up choice agent has no bot user id')
this.botToken = `<@${botUserId}>`
// Mention-bound, so the thread is the agent's own conversation session and never a coordinator's.
this.environment = world.buildEnvironment({ bindMatch: 'mention' })
this.environment = {
...world.buildEnvironment({ bindMatch: 'mention' }),
agentCron: async (request) => this.agentCron(request)
}
}

private agentCron(request: AgentCronReq): AgentCronResult {
if (request.op === 'list') return { status: 'ok', crons: [...this.schedules.values()] }
if (request.op === 'delete') {
this.schedules.delete(request.cronId)
return { status: 'ok' }
}
const { cron } = request
const known = cron.cronId !== undefined ? this.schedules.get(cron.cronId) : undefined
if (cron.cronId !== undefined && known === undefined)
return { status: 'refused', message: 'no such scheduled task' }
const saved: AgentCronView = {
cronId: known?.cronId ?? `00000000-0000-4000-8000-${String(this.schedules.size + 1).padStart(12, '0')}`,
name: cron.name ?? known?.name ?? null,
schedule: cron.schedule ?? known?.schedule ?? '',
timezone: cron.timezone,
once: false,
trigger: cron.trigger,
enabled: cron.enabled ?? true,
target:
cron.target === undefined
? (known?.target ?? null)
: cron.target && { platform: this.room.platform, ...cron.target },
lastRunAt: null
}
this.schedules.set(saved.cronId, saved)
return { status: 'ok', cron: saved }
}

isTerminal(): boolean {
Expand All @@ -128,6 +189,7 @@ export class FollowUpChoiceGame implements CollaborationGameWorld {
messageId,
followUp: line.followUp,
...(line.stopTask !== undefined ? { stopTask: line.stopTask } : {}),
...(line.schedule ? { schedule: true } : {}),
admitted: false,
replies: []
})
Expand Down Expand Up @@ -199,6 +261,7 @@ export class FollowUpChoiceGame implements CollaborationGameWorld {
messageId: line.messageId,
followUp: line.followUp,
...(line.stopTask !== undefined ? { stopTask: line.stopTask } : {}),
...(line.schedule ? { schedule: true } : {}),
admitted: line.admitted,
replied: line.replies.length > 0,
...(line.replies.length > 0 ? { reply: line.replies.join('\n').slice(0, 400) } : {})
Expand All @@ -217,10 +280,16 @@ export class FollowUpChoiceGame implements CollaborationGameWorld {
}
}

/** One AgentConnect tool call a turn made, by the tool's own name. */
/** One AgentConnect tool call a turn made, by the tool's own name, with `followUp`'s `mode`. */
export interface ObservedToolCall {
tool: string
mode?: string
/** The call ended in an error: refused, or made with arguments the tool does not take. */
failed?: boolean
}

function callMode(args: Record<string, unknown> | undefined): string | undefined {
return typeof args?.mode === 'string' ? args.mode : undefined
}

function record(value: unknown): Record<string, unknown> | undefined {
Expand Down Expand Up @@ -260,21 +329,27 @@ export function toolCallsByTurn(events: readonly unknown[]): Map<string, Observe
const turn = calls.get(event.turnId) ?? new Map<string, ObservedToolCall>()
calls.set(event.turnId, turn)
const seen = turn.get(callId)
const mode = callMode(args) ?? seen?.mode
const failed = update.status === 'failed' || (update.status === undefined && seen?.failed === true)
// A later update of the same call may carry the name or the arguments its first one lacked.
turn.set(callId, {
tool: label !== undefined ? ownToolName(label) : (seen?.tool ?? 'unknown'),
...(typeof args?.mode === 'string' ? { mode: args.mode } : seen?.mode !== undefined ? { mode: seen.mode } : {})
...(mode !== undefined ? { mode } : {}),
...(failed ? { failed } : {})
})
}
return new Map([...calls].map(([turnId, turn]) => [turnId, [...turn.values()]]))
}

const SCORED_TOOLS = new Set(['followUp', 'stopTask', 'saveSchedule'])

export interface FollowUpLineScore {
index: number
expected: { followUp: FollowUpMode | 'none'; stopTask?: boolean }
expected: { followUp: FollowUpMode | 'none'; stopTask?: boolean; schedule: boolean }
/** The modes `followUp` was called with in this line's turn, in call order. */
followUpModes: string[]
stopTaskCalls: number
scheduleCalls: number
/** Every other tool the turn called, by name: what the agent reached for instead. */
otherTools: string[]
replied: boolean
Expand All @@ -296,6 +371,10 @@ export interface FollowUpChoiceScore {
unwantedFollowUp: number
missedStop: number
unwantedStop: number
/** A schedule was expected and none was saved in that turn. */
missedSchedule: number
/** A schedule was saved where none was expected: work asked for once is a follow-up's. */
unwantedSchedule: number
missedReplies: number
}
}
Expand All @@ -314,16 +393,21 @@ export function scoreFollowUpChoice(verdict: GameVerdict, events: readonly unkno
const turnId = started.find((id) => id.endsWith(String(line.messageId)))
if (turnId === undefined) valid = false
const calls = turnId !== undefined ? (byTurn.get(turnId) ?? []) : []
const followUpModes = calls.filter((call) => call.tool === 'followUp').map((call) => call.mode ?? 'unknown')
const stopTaskCalls = calls.filter((call) => call.tool === 'stopTask').length
// A call that failed took, ended and saved nothing, as when an agent first calls a tool bare to read what it takes.
const taken = calls.filter((call) => !call.failed)
const followUpModes = taken.filter((call) => call.tool === 'followUp').map((call) => call.mode ?? 'unknown')
const stopTaskCalls = taken.filter((call) => call.tool === 'stopTask').length
const scheduleCalls = taken.filter((call) => call.tool === 'saveSchedule').length
// Names only: a runtime's display title can carry a path or a command.
const otherTools = [...new Set(calls.map((call) => call.tool))].filter(
(tool) => tool !== 'followUp' && tool !== 'stopTask' && /^[A-Za-z][A-Za-z0-9_]*$/.test(tool)
(tool) => !SCORED_TOOLS.has(tool) && /^[A-Za-z][A-Za-z0-9_]*$/.test(tool)
)
const expected = {
followUp: line.followUp as FollowUpMode | 'none',
...(typeof line.stopTask === 'boolean' ? { stopTask: line.stopTask } : {})
...(typeof line.stopTask === 'boolean' ? { stopTask: line.stopTask } : {}),
schedule: line.schedule === true
}
const scheduleMet = scheduleCalls > 0 === expected.schedule
const stopMet = expected.stopTask === undefined || stopTaskCalls > 0 === expected.stopTask
const modeMet =
expected.followUp === 'none'
Expand All @@ -335,9 +419,10 @@ export function scoreFollowUpChoice(verdict: GameVerdict, events: readonly unkno
expected,
followUpModes,
stopTaskCalls,
scheduleCalls,
otherTools,
replied,
met: modeMet && stopMet && replied
met: modeMet && stopMet && scheduleMet && replied
}
})
const count = (test: (line: FollowUpLineScore) => boolean) => lines.filter(test).length
Expand All @@ -355,6 +440,8 @@ export function scoreFollowUpChoice(verdict: GameVerdict, events: readonly unkno
unwantedFollowUp: count((line) => line.expected.followUp === 'none' && line.followUpModes.length > 0),
missedStop: count((line) => line.expected.stopTask === true && line.stopTaskCalls === 0),
unwantedStop: count((line) => line.expected.stopTask === false && line.stopTaskCalls > 0),
missedSchedule: count((line) => line.expected.schedule && line.scheduleCalls === 0),
unwantedSchedule: count((line) => !line.expected.schedule && line.scheduleCalls > 0),
missedReplies: count((line) => !line.replied)
}
}
Expand Down Expand Up @@ -402,6 +489,7 @@ export function scriptedFollowUpHostFactory(
else if (line !== undefined) {
if (line.followUp !== 'none') call(sessionId, 'followUp', { mode: line.followUp })
if (line.stopTask) call(sessionId, 'stopTask', { taskId: 'scripted' })
if (line.schedule) call(sessionId, 'saveSchedule', { schedule: '0 9 * * MON-FRI', timezone: 'UTC' })
}
onUpdate(sessionId, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'Noted.' } })
return { stopReason: 'end_turn' }
Expand Down Expand Up @@ -439,13 +527,16 @@ export async function runFollowUpChoice(options: FollowUpChoiceRunOptions): Prom
const game = new FollowUpChoiceGame(world, 'team-channel', options.lines)
const subject = prepareGameSubject(topology, subjectSpec)
try {
if (subjectSpec.kind === 'real' && options.agentDescription !== undefined) {
const agentPath = join(subject.root, 'agents', topology.agents[0]!.agentId, 'agent.json')
const agent = JSON.parse(readFileSync(agentPath, 'utf8')) as Record<string, unknown>
writeFileSync(agentPath, `${JSON.stringify({ ...agent, description: options.agentDescription }, null, 2)}\n`, {
mode: 0o600
})
}
// `saveSchedule` is offered only at the settings level, where a request has two tools to choose between.
const agentPath = join(subject.root, 'agents', topology.agents[0]!.agentId, 'agent.json')
const agent = JSON.parse(readFileSync(agentPath, 'utf8')) as Record<string, unknown>
const description =
subjectSpec.kind === 'real' && options.agentDescription !== undefined
? { description: options.agentDescription }
: {}
writeFileSync(agentPath, `${JSON.stringify({ ...agent, ...description, chatActions: 'settings' }, null, 2)}\n`, {
mode: 0o600
})
if (subjectSpec.kind === 'real') await preflightRealSubject(subject.root)
const runner = new CollaborationGameRunner({
root: subject.root,
Expand Down
14 changes: 11 additions & 3 deletions evals/test/follow-up-choice-real.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,15 @@ interface TrialRecord {
valid: boolean
errorCode?: string
metrics?: FollowUpChoiceScore['metrics']
/** Per line: the modes `followUp` was called with, how often `stopTask` was and the other tools' names; no message text. */
lines?: { index: number; followUpModes: string[]; stopTaskCalls: number; otherTools: string[]; met: boolean }[]
/** Per line: the modes `followUp` was called with, how often `stopTask` was, how often a schedule was saved and the other tools' names; no message text. */
lines?: {
index: number
followUpModes: string[]
stopTaskCalls: number
scheduleCalls: number
otherTools: string[]
met: boolean
}[]
}

const results: TrialRecord[] = []
Expand Down Expand Up @@ -71,10 +78,11 @@ describe.skipIf(!configured)('follow-up choice — real subject', () => {
// A line with no started turn (the runtime failed before the model ran) measured nothing.
...(result.error ? { errorCode: result.error.code } : score.valid ? {} : { errorCode: 'TURN_NOT_STARTED' }),
metrics: score.metrics,
lines: score.lines.map(({ index, followUpModes, stopTaskCalls, otherTools, met }) => ({
lines: score.lines.map(({ index, followUpModes, stopTaskCalls, scheduleCalls, otherTools, met }) => ({
index,
followUpModes,
stopTaskCalls,
scheduleCalls,
otherTools,
met
}))
Expand Down
40 changes: 40 additions & 0 deletions evals/test/follow-up-choice.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,46 @@ describe('reading tool calls from a run’s events', () => {
expect(calls.get('t2')).toEqual([{ tool: 'followUp' }, { tool: 'Read file' }])
})

it('counts a saved schedule, and leaves a failed call out of what a turn took', () => {
const events = [
{ type: 'turn.started', turnId: 'turn-1.000001' },
update('turn-1.000001', {
sessionUpdate: 'tool_call',
toolCallId: 'a',
title: 'mcp__agentconnect__saveSchedule'
}),
update('turn-1.000001', { sessionUpdate: 'tool_call_update', toolCallId: 'a', status: 'failed' }),
update('turn-1.000001', {
sessionUpdate: 'tool_call',
toolCallId: 'b',
title: 'mcp__agentconnect__saveSchedule',
rawInput: { schedule: '0 9 * * MON', timezone: 'UTC' }
}),
update('turn-1.000001', { sessionUpdate: 'tool_call_update', toolCallId: 'b', status: 'completed' })
]
expect(toolCallsByTurn(events).get('turn-1.000001')).toEqual([
{ tool: 'saveSchedule', failed: true },
{ tool: 'saveSchedule' }
])
const line = { index: 0, messageId: '1.000001', followUp: 'none', replied: true }
const verdict = (fields: Record<string, unknown>) => ({
terminalReason: 'completed',
refereeConsistent: true,
invariants: {},
metrics: {},
outcome: { lines: [{ ...line, ...fields }] }
})
expect(scoreFollowUpChoice(verdict({ schedule: true }), events).metrics).toMatchObject({ linesMet: 1 })
// The same save where nothing was to be scheduled.
expect(scoreFollowUpChoice(verdict({}), events).metrics).toMatchObject({ linesMet: 0, unwantedSchedule: 1 })
// Only the failed call: nothing was saved.
const bare = events.slice(0, 3)
expect(scoreFollowUpChoice(verdict({ schedule: true }), bare).metrics).toMatchObject({
linesMet: 0,
missedSchedule: 1
})
})

it('marks a trial invalid when a line’s turn is not in the events', () => {
const verdict = {
terminalReason: 'completed',
Expand Down
Loading