evOo-local/apps/api/src/thread-target.ts
cynarAI a35e431d1c
feat: main agent with a main conversation, user model and delegation (#101)
* feat(db): main agent, main conversation, user model and delegated task foundation

The product needs one main agent that leads a main conversation, knows the
user across spaces, and hands work to visible specialists. Today none of
that exists in the data model: "Chief" is a client-side naming convention,
the "Hauptthread" is a group the web client creates by name, and nothing
stores what the agents know about the user.

This adds the shared foundation the Phase 1 features build on:

- Bot.kind ("main" | "specialist", one main bot per user) plus capability
  fields (tags, builtin tool allowlist, model tier).
- ChatGroup.kind ("group" | "main", one main conversation per user) and
  ChatGroup.leadBotId.
- UserProfile and UserFact with category, confidence, source, consent
  status and per-space visibility; embeddings are stored as float arrays
  because none of the Postgres images ship pgvector.
- DelegatedTask for work the main bot hands to a specialist.
- SpaceModelTier to map a model tier to a connected model per space.

The migration backfills each user's onboarding bot in the home space as the
main bot and turns an existing "Hauptthread" group containing it into the
main conversation. CHECK and foreign key constraints on existing tables are
added NOT VALID and validated in a separate migration, as elsewhere in this
repo.

New db helpers ensure the main bot and the main conversation (idempotent and
race-safe, repairing a lost lead), add same-space specialists to the main
conversation and announce it with a group.updated event, and load the user
context a run may see. The main conversation is exempt from the two-member
floor and cannot have its members replaced through a group update. The
contracts expose the new fields and the user model and delegated task
schemas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* feat(adapters): every run knows who it is and who the user is, in the user's time zone

Runs dropped the bot's name, title and description whenever custom
instructions existed, always stated the time in UTC, and knew the user only
through free-form durable memory. Groups with a lead, like the main
conversation, still got the peer-group lines that forbid handing work back.
And every group follow-up run failed during setup: the inbound handoff lookup
selected a `bot` relation that Message does not have, which Prisma rejects.

- Instructions now open with the bot's identity, then its own instructions,
  a main-agent role paragraph for the main bot, the current time in the
  user's time zone with its offset (UTC when unknown), and a `<user>` block
  built from loadUserContext: profile fields and the active facts visible in
  the run's space, escaped, clipped and framed as data rather than
  instructions. Runs that reply in a shared messaging channel get only the
  name, zone, locale, language and style, matching how those runs already
  leave out durable memory.
- run_subagent helpers receive the identity, time and user block through a
  new optional AgentRunRequest.subagentContext instead of nothing.
- Groups with an active lead get lead and specialist lines and matching
  inbound handoff instructions. Members may hand a stage back to the lead and
  the lead may delegate the next stage; the bounce rules still apply between
  members. Ordinary groups keep today's lines.
- The teammate directory is rendered only when the run has message_bot, which
  group runs never have, and tool guidance names a tool only when the run has
  it.
- The auto-review judge, history compaction and the team chat judge read the
  time in the user's zone, and schedule_create defaults to it.
- The inbound handoff sender is read from the handoff block and looked up
  among the user's bots; a Postgres test covers the follow-up run, the prompt
  it receives, and handing the result back to the lead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* feat(memory): learn the user profile from conversations; add built-in semantic memory

Why: the user profile only knew what onboarding wrote, so people had to repeat themselves,
and semantic recall needed a hosted or separately run memory service. The profile now grows
from everyday conversations, and recall can run on the user's own server with a local
embeddings endpoint (for example llama.cpp). Both stay optional and are tested offline.

What:
- adapter-kit: EmbeddingProvider contract (describe, embed) and the profile.consolidate job
  (payload schema and a replace-keyed job factory, one pending job per user).
- adapters: OpenAI-compatible embeddings (POST {baseUrl}/embeddings through the guarded
  OpenAI-compatible fetch, batching, bounded responses, clear errors), a deterministic
  emulator, an in-process /v1/embeddings server emulator, and a shared conformance suite.
- adapters: "builtin" semantic memory stored in Postgres (semantic_memory_items with Float[]
  embeddings, cosine ranking in process, bot/shared/history scopes matching the existing
  providers), registered in the memory provider factory and configured through
  memory.connectProvider with an embeddings URL, model and optional API key. Private
  endpoints require the deployment owner, like the other local memory providers.
- adapters: profile consolidation reads the user's settled app conversations since
  UserProfile.consolidatedAt (never messaging channels), asks the main bot's model for strict
  JSON facts and an updated summary, drops restatements (embedding cosine when built-in
  memory is configured, normalized text otherwise), stores sensitive categories as pending,
  and advances the cursor with a compare-and-set. A reconciler hook enqueues it at most daily
  per active user; it skips under the scripted runtime and without a usable model.
- db: additive migration 20261002210400_ws4_semantic_memory.
- web: a "Built-in" option in Memory settings; AI data sharing names the embeddings server.

Tests: new embedding conformance, OpenAI-compatible wire, built-in provider and consolidation
unit tests; new Postgres suites for built-in memory (including a real loopback embeddings
server through the memory provider resolver) and for consolidation and its scheduling query,
both added to the integration harness. The settings E2E spec now opens the new form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* feat(models): map model tiers per space and let bots and helpers ask for one

A space can now map the tiers fast, standard and code to connected models,
including several models served by one OpenAI-compatible router endpoint
(one credential, many model ids). A bot can ask for a tier, and a single
run_subagent call can ask for one. A tier with no model mapped falls back
to the usual model choice, so nothing breaks before tiers are set up.

- db: SpaceModelTier repo (list, find, set or clear); tier mappings are
  copied into a new space like model and voice preferences; createBot
  carries a tier, so duplicates keep it and spawned bots inherit it.
- contracts/api: models.tiers.list and models.tiers.set;
  models.probeOpenAiCompatible can list a connected server's models by
  credential id with its stored address and key; bots.update accepts
  modelTier and keeps a pinned model and a tier mutually exclusive, so a
  model picked on a surface that knows no tiers (mobile) is never silently
  overridden. Thinking-level validation follows the tier's model. AI
  consent status discloses tier models; desktop local settings allow the
  tier procedures.
- adapters: selectConfiguredModel runs a mapped tier ahead of the pinned
  model and the space default; the executor resolves bot tiers for runs
  and model lookups, and helper tiers through resolveModelTier.
  run_subagent takes model_tier; an explicit model wins over it.
- web: a collapsed Tiers section in model settings (shown once a model is
  connected) and mapped tiers as choices in the bot Model select.
- docs: tiers in self-host model setup.
- tests: resolution order and fallbacks (selection, executor, Pi helper),
  repo, API and contract units, authorization and offline Pi Postgres
  suites, and a model-tiers web E2E spec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* fix(adapters): state the consolidation time in the user's zone; name the memory migration after its content

Profile consolidation now passes the profile's time zone to the shared time
instruction, which takes the zone since every run states the time in the
user's zone. The semantic memory migration is renamed after what it creates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* fix(adapters): keep the user's summary and facts out of replies to other owners' agents

An agent connection wakes a bot with another owner's message, and the reply
goes back to that owner. Such runs now get only the basics of the user block
(name, time zone, locale, language, style), like runs in shared messaging
channels, so confirmed facts such as health never reach another person's
agent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* feat(profile): readable, writable and forgettable user model

The main agent is meant to know the user, but nothing could read or change
the user model the foundation added. Onboarding pasted the user's answers
into the first bot's instructions as a "User Context" block, and the user
had no way to see or remove what their bots knew about them.

This makes the user model a user-controlled resource:

- db: a profile repository scoped by user. One atomic update writes the
  account name, profile fields, new facts (deduplicated by normalized
  text, capped per user), fact edits including per-space visibility, and
  confirmations. Health and values facts wait for confirmation unless the
  user wrote them. Forgetting hard-deletes facts by id, category or all,
  clears the summary that may restate them and marks earlier chats as
  consolidated so they cannot teach them again; forgetting everything also
  clears the profile fields. Writes take a per-user advisory lock.
- api/contracts: profile.get, profile.update and profile.forget. Unknown
  fact ids are a 404 on update and ignored on forget; spaces outside the
  user's memberships are rejected.
- adapters: an update_user_profile tool for the main bot only, hidden from
  specialists and shared messaging channels and refused if called anyway.
  Facts carry source "conversation" and the bot, thread and message they
  came from. The scripted runtime records "learn about me: [category:]
  statement" for tests.
- web: onboarding writes the name, time zone (browser default, now
  prefilled and editable), locale, chosen language, communication style
  and the hobby and work-style answers to the profile instead of
  overwriting the bot's instructions, and the harvested memory section no
  longer repeats them. A new "About you" settings section lists profile
  fields and facts by category with their origin, confirms pending facts,
  and forgets one fact or everything.

Tests cover the contracts, the repository (unit and PostgreSQL), tool
selection and refusal, the scripted trigger, the onboarding mapping and
view helpers, an API suite that runs the tool through the executor with a
real main bot, authorization for the new procedures, and an E2E spec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* feat(delegation): main bot hands work to specialists as tracked tasks

The main agent had no way to give a specialist a piece of work and keep
track of it. message_bot is a fire-and-forget peer message whose work stays
hidden from the user, and handoff_to_bot ends the main bot's turn and only
works between members of one group. Delegation now runs the specialist's
work where the user follows the main agent and brings the result back so
the main agent can close the task.

- delegate_task({bot, title, brief, deadline?}) is offered to the main bot
  only and refused unless the caller leads the main conversation. It
  resolves the specialist by id or name across the user's spaces, creates a
  DelegatedTask and posts a task card in the main conversation.
- A specialist from the main conversation's space joins it and works there
  in a run with the new trigger "delegation", which the peer filters do not
  hide, so its progress, asks and approvals appear in the main conversation
  with the specialist as sender. A specialist from another space works in
  its own chat; its written result is posted into the main conversation as
  its message.
- The executor mirrors the run on its task (running, waiting, done, failed,
  cancelled) after the run starts and when each attempt ends, and updates
  the card in place through thread.message.updated. Done and failed tasks
  wake the main bot in the main conversation with the result. The job
  reconciler settles tasks whose run ended without the executor (stop,
  clear, archive, deletion, crash).
- tasks.list({threadId?, status?}) returns the caller's tasks for the
  current space.
- The task card shows who, what and status with Lingui labels; the brief
  opens on demand. The message_bot card no longer shows the recipient's
  unrelated overall status or hard-coded German copy.
- The scripted runtime understands "delegate to the bot named X: ..." and
  the task wake prompt; activity rows name delegation runs by task title.

Tests: unit tests for the prompts, status mapping, card, reducer, tool
selection and scripted runtime; a Postgres suite for same-space, group,
other-space, ask and answer, failure, stop and replay; tasks.list in the
authorization suite; and an end-to-end spec for the whole flow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* fix(adapters): show the main agent the specialists it can delegate to

The main conversation is a group run, and group runs no longer list the
teammate directory, so the main agent could not see the names of the
specialists delegate_task expects. Runs that have delegate_task now list
the user's specialists across the spaces they belong to, those next to the
conversation first and others marked with their space, and that list
replaces the teammate directory so no bot appears twice. It also says when
to prefer delegate_task over handoff_to_bot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* feat(inbox): show what specialists need from the user in the main conversation

Specialists ask questions, request approvals and the computer screen in
their own threads, and the user only finds out by opening each thread. With
the main conversation as the single entry point, those requests have to
reach the user there, with the specialist as the visible sender.

- inbox.list returns, for the current space and the user's own bots, pending
  asks and approvals (bot messages with a pending ask block whose run waits
  for input), takeover requests, and unread specialist threads. Asks already
  in the main conversation are left out; takeovers stay because their
  controls live in the bot's own thread. Each item carries the bot, the
  thread target, run and message ids, and the ask block for asks and
  approvals.
- The main conversation shows the items above the composer. Asks and
  approvals are answered in place through threads.answer with the source
  thread target; takeovers and unread threads open the bot's thread. The
  list refreshes when the bots' status, unread state or newest message
  changes, every 15 seconds, and after an answer.
- The inbox shrinks and scrolls so it never pushes the composer out of view.
  The transcript now clips its scroller: with no room left in the column,
  the scroller's padding used to spill over whatever sat below it.
- The ask block schema is extracted from MessageBlock so the inbox contract
  reuses it, and AskCard accepts a className.

Tests: unit tests for the item builder and the component, a Postgres suite
for the query (added to the harness list), inbox cases in the authorization
suite, and an E2E spec in which a specialist asks in its own thread and the
user answers from the main conversation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* fix(adapters): write learned facts under the profile's lock and limit

Profile consolidation wrote facts beside the user profile repository: without
its per-user lock, its duplicate check at write time, or its limit of 500
facts. A long-running profile could grow past the limit and then refuse the
user's own additions. Consolidation now takes the same lock, drops facts the
profile gained since the run read it, and keeps only what still fits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* fix(adapters): keep profile writes out of replies to other owners' agents

A run woken over an agent connection hears another owner's bot, not the
user, so update_user_profile is withheld there: nothing such a conversation
says can become a fact about the user. Detection moves ahead of tool
selection; the reduced user block uses the same flag.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* feat(capabilities): least-privilege builtin tools per bot and schedules on behalf

Every bot saw every builtin tool, and nothing outside the runtime's own
declaration kept a run to the tools it was given: the executor ran any tool a
runtime asked for, and the Pi runtime exposed all builtins whenever a caller
passed an empty tool list, which the safety checker, the history summarizer
and the team chat judge do on purpose. A specialist could not be kept to the
tools of its lane, bots had no capability tags, and the main bot could only
schedule routines for itself.

- A bot can carry a builtin tool allowlist. Its runs see only the allowlisted
  builtins, and an empty allowlist means none. MAIN_ONLY_BUILTIN_TOOLS (empty
  until the user profile and delegation tools land) never reach other bots.
  applyTool refuses any tool the run did not expose, and an empty tool list
  now means no tools for the Pi runtime and its subagents.
- A bot spawned by a restricted bot inherits the restriction and a duplicate
  keeps it, so neither path widens a bot's tools.
- bots.create and bots.update accept tags, restrictBuiltinTools and
  allowedBuiltinTools; the router rejects names that are not builtin tools.
  bots.builtinTools lists the names a bot's allowlist can use.
- Bot settings get a Tags field and a switch with a tool checklist under
  Advanced.
- The main bot's schedule_create takes an optional bot: one of the user's
  bots in any space the user still belongs to. The routine belongs to that
  bot in its space and wakes in the main conversation when the bot is a
  member there, otherwise in its 1:1 thread. Routines record the bot that
  scheduled them (additive migration), so schedule_list and schedule_cancel
  also cover exactly the routines a bot scheduled for others. Cancelling by
  a name that matches several routines is refused.

Tested with unit tests for the per-bot filter, the applyTool guard, the empty
tool list, and on-behalf resolution, creation, listing and cancelling; with
Postgres journeys for on-behalf routines waking across spaces and in the main
conversation and for allowlist enforcement through the scripted runtime; and
with a web E2E for the settings section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* test(adapters): give the consolidation unit tests the profile lock

The write transaction now takes the per-user profile lock, so the mocked
client answers the lock query, and the first case checks the lock is taken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* feat(adapters): run profile consolidation on the fast tier when one is mapped

Fact extraction is short structured work, so consolidation asks the model
resolver for the fast tier. The resolver takes a per-call tier and, when the
space has not mapped it, keeps the bot's own tier or model as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

* feat: land in the main conversation, led by the main bot

After onboarding the user ended up in a 1:1 chat with "Chief", and the
"Hauptthread" was a group the web client created and found by name. The
main bot had no conversation it actually led, and addressing another bot
there did nothing unless the user had added it as a member first.

Now the main conversation is a real place:

- bots.ensureMain creates or returns the main bot. Bootstrap and space
  navigation return `main` ({ botId, groupId, spaceId }) once the main
  bot exists; reading navigation never creates a bot.
- The main bot leads the main conversation and answers when nobody is
  addressed: message routing, follow-ups, reactions and clearing the
  thread fall back to the group's lead instead of its first member.
- Addressing a same-space bot that is not a member yet, by @Name or a
  mention chip, makes it join before the message is routed, so it
  answers in the conversation. Specialists from other spaces do not join.
- The main bot cannot be archived or deleted, the main conversation
  cannot be archived or deleted or have its members edited, and child
  bots never dissolve it. Renaming the main bot renames the conversation.
- Web: onboarding uses bots.ensureMain and finishes in the main
  conversation. The main conversation is the first sidebar entry in every
  space, shown with the main bot's avatar and name; from another space it
  switches back to the home space. The main bot is not listed again among
  the bots, its 1:1 thread stays reachable by URL. The client no longer
  creates or detects the "Hauptthread" by name, refetches a group when it
  changes, and shows the speaker of any of the user's bots in a group.
- Onboarding no longer resets the step when its bootstrap resolves after
  the user has already moved on, and new spaces open in the app instead
  of walking onboarding again.

Tests: group mention routing with a default responder, lead follow-ups,
child-bot guards, a journey for the main conversation (lead answers,
addressed bot joins, guards, rename), authorization for bots.ensureMain,
and an E2E spec that lands in the main conversation, gets an answer from
the lead, sees an addressed bot join, and reaches the conversation from
another space. Existing E2E specs start in the main bot's thread through
a helper or use the main conversation where that is what they test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MRtGG9ARfqqhma3t85Ro2u

---------

Co-authored-by: cynarAI <cynarAI@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 06:44:20 +02:00

1293 lines
44 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { ORPCError } from "@orpc/server";
import { type JobPublisher, runContinueJob, type SandboxProvider } from "@rakazo/adapter-kit";
import { cancelComputerRunWork, screenLeaseIdForRun, toComputerRef } from "@rakazo/adapters";
import {
type Actor,
GROUP_MEMBER_MIN,
type GroupKind,
type GroupMember,
type MessageBlock,
type MessageReaction,
REPLY_QUOTE_MAX_LENGTH,
type RunStatus,
type ThreadSnapshot,
} from "@rakazo/contracts";
import {
ACTIVE_RUN_STATUSES,
blocksToAgentHistoryText,
isActive,
projectMessages,
resolveGroupTargetBotIds,
runFailureError,
} from "@rakazo/core";
import {
appendEventInTransaction,
createGroupRepos,
createRepos,
createThreadMessageInTransaction,
expireComputerExecutionLeases,
IsolationError,
lockOwnedGroup,
type Prisma,
type PrismaClient,
type ThreadEvents,
touchGroupUpdatedAt,
} from "@rakazo/db";
import { getLogger } from "@rakazo/logging";
import {
buildSendPrompt,
buildUserMessageBlocks,
resolveGroupSendAttachments,
resolveSendAttachments,
} from "./artifacts.js";
import { resolveBusyBotName, toComputerStatus } from "./computer-status.js";
import { joinAddressedBots } from "./main-conversation.js";
import { withSerializableRetry } from "./serializable-retry.js";
import { loadMessagePage } from "./thread-message-pages.js";
export type ThreadTarget =
| {
kind: "bot";
botId: string;
threadId: string;
bot: Awaited<ReturnType<ReturnType<typeof createRepos>["getBot"]>>;
}
| {
kind: "group";
groupId: string;
threadId: string;
groupName: string;
groupKind: GroupKind;
/** Answers when nobody is addressed; null for ordinary groups. */
leadBotId: string | null;
members: GroupMember[];
memberBotIds: string[];
};
/** The member that answers when nobody is addressed: the group's lead, else its first member. */
export function groupDefaultBotId(target: Extract<ThreadTarget, { kind: "group" }>) {
return target.leadBotId && target.memberBotIds.includes(target.leadBotId)
? target.leadBotId
: target.memberBotIds[0];
}
/**
* Flatten text for excerpt comparison. The parent blocks hold markdown
* source while the selection captures rendered text, so structural syntax
* is normalized away: table delimiters and alignment rows, list markers,
* heading and blockquote markers, link targets, emphasis characters.
* Semantic punctuation (: + - . ! #) stays on both sides — otherwise
* "C++ is fast" would accept a fabricated "C is fast".
*/
function flattenForQuoteMatch(text: string, markdownSource = false): string {
let fence: { marker: string; quoteDepth: number } | undefined;
return text
.split("\n")
.filter((line) => !/^\s*\|?[\s:|-]+\|?\s*$/.test(line))
.map((line) => {
const normalized = line
.replace(/^\s*(?:>\s*)+/, "")
.replace(/^\s*#{1,6}\s+/, "")
.replace(/^\s*[-*+•]\s+/, "");
if (!markdownSource) return normalized;
if (fence) {
let boundary = line;
const quoteDepth = fence.quoteDepth;
for (let depth = 0; depth < quoteDepth; depth++) {
const prefix = /^ {0,3}>[ \t]?/.exec(boundary)?.[0];
if (!prefix) {
fence = undefined;
break;
}
boundary = boundary.slice(prefix.length);
}
if (fence) {
const closing = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(boundary)?.[1];
if (closing && closing[0] === fence.marker[0] && closing.length >= fence.marker.length) {
fence = undefined;
}
return normalized;
}
}
let source = line;
let quoteDepth = 0;
for (
let prefix = /^ {0,3}>[ \t]?/.exec(source)?.[0];
prefix;
prefix = /^ {0,3}>[ \t]?/.exec(source)?.[0]
) {
source = source.slice(prefix.length);
quoteDepth++;
}
const match = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(source);
const marker = match?.[1];
const suffix = match?.[2] ?? "";
if (marker && (marker[0] !== "`" || !suffix.includes("`"))) {
fence = { marker, quoteDepth };
return normalized;
}
// Test source syntax before stripping headings or other visible containers.
return /^ {0,3}\d{1,9}[.)][ \t]+/.test(source)
? normalized.replace(/^ {0,3}\d{1,9}[.)][ \t]+/, "")
: normalized;
})
.join(" ")
.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.toLowerCase()
.replace(/&nbsp;/g, " ")
.replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&#0?39;|&apos;/g, "'")
.replace(/[‘’]/g, "'")
.replace(/[“”]/g, '"')
.replace(/[\\`*_~|[\]()•]/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function quoteAppearsInBlocks(quote: string, blocks: MessageBlock[]): boolean {
const excerpt = flattenForQuoteMatch(quote);
if (!excerpt) return false;
const parent = blocksToAgentHistoryText(blocks);
// Keep existing matches (including visible numbering in code) before removing list syntax.
return (
flattenForQuoteMatch(parent).includes(excerpt) ||
flattenForQuoteMatch(parent, true).includes(excerpt)
);
}
const THREAD_MESSAGE_PAGE_SIZE = 100;
const RUNS_NEEDING_CONTINUE = new Set(["queued", "waiting_takeover"]);
const STEERABLE_RUN_STATUSES = new Set(["queued", "leased", "running", "waiting_takeover"]);
type MentionTargetInput = string | { kind: "bot" | "group" | "routine" | "connector"; id: string };
function splitMentionTargets(mentions: MentionTargetInput[] | undefined) {
const botMentionIds = new Set<string>();
const groupMentionIds = new Set<string>();
const routineMentionIds = new Set<string>();
const connectorMentionIds = new Set<string>();
for (const mention of mentions ?? []) {
if (typeof mention === "string") {
botMentionIds.add(mention);
continue;
}
if (mention.kind === "bot") botMentionIds.add(mention.id);
if (mention.kind === "group") groupMentionIds.add(mention.id);
if (mention.kind === "routine") routineMentionIds.add(mention.id);
if (mention.kind === "connector") connectorMentionIds.add(mention.id);
}
return {
botMentionIds: [...botMentionIds],
groupMentionIds: [...groupMentionIds],
routineMentionIds: [...routineMentionIds],
connectorMentionIds: [...connectorMentionIds],
};
}
async function resolveOwnedConnectorDisplayNames(
tx: Prisma.TransactionClient,
actor: Actor,
connectionIds: string[],
) {
if (!connectionIds.length) return [];
const rows = await tx.connection.findMany({
where: {
id: { in: connectionIds },
spaceId: actor.spaceId,
userId: actor.userId,
status: "connected",
},
select: { id: true, displayName: true },
});
if (rows.length !== connectionIds.length) throw new IsolationError();
const byId = new Map(rows.map((row) => [row.id, row.displayName]));
return connectionIds.map((id) => byId.get(id) ?? "connector");
}
function sendRunClientNonce(
clientNonce: string | undefined,
messageId: string,
botId?: string,
): string | undefined {
if (!clientNonce) return undefined;
return botId ? `send:${messageId}:${botId}` : `send:${messageId}`;
}
async function enqueueRunsNeedingContinue(
jobs: JobPublisher,
runs: Array<{ id: string; status: string }>,
) {
await Promise.all(
runs
.filter((run) => RUNS_NEEDING_CONTINUE.has(run.status))
.map((run) =>
jobs.enqueue(runContinueJob(run.id)).catch((error) => {
// The queued run is durable; the reconciler repairs a missed immediate wake.
getLogger().error("thread send enqueue", error);
}),
),
);
}
async function findSendReceipt(prisma: PrismaClient, threadId: string, clientNonce: string) {
return prisma.message.findUnique({
where: { threadId_clientNonce: { threadId, clientNonce } },
include: { sourceRuns: { orderBy: [{ createdAt: "asc" }, { id: "asc" }] } },
});
}
async function replayExistingSend(
deps: { prisma: PrismaClient; events: ThreadEvents; jobs: JobPublisher },
threadId: string,
clientNonce: string | undefined,
) {
if (!clientNonce) return null;
const message = await findSendReceipt(deps.prisma, threadId, clientNonce);
if (!message) return null;
const receiptEvent = await deps.prisma.event.findFirst({
where: {
threadId,
type: "thread.message.created",
payload: { path: ["messageId"], equals: message.id },
},
orderBy: { seq: "desc" },
select: { payload: true },
});
const receiptRunIds = sendEventRunIds(receiptEvent?.payload);
const receiptRuns = receiptRunIds.length
? await deps.prisma.run.findMany({ where: { id: { in: receiptRunIds } } })
: [];
const receiptRunById = new Map(receiptRuns.map((run) => [run.id, run]));
const orderedReceiptRuns = receiptRunIds.flatMap((id) => {
const run = receiptRunById.get(id);
return run ? [run] : [];
});
const linkedRun =
message.sourceRuns[0] ??
(message.runId ? await deps.prisma.run.findUnique({ where: { id: message.runId } }) : null);
if (!linkedRun && orderedReceiptRuns.length === 0) return null;
const runs = orderedReceiptRuns.length
? orderedReceiptRuns
: message.sourceRuns.length
? message.sourceRuns
: [linkedRun!];
await enqueueRunsNeedingContinue(deps.jobs, runs);
const latestEvent = await deps.prisma.event.findFirst({
where: { threadId },
orderBy: { seq: "desc" },
select: { seq: true },
});
if (latestEvent) {
await deps.events.notify(threadId, latestEvent.seq).catch((error) => {
// Subscribers catch up from the durable event cursor after a missed realtime wake.
getLogger().error("thread send realtime notification", error);
});
}
return sendResult(message, runs);
}
function sendEventRunIds(payload: Prisma.JsonValue | undefined): string[] {
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return [];
const runIds = (payload as { runIds?: unknown }).runIds;
return Array.isArray(runIds) ? runIds.filter((id): id is string => typeof id === "string") : [];
}
function sendResult(message: { seq: number }, runs: Array<{ id: string; taskId: string }>) {
const first = runs[0];
if (!first) throw new IsolationError("Send did not create a run");
return {
taskId: first.taskId,
runId: first.id,
seq: message.seq,
runIds: runs.map((run) => run.id),
};
}
export async function cancelSupersededQueuedRuns(
tx: Prisma.TransactionClient,
input: { threadId: string; botIds: string[]; keepRunIds: string[] },
) {
const superseded = await tx.run.findMany({
where: {
threadId: input.threadId,
botId: { in: input.botIds },
status: "queued",
OR: [{ trigger: "user", sourceMessage: { role: "user" } }, { trigger: "reaction" }],
id: { notIn: input.keepRunIds },
},
select: { id: true, taskId: true },
});
if (superseded.length === 0) return;
const now = new Date();
await tx.run.updateMany({
where: { id: { in: superseded.map((run) => run.id) } },
data: { status: "cancelled", completedAt: now },
});
await tx.task.updateMany({
where: { id: { in: superseded.map((run) => run.taskId) } },
data: { status: "cancelled" },
});
}
async function lockAndLoadGroupMembers(
tx: Prisma.TransactionClient,
actor: Actor,
target: Extract<ThreadTarget, { kind: "group" }>,
) {
await lockOwnedGroup(tx, actor, target.groupId);
const group = await tx.chatGroup.findFirst({
where: {
id: target.groupId,
spaceId: actor.spaceId,
userId: actor.userId,
archivedAt: null,
thread: { id: target.threadId },
},
include: {
members: {
where: { bot: { archivedAt: null } },
include: { bot: { select: { id: true, name: true, color: true } } },
orderBy: { createdAt: "asc" },
},
},
});
// The main conversation starts with only its lead.
const minimum = group?.kind === "main" ? 1 : GROUP_MEMBER_MIN;
if (!group || group.members.length < minimum) throw new IsolationError();
return group.members.map((member) => ({
botId: member.bot.id,
name: member.bot.name,
color: member.bot.color,
}));
}
export async function resolveThreadTarget(
prisma: PrismaClient,
actor: Actor,
input: { botId?: string; groupId?: string },
): Promise<ThreadTarget> {
const repos = createRepos(prisma);
const groupRepos = createGroupRepos(prisma);
if (input.botId) {
const bot = await repos.getBot(actor, input.botId);
if (!bot.thread) throw new IsolationError();
return {
kind: "bot",
botId: bot.id,
threadId: bot.thread.id,
bot,
};
}
if (input.groupId) {
const group = await groupRepos.getGroupTarget(actor, input.groupId);
if (!group.thread) throw new IsolationError();
const members = group.members.map((member) => ({
botId: member.bot.id,
name: member.bot.name,
color: member.bot.color,
status: member.bot.runs[0]?.status ?? "idle",
}));
return {
kind: "group",
groupId: group.id,
threadId: group.thread.id,
groupName: group.name,
groupKind: group.kind === "main" ? "main" : "group",
leadBotId: group.leadBotId,
members,
memberBotIds: members.map((member) => member.botId),
};
}
throw new IsolationError();
}
export async function threadHead(prisma: PrismaClient, target: ThreadTarget) {
const latest = await prisma.event.findFirst({
where: { threadId: target.threadId },
orderBy: { seq: "desc" },
select: { seq: true },
});
return { threadId: target.threadId, cursor: latest?.seq ?? -1 };
}
export async function threadSnapshot(
deps: { prisma: PrismaClient },
target: ThreadTarget,
): Promise<ThreadSnapshot> {
// Lock the thread row so messages, the event cursor, active runs, and live
// progress are read from one consistent commit. A torn Promise.all can
// otherwise advance the client cursor past thread.message.created while the
// ask message page still omits it — leaving waiting_input with no AskCard.
if (target.kind === "bot") {
const [busyBotName, core] = await Promise.all([
resolveBusyBotName(deps.prisma, {
computerId: target.bot.computer?.id,
botId: target.botId,
botName: target.bot.name,
}),
deps.prisma.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM threads WHERE id = ${target.threadId} FOR SHARE`;
const [messagePage, last, waitingRun, busyOrFailed] = await Promise.all([
loadMessagePage(tx, target.threadId, undefined, THREAD_MESSAGE_PAGE_SIZE),
tx.event.findFirst({
where: { threadId: target.threadId },
orderBy: { seq: "desc" },
select: { seq: true },
}),
// Waiting asks win over a concurrent busy run (including peer bot_message).
tx.run.findFirst({
where: {
botId: target.botId,
threadId: target.threadId,
status: { in: ["waiting_input", "waiting_takeover"] },
},
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
}),
tx.run.findFirst({
where: {
botId: target.botId,
threadId: target.threadId,
// Hide peer bot_message busy/failed noise; waiting is handled above.
trigger: { not: "bot_message" },
status: { in: [...ACTIVE_RUN_STATUSES, "failed"] },
},
// The id tiebreak keeps ordering deterministic under equal
// timestamps, matching the supersession probe below.
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
}),
]);
const run = waitingRun ?? busyOrFailed;
// A failed run is only the thread's word while it is still the newest
// terminal run; otherwise a stale failure would resurface in the
// composer error strip on every load, forever. Instead of comparing
// timestamps (equal createdAt values reverse under gt/gte), ask for
// the newest terminal run under the same deterministic ordering and
// check whether it is this failure.
const newestTerminal =
run?.status === "failed"
? await tx.run.findFirst({
where: {
botId: target.botId,
threadId: target.threadId,
// Peer bot_message failures must not bury a user-visible failure.
trigger: { not: "bot_message" },
status: { in: ["failed", "completed", "cancelled"] },
},
orderBy: [{ createdAt: "desc" }, { id: "desc" }],
select: { id: true },
})
: null;
const currentRun = run?.status === "failed" && newestTerminal?.id !== run.id ? null : run;
const liveEvents =
currentRun && isActive(currentRun.status as RunStatus)
? await tx.event.findMany({
where: {
threadId: target.threadId,
runId: currentRun.id,
type: {
in: [
"thread.progress",
"thread.subagent",
"agent.tool.called",
"agent.tool.completed",
],
},
},
orderBy: { seq: "asc" },
})
: [];
return { messagePage, last, run: currentRun, liveEvents };
}),
]);
return {
botId: target.botId,
threadId: target.threadId,
cursor: core.last?.seq ?? -1,
messages: messagesWithLiveEvents(core.messagePage.messages, core.liveEvents),
olderCursor: core.messagePage.olderCursor,
run: core.run ? mapRun(core.run) : null,
computer: toComputerStatus(target.botId, target.bot.computer, busyBotName),
};
}
const core = await deps.prisma.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM threads WHERE id = ${target.threadId} FOR SHARE`;
const [messagePage, last, activeRuns, recentTerminals] = await Promise.all([
loadMessagePage(tx, target.threadId, undefined, THREAD_MESSAGE_PAGE_SIZE),
tx.event.findFirst({
where: { threadId: target.threadId },
orderBy: { seq: "desc" },
select: { seq: true },
}),
tx.run.findMany({
where: {
threadId: target.threadId,
status: { in: [...ACTIVE_RUN_STATUSES] },
// Include waiting peer runs so their ask cards stay answerable.
OR: [
{ trigger: { not: "bot_message" } },
{ status: { in: ["waiting_input", "waiting_takeover"] } },
],
},
orderBy: { createdAt: "desc" },
}),
// Recently updated terminals (completion bumps updatedAt). pickLatestTerminalRun then
// ranks by completedAt ?? createdAt so null timestamps cannot revive a stale failure.
tx.run.findMany({
where: {
threadId: target.threadId,
trigger: { not: "bot_message" },
status: { in: ["failed", "completed", "cancelled"] },
},
orderBy: [{ updatedAt: "desc" }, { id: "desc" }],
take: 50,
}),
]);
const liveEvents =
activeRuns.length > 0
? await tx.event.findMany({
where: {
threadId: target.threadId,
runId: { in: activeRuns.map((run) => run.id) },
type: {
in: [
"thread.progress",
"thread.subagent",
"agent.tool.called",
"agent.tool.completed",
],
},
},
orderBy: { seq: "asc" },
})
: [];
return {
messagePage,
last,
activeRuns,
terminalRun: pickLatestTerminalRun(recentTerminals),
liveEvents,
};
});
const primaryActiveRun = pickPrimaryActiveRun(core.activeRuns);
return {
groupId: target.groupId,
groupName: target.groupName,
members: target.members,
...(target.leadBotId ? { leadBotId: target.leadBotId } : {}),
threadId: target.threadId,
cursor: core.last?.seq ?? -1,
messages: messagesWithLiveEvents(core.messagePage.messages, core.liveEvents),
olderCursor: core.messagePage.olderCursor,
// Match the live reducer: a failed latest terminal stays in run even while siblings are
// still active or start late. A newer completed/cancelled terminal clears it.
run:
core.terminalRun?.status === "failed"
? mapRun(core.terminalRun)
: primaryActiveRun
? mapRun(primaryActiveRun)
: null,
activeRuns: core.activeRuns.map(mapRun),
};
}
/**
* Prefer a waiting ask/takeover over a merely-busy run for the group's headline
* `run` field, even when the busy run started more recently — createdAt-desc
* ordering alone would let a fresh busy run for one bot bury an older waiting
* card for another. `activeRuns` still carries every active run regardless of
* which one is picked here, so nothing is hidden from the client, only the
* single-run summary field.
*/
function pickPrimaryActiveRun<T extends { status: string }>(runs: readonly T[]): T | undefined {
return (
runs.find((run) => run.status === "waiting_input" || run.status === "waiting_takeover") ??
runs[0]
);
}
/** Latest terminal by end time (completedAt, else createdAt), then createdAt, then id. */
function pickLatestTerminalRun<T extends { id: string; createdAt: Date; completedAt: Date | null }>(
runs: T[],
): T | null {
if (runs.length === 0) return null;
return runs.reduce((best, run) => {
const bestEnd = (best.completedAt ?? best.createdAt).getTime();
const runEnd = (run.completedAt ?? run.createdAt).getTime();
if (runEnd !== bestEnd) return runEnd > bestEnd ? run : best;
if (run.createdAt.getTime() !== best.createdAt.getTime()) {
return run.createdAt > best.createdAt ? run : best;
}
return run.id > best.id ? run : best;
});
}
function messagesWithLiveEvents(
persisted: ThreadSnapshot["messages"],
liveEvents: Parameters<typeof projectMessages>[0],
) {
const live = projectMessages(liveEvents).filter((message) => {
if (message.blocks.some((block) => block.kind === "progress" || block.kind === "steps")) {
return true;
}
if (!message.id.startsWith("subagent:")) return false;
return !persisted.some((row) =>
row.blocks.some(
(block) => block.kind === "subagent" && message.id === `subagent:${block.agentId}`,
),
);
});
return [...persisted, ...live];
}
function mapRun(run: {
id: string;
botId: string;
threadId: string;
taskId: string;
status: string;
trigger: string;
routineId: string | null;
modelProvider: string | null;
modelId: string | null;
error: string | null;
startedAt: Date | null;
completedAt: Date | null;
createdAt: Date;
}) {
return {
id: run.id,
botId: run.botId,
threadId: run.threadId,
taskId: run.taskId,
status: run.status as never,
trigger: run.trigger as never,
routineId: run.routineId ?? null,
modelProvider: run.modelProvider,
modelId: run.modelId,
// Same display clamp as live run.failed events so a huge stored error cannot bypass it.
error:
run.status === "failed"
? runFailureError({ type: "run.failed", payload: { error: run.error } })
: run.error,
startedAt: run.startedAt?.toISOString() ?? null,
completedAt: run.completedAt?.toISOString() ?? null,
createdAt: run.createdAt.toISOString(),
};
}
export async function sendThreadMessage(
deps: {
prisma: PrismaClient;
events: ThreadEvents;
jobs: JobPublisher;
},
actor: Actor,
target: ThreadTarget,
input: {
text?: string;
artifactIds?: string[];
mentions?: MentionTargetInput[];
replyToMessageId?: string;
replyQuote?: string;
clientNonce?: string;
},
) {
const existing = await replayExistingSend(deps, target.threadId, input.clientNonce);
if (existing) return existing;
if (target.kind === "group" && target.groupKind === "main") {
await joinAddressedBots(deps.prisma, actor, {
memberBotIds: target.memberBotIds,
text: input.text ?? "",
botMentionIds: splitMentionTargets(input.mentions).botMentionIds,
});
}
// The excerpt is rendered text while blocks hold markdown source, so it
// can't be substring-verified verbatim — enforce the cap here, then check
// the flattened form against the parent inside the transaction.
let replyQuote = input.replyQuote?.trim().slice(0, REPLY_QUOTE_MAX_LENGTH) || undefined;
if (replyQuote && !input.replyToMessageId) {
throw new ORPCError("BAD_REQUEST", { message: "replyQuote requires replyToMessageId." });
}
const commit = () =>
deps.prisma.$transaction(async (tx) => {
if (input.replyToMessageId) {
const reply = await tx.message.findFirst({
where: { id: input.replyToMessageId, threadId: target.threadId },
select: { id: true, blocks: true },
});
if (!reply) throw new IsolationError();
// Client-supplied excerpts are untrusted: drop a mismatch instead of
// failing the send — the reply still lands, just without the quote.
if (
replyQuote &&
!quoteAppearsInBlocks(
replyQuote,
Array.isArray(reply.blocks) ? (reply.blocks as MessageBlock[]) : [],
)
) {
replyQuote = undefined;
}
}
if (target.kind === "bot") {
const mentionTargets = splitMentionTargets(input.mentions);
const { blocks: attachmentBlocks, artifacts } = await resolveSendAttachments(
{ prisma: tx },
actor,
target.botId,
input.artifactIds,
);
const connectorNames = await resolveOwnedConnectorDisplayNames(
tx,
actor,
mentionTargets.connectorMentionIds,
);
const blocks = buildUserMessageBlocks(input.text, attachmentBlocks);
const message = await createThreadMessageInTransaction(tx, {
threadId: target.threadId,
role: "user",
blocks,
replyToMessageId: input.replyToMessageId,
replyQuote,
clientNonce: input.clientNonce,
});
const activeRuns = await tx.run.findMany({
where: {
threadId: target.threadId,
botId: target.botId,
status: { in: [...ACTIVE_RUN_STATUSES] },
},
select: { id: true, taskId: true, status: true },
});
if (activeRuns.some((run) => !STEERABLE_RUN_STATUSES.has(run.status))) {
throw new ORPCError("CONFLICT", {
message: "Answer the pending ask first.",
});
}
const active = activeRuns[0];
if (active) {
await tx.steeringMessage.create({
data: {
messageId: message.id,
botId: target.botId,
userId: actor.userId,
runId: active.id,
},
});
await tx.message.update({ where: { id: message.id }, data: { runId: active.id } });
const event = await appendEventInTransaction(tx, {
spaceId: actor.spaceId,
threadId: target.threadId,
botId: target.botId,
type: "thread.message.created",
runId: active.id,
payload: {
messageId: message.id,
role: "user",
blocks,
replyToMessageId: input.replyToMessageId,
replyQuote,
},
});
return { message, runs: [active], eventSeq: event.seq };
}
const task = await tx.task.create({
data: {
spaceId: actor.spaceId,
botId: target.botId,
threadId: target.threadId,
userId: actor.userId,
prompt: buildSendPrompt(input.text, artifacts, connectorNames),
status: "queued",
},
});
const run = await tx.run.create({
data: {
spaceId: actor.spaceId,
botId: target.botId,
threadId: target.threadId,
taskId: task.id,
userId: actor.userId,
status: "queued",
trigger: "user",
clientNonce: sendRunClientNonce(input.clientNonce, message.id),
sourceMessageId: message.id,
},
});
await tx.message.update({ where: { id: message.id }, data: { runId: run.id } });
await cancelSupersededQueuedRuns(tx, {
threadId: target.threadId,
botIds: [target.botId],
keepRunIds: [run.id],
});
const event = await appendEventInTransaction(tx, {
spaceId: actor.spaceId,
threadId: target.threadId,
botId: target.botId,
type: "thread.message.created",
runId: run.id,
payload: {
messageId: message.id,
role: "user",
blocks,
runIds: [run.id],
replyToMessageId: input.replyToMessageId,
replyQuote,
},
});
return { message, runs: [run], eventSeq: event.seq };
}
const members = await lockAndLoadGroupMembers(tx, actor, target);
const memberBotIds = members.map((member) => member.botId);
const mentionTargets = splitMentionTargets(input.mentions);
const targetBotIds = resolveGroupTargetBotIds({
text: input.text ?? "",
members: members.map((member) => ({ id: member.botId, name: member.name })),
explicitMentions: mentionTargets.botMentionIds,
defaultBotId: target.leadBotId,
});
const { blocks: attachmentBlocks, artifacts } = await resolveGroupSendAttachments(
{ prisma: tx },
actor,
target.groupId,
memberBotIds,
input.artifactIds,
);
const connectorNames = await resolveOwnedConnectorDisplayNames(
tx,
actor,
mentionTargets.connectorMentionIds,
);
const blocks = buildUserMessageBlocks(input.text, attachmentBlocks);
const message = await createThreadMessageInTransaction(tx, {
threadId: target.threadId,
role: "user",
blocks,
replyToMessageId: input.replyToMessageId,
replyQuote,
clientNonce: input.clientNonce,
});
const activeRuns = await tx.run.findMany({
where: {
threadId: target.threadId,
botId: { in: targetBotIds },
status: { in: [...ACTIVE_RUN_STATUSES] },
},
select: { id: true, taskId: true, botId: true, status: true },
});
const activeByBotId = new Map<string, (typeof activeRuns)[number]>();
for (const run of activeRuns) {
if (!STEERABLE_RUN_STATUSES.has(run.status)) {
throw new ORPCError("CONFLICT", {
message: "Answer the pending ask first.",
});
}
if (!activeByBotId.has(run.botId)) activeByBotId.set(run.botId, run);
}
const runs: Array<{ id: string; taskId: string; botId: string; status: string }> = [];
for (const botId of targetBotIds) {
const active = activeByBotId.get(botId);
if (active) {
await tx.steeringMessage.create({
data: { messageId: message.id, botId, userId: actor.userId, runId: active.id },
});
runs.push(active);
continue;
}
const task = await tx.task.create({
data: {
spaceId: actor.spaceId,
botId,
threadId: target.threadId,
userId: actor.userId,
prompt: buildSendPrompt(input.text, artifacts, connectorNames),
status: "queued",
},
});
const run = await tx.run.create({
data: {
spaceId: actor.spaceId,
botId,
threadId: target.threadId,
taskId: task.id,
userId: actor.userId,
status: "queued",
trigger: "user",
clientNonce: sendRunClientNonce(input.clientNonce, message.id, botId),
sourceMessageId: message.id,
},
});
runs.push(run);
}
const firstRun = runs[0];
const eventBotId = firstRun?.botId ?? targetBotIds[0];
if (!eventBotId) throw new IsolationError("Group send did not resolve a target");
if (firstRun) {
await tx.message.update({ where: { id: message.id }, data: { runId: firstRun.id } });
const createdRuns = runs.filter((run) => !activeByBotId.has(run.botId));
if (createdRuns.length) {
await cancelSupersededQueuedRuns(tx, {
threadId: target.threadId,
botIds: createdRuns.map((run) => run.botId),
keepRunIds: createdRuns.map((run) => run.id),
});
}
}
await touchGroupUpdatedAt(tx, target.groupId);
const event = await appendEventInTransaction(tx, {
spaceId: actor.spaceId,
threadId: target.threadId,
botId: eventBotId,
type: "thread.message.created",
runId: firstRun?.id ?? activeRuns[0]?.id,
payload: {
messageId: message.id,
role: "user",
blocks,
runIds: runs.map((run) => run.id),
replyToMessageId: input.replyToMessageId,
replyQuote,
},
});
return { message, runs, eventSeq: event.seq };
});
const committed = await withSerializableRetry(commit).catch(async (error) => {
const winner = await replayExistingSend(deps, target.threadId, input.clientNonce);
if (winner) return { replay: winner } as const;
throw error;
});
if ("replay" in committed) return committed.replay;
await deps.events.notify(target.threadId, committed.eventSeq).catch((error) => {
// Subscribers catch up from the durable event cursor after a missed realtime wake.
getLogger().error("thread send realtime notification", error);
});
await enqueueRunsNeedingContinue(deps.jobs, committed.runs);
return sendResult(committed.message, committed.runs);
}
/**
* Pick the group member bot that should receive a follow-up. Prefer a waiting
* ask/takeover on any member over the first member's merely-busy run — the
* router's old members[0] shortcut let a fresh run on bot A bury an unanswered
* ask on bot B. Unaddressed follow-ups go to the lead when the group has one.
*/
export function resolveGroupFollowUpBotId(input: {
text: string;
members: Array<{ botId: string; name: string }>;
activeRuns: Array<{ botId: string; status: string; createdAt: Date }>;
defaultBotId?: string | null;
}): string {
const memberBotIds = new Set(input.members.map((member) => member.botId));
const memberRuns = input.activeRuns
.filter((run) => memberBotIds.has(run.botId))
.sort((left, right) => right.createdAt.getTime() - left.createdAt.getTime());
const waiting = memberRuns.find(
(run) => run.status === "waiting_input" || run.status === "waiting_takeover",
);
if (waiting) return waiting.botId;
const steerable = memberRuns.find((run) => STEERABLE_RUN_STATUSES.has(run.status));
if (steerable) return steerable.botId;
const mentioned = resolveGroupTargetBotIds({
text: input.text,
members: input.members.map((member) => ({ id: member.botId, name: member.name })),
explicitMentions: [],
defaultBotId: input.defaultBotId,
})[0];
if (mentioned) return mentioned;
const fallback = input.members[0]?.botId;
if (!fallback) throw new IsolationError();
return fallback;
}
export async function followUpGroupThreadMessage(
deps: { prisma: PrismaClient },
actor: Actor,
target: Extract<ThreadTarget, { kind: "group" }>,
input: { text: string },
) {
return deps.prisma.$transaction(async (tx) => {
const members = await lockAndLoadGroupMembers(tx, actor, target);
const memberBotIds = members.map((member) => member.botId);
const activeRuns = await tx.run.findMany({
where: {
threadId: target.threadId,
botId: { in: memberBotIds },
status: { in: [...ACTIVE_RUN_STATUSES] },
},
select: { id: true, botId: true, status: true, createdAt: true },
orderBy: { createdAt: "desc" },
});
const botId = resolveGroupFollowUpBotId({
text: input.text,
members,
activeRuns,
defaultBotId: target.leadBotId,
});
const blocks = [{ kind: "text" as const, text: input.text }];
const message = await createThreadMessageInTransaction(tx, {
threadId: target.threadId,
role: "user",
blocks,
});
const active = activeRuns.find((run) => run.botId === botId);
let run: { id: string } | null = null;
if (!active) {
const task = await tx.task.create({
data: {
spaceId: actor.spaceId,
botId,
threadId: target.threadId,
userId: actor.userId,
prompt: input.text,
status: "queued",
},
});
run = await tx.run.create({
data: {
spaceId: actor.spaceId,
botId,
threadId: target.threadId,
taskId: task.id,
userId: actor.userId,
status: "queued",
trigger: "follow_up",
sourceMessageId: message.id,
},
select: { id: true },
});
await tx.message.update({ where: { id: message.id }, data: { runId: run.id } });
} else {
await tx.steeringMessage.create({
data: {
messageId: message.id,
botId,
userId: actor.userId,
runId: active.id,
},
});
await tx.message.update({ where: { id: message.id }, data: { runId: active.id } });
}
const event = await appendEventInTransaction(tx, {
spaceId: actor.spaceId,
threadId: target.threadId,
botId,
type: "thread.message.created",
runId: run?.id ?? active?.id,
payload: { messageId: message.id, role: "user", blocks },
});
await touchGroupUpdatedAt(tx, target.groupId);
return { runId: run?.id, eventSeq: event.seq };
});
}
/**
* Append an emoji reply to the conversation so the next AI turn sees its target.
* Clients render it beneath that message; the reaction itself does not start an AI turn.
*/
export async function reactToThreadMessage(
deps: { prisma: PrismaClient },
actor: Actor,
target: ThreadTarget,
input: {
messageId: string;
reaction: MessageReaction;
clientNonce: string;
},
) {
return deps.prisma.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM threads WHERE id = ${target.threadId} FOR UPDATE`;
const parent = await tx.message.findFirst({
where: { id: input.messageId, threadId: target.threadId },
select: { id: true },
});
if (!parent) throw new IsolationError();
const existing = await tx.message.findUnique({
where: {
threadId_clientNonce: { threadId: target.threadId, clientNonce: input.clientNonce },
},
select: { id: true },
});
if (existing) return { eventSeq: null };
const botId = target.kind === "bot" ? target.botId : groupDefaultBotId(target);
if (!botId) throw new IsolationError();
const blocks: MessageBlock[] = [{ kind: "text", text: input.reaction }];
const message = await createThreadMessageInTransaction(tx, {
threadId: target.threadId,
role: "user",
blocks,
replyToMessageId: parent.id,
clientNonce: input.clientNonce,
});
if (target.kind === "group") await touchGroupUpdatedAt(tx, target.groupId);
const event = await appendEventInTransaction(tx, {
spaceId: actor.spaceId,
threadId: target.threadId,
botId,
type: "thread.message.created",
payload: { messageId: message.id, role: "user", blocks, replyToMessageId: parent.id },
});
return { eventSeq: event.seq };
});
}
export async function stopThreadRuns(
deps: {
prisma: PrismaClient;
sandbox: SandboxProvider;
},
actor: Actor,
target: ThreadTarget,
) {
const { runIds, computers, leases } = await deps.prisma.$transaction(async (tx) => {
await tx.$queryRaw`SELECT id FROM threads WHERE id = ${target.threadId} FOR UPDATE`;
const cancelled = await tx.run.updateManyAndReturn({
where: {
threadId: target.threadId,
status: { in: [...ACTIVE_RUN_STATUSES] },
},
data: { status: "cancelled", completedAt: new Date() },
select: { id: true },
});
const ids = cancelled.map((run) => run.id);
await tx.steeringMessage.deleteMany({
where: {
botId: { in: target.kind === "bot" ? [target.botId] : target.memberBotIds },
message: { threadId: target.threadId },
},
});
// Snapshot teardown coordinates before commit. Once cancellation becomes
// visible, a worker can release its lease / execution columns immediately; a
// later lookup would then miss the sandbox work this request must stop.
// Team ownership lives on ComputerExecutionLease; Computer.executionRunId is
// only a legacy secondary path and is not written by current acquisition.
const leases = ids.length
? await tx.computerExecutionLease.findMany({
where: { runId: { in: ids } },
select: { computerId: true, botId: true, runId: true, fence: true },
})
: [];
const leaseComputerIds = [...new Set(leases.map((lease) => lease.computerId))];
const computers = ids.length
? await tx.computer.findMany({
where:
leaseComputerIds.length > 0
? {
OR: [{ id: { in: leaseComputerIds } }, { executionRunId: { in: ids } }],
}
: { executionRunId: { in: ids } },
select: {
id: true,
homeKey: true,
kind: true,
providerRef: true,
executionBotId: true,
executionRunId: true,
},
})
: [];
return { runIds: ids, computers, leases };
});
// Keep the DB lease until after teardown so a replacement run cannot claim the
// screen while we still need the cancelled run's screenLeaseId to release it.
const computerById = new Map(computers.map((computer) => [computer.id, computer]));
const teardownTargets: Array<{
computer: (typeof computers)[number];
botId: string;
runId: string;
lease: (typeof leases)[number] | null;
}> = [];
const seenTargets = new Set<string>();
for (const lease of leases) {
const computer = computerById.get(lease.computerId);
if (!computer) continue;
const key = `${computer.id}:${lease.runId}`;
if (seenTargets.has(key)) continue;
seenTargets.add(key);
teardownTargets.push({
computer,
botId: lease.botId,
runId: lease.runId,
lease,
});
}
const cancelledRunIds = new Set(runIds);
for (const computer of computers) {
if (!computer.executionBotId || !computer.executionRunId) continue;
// Computers may enter the snapshot via a cancelled lease while
// Computer.executionRunId still points at an unrelated live run. Only treat
// the legacy columns as a teardown target when they belong to a run we
// cancelled in this transaction.
if (!cancelledRunIds.has(computer.executionRunId)) continue;
const key = `${computer.id}:${computer.executionRunId}`;
if (seenTargets.has(key)) continue;
seenTargets.add(key);
teardownTargets.push({
computer,
botId: computer.executionBotId,
runId: computer.executionRunId,
lease: null,
});
}
await Promise.all(
teardownTargets.map(async ({ computer, botId, runId, lease }) => {
if (!computer.providerRef) return;
const context = {
operationId: "stop",
traceId: "stop",
spaceId: actor.spaceId,
userId: actor.userId,
botId,
runId,
screenLeaseId: screenLeaseIdForRun(lease, runId),
cancelRunWork: true,
signal: new AbortController().signal,
};
const ref = toComputerRef(computer);
await cancelComputerRunWork(deps.sandbox, ref, computer.id, runId, context);
await deps.sandbox.releaseScreen?.(ref, context).catch(() => undefined);
}),
);
await expireComputerExecutionLeases(deps.prisma, { runId: { in: runIds } });
await deps.prisma.computer.updateMany({
where: { executionRunId: { in: runIds } },
data: {
executionRunId: null,
executionBotId: null,
executionLeaseExpiresAt: null,
},
});
await deps.prisma.event.deleteMany({
where: {
type: "thread.progress",
runId: { in: runIds },
},
});
}
export async function setThreadUnreadState(
prisma: PrismaClient,
actor: Actor,
target: ThreadTarget,
unread: boolean,
) {
const result = await prisma.thread.updateMany({
where: {
id: target.threadId,
spaceId: actor.spaceId,
userId: actor.userId,
unread: { not: unread },
},
data: { unread },
});
if (result.count > 1) throw new IsolationError();
}