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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- App: Room agents keep their own reasoning effort, and an agent without one inherits the run's default (#3514). Thanks to @AIFlowML.

- Tests: the Zig cache restat tests read `.lib_dir` from `zig env` instead of guessing a `lib` folder beside the executable, so they work with Homebrew Zig (#3786, fixes #3785). Thanks to @AIFlowML.

- `tensorfold web`: after a PATH miss, the launcher looks in uv's tool directory for an existing Web executable before offering an install; PATH still wins and installing still needs an explicit yes (#3748, fixes #3747). Thanks to @AIFlowML.
Expand Down
4 changes: 2 additions & 2 deletions app/electron/agent/delegation-route.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,15 +179,15 @@ async function run() {
// --- Source pins: both spawn paths route through the resolver ------------------------
{
const source = (rel: string) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf8')
const roomIpc = source('../main/host/workspace-runtime-ipc.ts')
const roomIpc = source('../main/host/room-tools-runtime.ts')
const delegateStart = roomIpc.indexOf('delegate: async (args, seat)')
const delegateEnd = roomIpc.indexOf('read_file: async', delegateStart)
assert.ok(delegateStart >= 0 && delegateEnd > delegateStart, 'room delegate tool remains discoverable')
const delegate = roomIpc.slice(delegateStart, delegateEnd)
assert.match(delegate, /resolveDelegationRoute\(store\.settings\.providers/, 'room delegate resolves the cross-model route')
assert.match(delegate, /!routed\.route\) return `Cannot delegate:/, 'route errors surface as tool errors, not crashes')
assert.match(delegate, /runReadOnlySubAgent\(created\.agent, prov, routed\.route\.model/, 'room delegate runs the sub-agent on the routed model')
assert.match(delegate, /parent: parentForRoomSeat\(room, s\)/, 'delegated sub-agent lineage stays under the delegating seat')
assert.match(delegate, /parent: parentForRoomSeat\(runtimeScope\.room, s\)/, 'delegated sub-agent lineage stays under the delegating seat')

const threadRuntime = source('../main/host/tool-context-runtime.ts')
assert.match(threadRuntime, /resolveDelegationRoute\(store\.settings\.providers/, 'thread sub-agent launcher resolves the cross-model route')
Expand Down
9 changes: 7 additions & 2 deletions app/electron/agent/delegation-route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Provider, Seat } from './types'
import type { Provider, ReasoningEffortSetting, Seat } from './types'
import { resolveProviderModel, selectProviderAccount } from './provider-accounts'

// Cross-model delegation routing (Traycer-style): a single spawn binds provider/account/model,
Expand All @@ -10,6 +10,7 @@ export interface DelegationRouteBase {
// "fall back to the active/default account" while null means "no account".
providerAccountId?: string | null
model: string
reasoningEffort?: ReasoningEffortSetting
}

export interface DelegationRouteOverride {
Expand Down Expand Up @@ -49,10 +50,14 @@ export function resolveDelegationRoute(
const seat = seats?.find((candidate) => candidate.name === targetSeat)
if (!seat) return { error: `unknown seat "${targetSeat}"` }
route = { providerId: seat.providerId, providerAccountId: seat.providerAccountId, model: seat.model }
if (seat.reasoningEffort !== undefined) route.reasoningEffort = seat.reasoningEffort
}
// A same-provider override keeps the inherited account; only a cross-provider switch
// resets it (the account id is meaningless on the new provider).
if (providerId && providerId !== route.providerId) route = { providerId, model: route.model }
if (providerId && providerId !== route.providerId) {
route = { providerId, model: route.model,
...(route.reasoningEffort === undefined ? {} : { reasoningEffort: route.reasoningEffort }) }
}
const provider = providers.find((candidate) => candidate.id === route.providerId)
if (!provider) return { error: `unknown provider "${route.providerId}"` }
if (localOnly && provider.kind !== 'local') return { error: `provider "${provider.name}" must be a local provider for this local-only project` }
Expand Down
20 changes: 20 additions & 0 deletions app/electron/agent/room-delegation-effort.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict'
import { resolveDelegationRoute } from './delegation-route'
import type { Provider, Seat } from './types'

const provider: Provider = { id: 'fixture', name: 'Fixture', kind: 'local', apiKey: '',
baseUrl: 'http://127.0.0.1:1/v1', models: ['first', 'second'] }
const other: Provider = { ...provider, id: 'other' }
const base = { providerId: provider.id, model: 'first', reasoningEffort: 'low' as const }
const seats: Seat[] = [
{ id: 'reviewer', name: 'Reviewer', role: 'Review input', providerId: provider.id, model: 'second', reasoningEffort: 'high' },
{ id: 'legacy', name: 'Legacy', role: 'Review input', providerId: provider.id, model: 'first' },
]
assert.deepEqual(resolveDelegationRoute([provider, other], base, {}).route, base)
assert.deepEqual(resolveDelegationRoute([provider, other], base, { targetSeat: 'Reviewer' }, seats).route,
{ providerId: provider.id, providerAccountId: undefined, model: 'second', reasoningEffort: 'high' })
assert.deepEqual(resolveDelegationRoute([provider, other], base, { targetSeat: 'Legacy' }, seats).route,
{ providerId: provider.id, providerAccountId: undefined, model: 'first' }, 'an inherited target does not adopt the origin agent override')
assert.deepEqual(resolveDelegationRoute([provider, other], base, { providerId: other.id, model: 'second' }).route,
{ providerId: other.id, model: 'second', reasoningEffort: 'low' }, 'explicit provider changes retain the originating effort')
console.log('Room delegation effort routing checks passed: origin, target agent, legacy target and explicit provider/model route.')
97 changes: 97 additions & 0 deletions app/electron/agent/room-heartbeats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
import type { RoomDeliberationEffort, Seat, SeatHeartbeat } from './types'

// Minimal shape the heartbeat helpers need — lets tests exercise stall detection
// without standing up a full SeatRuntime (messages/recent are irrelevant here).
export interface SeatRuntimeLike {
seat: Pick<Seat, 'id' | 'name'>
heartbeat: SeatHeartbeat
}

// Default grace after nextDueAt before a slow seat is flagged stalled (BUG #53).
// Tolerates transient model latency so a normal slow turn does not false-positive.
const SEAT_STALL_GRACE_SECONDS = 30

// Heartbeat cadence derived from the room deliberation effort. Deeper sessions
// expect longer per-turn thinking, so we widen the interval to avoid false stalls.
export function seatHeartbeatIntervalSeconds(effort?: RoomDeliberationEffort | null): number {
switch (effort) {
case 'quick': return 30
case 'deep': return 90
case 'max': return 120
case 'normal':
default: return 60
}
}

// Seed a healthy heartbeat for a seat at room start.
export function initSeatHeartbeat(seat: Pick<Seat, 'id' | 'name'>, intervalSeconds: number, now: number): SeatHeartbeat {
return {
seatId: seat.id,
seatName: seat.name,
intervalSeconds,
stallGraceSeconds: SEAT_STALL_GRACE_SECONDS,
required: true,
count: 0,
lastBeatAt: now,
nextDueAt: now + intervalSeconds * 1000,
missedSince: null,
}
}

// Record that a seat produced a turn: bump count, advance the clock, clear any stall.
export function recordSeatBeat(hb: SeatHeartbeat, now: number): void {
hb.count++
hb.lastBeatAt = now
hb.nextDueAt = hb.required ? now + hb.intervalSeconds * 1000 : null
hb.missedSince = null
}

// Names of seats currently flagged stalled (missedSince set), excluding one seat
// by name (the seat trying to FINAL is obviously alive). Used to block a premature
// finalize while a teammate is hung (BUG #53).
export function stalledSeatNames(runtimes: SeatRuntimeLike[], exclude?: string): string[] {
return runtimes
.filter((rt) => rt.heartbeat.required && rt.heartbeat.missedSince != null && rt.seat.name !== exclude)
.map((rt) => rt.seat.name)
}

// Re-arm the stall window for seats that actually took a turn in the previous pass.
// A single pass over several slow models can take longer than interval+grace, so a
// seat that beat last pass and is merely waiting its turn must not be false-flagged;
// pushing its nextDueAt forward to this pass start prevents that. Crucially, seats
// that did NOT run last pass (e.g. one that keeps timing out without ever calling
// recordSeatBeat, or any seat on the very first pass) are left untouched so their
// window keeps counting and evaluateSeatHeartbeats can actually flag a real stall —
// re-arming every non-stalled seat unconditionally is what made stall detection dead
// code (BUG #53 regression).
export function rearmSeatHeartbeats(
runtimes: SeatRuntimeLike[],
ranLastPass: Set<string>,
passStart: number,
): void {
for (const rt of runtimes) {
const hb = rt.heartbeat
if (hb.required && hb.missedSince == null && ranLastPass.has(rt.seat.id)) {
hb.nextDueAt = passStart + hb.intervalSeconds * 1000
}
}
}

// Detect seats whose turn is overdue past the grace window. Mutates each newly
// stalled heartbeat's missedSince so a stall is reported once (not every tick),
// and returns human-readable notices for the moderator to surface.
export function evaluateSeatHeartbeats(runtimes: SeatRuntimeLike[], now: number): string[] {
const stalled: string[] = []
for (const rt of runtimes) {
const hb = rt.heartbeat
if (!hb.required || hb.lastBeatAt == null || hb.nextDueAt == null) continue
if (hb.missedSince != null) continue // already flagged; do not re-report
const stallAt = hb.nextDueAt + hb.stallGraceSeconds * 1000
if (now >= stallAt) {
hb.missedSince = hb.nextDueAt
const ago = Math.round((now - hb.lastBeatAt) / 1000)
stalled.push(`Seat "${rt.seat.name}": heartbeat overdue (last beat ${ago}s ago)`)
}
}
return stalled
}
157 changes: 157 additions & 0 deletions app/electron/agent/room-protocol.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import type { Project, Provider, Room, RoomEventItem, Seat } from './types'
import { isExternalProvider } from '../../shared/provider-trust'
import { PROJECT_CONTEXT_WITHHELD_NOTE } from './planning-guard'
import { VONTRA_STYLE_PROMPT } from './prompt-style'
import { formatRoomMemory, seatCollaborationInstructions } from './room-collaboration'
import { roomModePromptBlock, roomOutcomeProfile } from './room-outcomes'
import { renderSharedMemory } from './shared-room-memory'

// Ported from LLMComposer's room/huddle engine: multiple provider-bound seats
// deliberate on one shared problem as an attributed dialogue, with SENSE
// injection so each seat knows it is one of several real teammates.

const VERBS = new Set(['SPEAK', 'ASK', 'OBJECT', 'ASSIGN', 'CLAIM', 'CHECK', 'VOTE', 'YIELD', 'FINAL', 'TOOL'])

export function buildPrimer(project: Project, room: Room, seat: Seat, roster: Seat[], provider?: Provider): string {
const rosterText = roster.map((s) => `- ${s.name}: ${s.role} (model ${s.model})`).join('\n')
const roomMemory = formatRoomMemory(room)
const sharedMemory = room.sharedMemory ? renderSharedMemory(room.sharedMemory) : ''
return [
`You are ${seat.name} in a live multi-agent working session with the teammates below.`,
'',
`ROOM ROLE\nYour visible room role is ${seat.role}. Use it to decide when to volunteer, challenge, defer, or take a ticket, but keep your general reasoning intact.`,
`\n${seatCollaborationInstructions(room, seat, provider)}`,
roomOutcomeProfile(room.mode) ? `\nROOM OUTCOME\n${roomModePromptBlock(roomOutcomeProfile(room.mode)!)}` : '',
project.team ? `\nTEAM CHARTER\n${project.team}` : '',
// External seats plan only and never see project memory (planning-guard.ts).
project.memory ? (isExternalProvider(provider) ? `\n${PROJECT_CONTEXT_WITHHELD_NOTE}` : `\nPROJECT MEMORY\n${project.memory}`) : '',
roomMemory ? `\nROOM MEMORY\n${roomMemory}` : '',
sharedMemory ? `\n${sharedMemory}` : '',
'',
'ROOM CONTRACT',
'Messages tagged [room] are what teammates actually said; [moderator] hands you the floor.',
'Speak in first person, briefly and concretely. React to what was just said instead of restating it.',
"Never write [room] or [moderator] lines yourself, and never invent a teammate's reply.",
'Never repeat a question or point you already made.',
'End every reply with exactly one line: ACTION: <VERB> <content>.',
'Verbs: SPEAK, ASK, OBJECT, ASSIGN, CLAIM, CHECK, VOTE, YIELD, FINAL, TOOL.',
'ACTION: ASK <teammate> <question> addresses one teammate by name. ACTION: FINAL <answer> ends the room only when the task is genuinely done.',
'When you answer a specific ASK or ASSIGN, cite it by appending RE: #<id> to your ACTION line so the reply links back to the question.',
'Only state what you can actually see in the [room] lines above. Do not claim progress that has not happened.',
'',
'TEAMWORK CONTRACT',
'Make handoffs explicit. If a teammate asks or assigns you something, answer that first and say what you are unblocking for them.',
'Help the room finish the user goal: create or claim concrete tickets, attach evidence, start workers when ready, and yield when waiting.',
'If you disagree, name the risk and offer the next useful move instead of reopening the whole plan.',
'',
VONTRA_STYLE_PROMPT,
'',
'SHARED BOARD: coordinate through it so you never duplicate a teammate\'s work:',
'ACTION: TOOL list_tickets: see every ticket and who is working on what.',
'ACTION: TOOL claim_ticket {"title":"..."}: claim a ticket BEFORE you start it, so teammates know it is taken.',
'ACTION: TOOL create_ticket {"title":"...","body":"...","priority":"high","risk":"medium","allowedCapabilities":["read"],"requiredEvidence":["files inspected","verification result"],"acceptanceCriteria":["..."]}: add an execution ticket to the board.',
'ACTION: TOOL add_ticket_evidence {"title":"...","kind":"file","summary":"What you found","ref":"src/file.ts"}: attach evidence to a claimed ticket.',
'ACTION: TOOL complete_ticket {"title":"...","evidence":[{"kind":"review","summary":"Reviewed X and found Y"}]}: mark your claimed ticket complete after attaching required evidence.',
'ACTION: TOOL left_to_work: see the remaining room tickets, active workers, risks, and known file refs.',
'ACTION: TOOL memory_write {"name":"decisions","content":"...","mode":"append-bullet"}: update the room\'s live shared memory (decisions, plan, blockers). Teammates see updates on their next turn.',
'ACTION: TOOL start_ticket_work {"title":"...","phase":"build","paths":["src/x.ts"]}: ask the Room Supervisor to start a ticket worker thread in the room worktree. Use phase "review" for reviewer passes. If a file overlap is intentional, include "mergeDecision":"why this overlap is safe and how results will be merged".',
'ACTION: TOOL delegate {"task":"..."}: hand a focused subtask to a sub-agent and get its result. Add "targetSeat":"SeatName" to run it on that seat\'s provider/model, or "providerId"/"accountId"/"model" for an explicit route; omit them to use your own.',
'Always claim before working; never touch a ticket already claimed by someone else.',
'Only start ticket workers for claimed or ready tickets. Declare paths when you know them so the supervisor can prevent overlapping edits.',
'Do not ACTION: FINAL while room tickets are still open.',
'',
'WORKSPACE: inspect the shared project safely:',
'ACTION: TOOL read_file {"path":"src/x.ts"}: read a file.',
'ACTION: TOOL search {"query":"..."}: find relevant code.',
'ACTION: TOOL list_dir {"path":"src"}: inspect folders.',
'Room agents are read-only by default. Do not attempt edit_file, write_file, or run_command unless the user opens an approved work thread for that ticket.',
'When you know the change needed, create/claim a ticket and explain the proposed edit for an approved thread to execute.',
'',
'TEAM ROSTER',
rosterText,
].filter(Boolean).join('\n')
}

export interface Action { verb: string; text: string; raw: string; prose?: string }

// Lenient gate: missing action becomes SPEAK, empty body becomes YIELD.
export function gateAction(output: string): Action {
const raw = (output ?? '').trim()
if (!raw) return { verb: 'YIELD', text: '', raw }
const lines = raw.split('\n')
const actionLine = [...lines].reverse().find((l) => l.trim().toUpperCase().startsWith('ACTION:'))
const prose = lines.filter((l) => l !== actionLine).join('\n').trim()
if (!actionLine) return { verb: 'SPEAK', text: prose || raw, raw }
const body = actionLine.trim().slice(actionLine.trim().indexOf(':') + 1).trim()
const parts = body.split(/\s+/)
const verb = (parts[0] || '').toUpperCase()
const text = parts.slice(1).join(' ').trim()
if (!VERBS.has(verb)) return { verb: 'SPEAK', text: prose || raw, raw }
if (!text && verb !== 'YIELD') return { verb: 'YIELD', text: '', raw }
// Keep the prose so peers receive the model's actual reasoning, not just the one-line ACTION tagline.
return { verb, text, raw, prose }
}

export function renderForRoom(ev: RoomEventItem, compact = false): string {
const label = ev.kind.toUpperCase()
// Addressed asks/assigns carry a short ref (#id8) so a teammate can answer with
// "RE: #<id>"; replies show the ref they answer (re #id8).
const ref = (ev.kind === 'ask' || ev.kind === 'assign') ? ` #${ev.id.slice(0, 8)}` : ''
const reply = ev.replyTo ? ` re #${ev.replyTo.slice(0, 8)}` : ''
if (compact) return `[room] ${ev.seat} (${label}${reply}): ${ev.text}`
const head = ev.target && ev.target !== 'all' && ev.target !== ev.seat
? `[room] ${ev.seat} (${label}, to ${ev.target}${ref}${reply}):`
: `[room] ${ev.seat} (${label}${ref}${reply}):`
return `${head}\n${ev.text}`
}

export function signature(raw: string): string {
return raw.split('\n').filter((l) => !l.trim().toUpperCase().startsWith('ACTION:')).join(' ').trim().toLowerCase().slice(0, 400)
}

export function blockerSignature(blockers: string[]): string {
return blockers.map((blocker) => blocker.replace(/\s+/g, ' ').trim().toLowerCase()).filter(Boolean).join('\n')
}

export function oneLine(text: string, max = 180): string {
const compact = text.replace(/\s+/g, ' ').trim()
return compact.length > max ? `${compact.slice(0, Math.max(0, max - 3))}...` : compact
}

export function roomTeamCue(room: Room, seat: Seat): string {
const recent = room.events.filter((event) => !['task', 'notice', 'user'].includes(event.kind)).slice(-10)
const directHandoffs = recent.filter((event) => (event.kind === 'ask' || event.kind === 'assign') && event.target === seat.name)
const latestDirect = directHandoffs[directHandoffs.length - 1]
const latestOtherHandoff = recent.filter((event) =>
(event.kind === 'ask' || event.kind === 'assign') &&
!!event.target &&
event.target !== 'all' &&
event.target !== seat.name
).slice(-1)[0]
const latestClaim = recent.filter((event) => event.kind === 'claim').slice(-1)[0]
const latestUserSteer = room.events
.filter((event) => event.kind === 'user' && (event.target === 'all' || event.target === seat.name))
.slice(-1)[0]
const cue: string[] = []

if (latestUserSteer) {
cue.push(`USER STEERING: "${oneLine(latestUserSteer.text, 220)}". Treat this as the user's latest direction and respond to it before lower-priority room chatter.`)
}

if (latestDirect) {
cue.push(`TEAM CUE: ${latestDirect.seat} handed work to you: "${oneLine(latestDirect.text, 220)}". Answer or unblock that first, naming ${latestDirect.seat}.`)
} else if (latestOtherHandoff) {
cue.push(`TEAM CUE: ${latestOtherHandoff.seat} handed work to ${latestOtherHandoff.target}. Let that teammate respond unless you can unblock with new evidence.`)
}

if (latestClaim) {
cue.push(`Latest claim: ${latestClaim.seat} claimed "${oneLine(latestClaim.text, 120)}". Build on it and do not duplicate it.`)
}

cue.push('Work like a teammate: reference who you are helping, answer direct asks before new topics, create or claim the next useful ticket, start workers when ready, and ACTION: YIELD if you are waiting.')
return cue.join(' ')
}

export function escapeReg(s: string): string {
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
Loading
Loading