/** * Agent chat-reply loop (`teamshare-agent chat`): replies to a single * mentioning message (the one that triggered the wake). One mention → one * reply → go to sleep. When no targetId is given, replies only to the * *latest* mention (not all historical ones) as a fallback. * * Generation uses the configured harness (opencode/claude/codex/gemini/ * copilot/goose/openhands/aider) or the `--self` LLM completion. */ import { TeamshareApi } from '../api'; import { type HarnessName } from '../harness/harness-adapter'; /** * Extract a human-readable error from a harness failure message. * With spawnHarness the error is " exited with code N: ". * We extract the detail part and try to parse JSON errors from it. */ export declare function cleanHarnessError(raw: string): string; /** * IMP-913: injected into the prompt on retry attempts (>= 2) after a * transient provider error. Permissive by design - the model verifies and * reuses what exists, but a crash BEFORE creation still creates normally. */ export declare const RETRY_NOTE: string; /** * The runner's own "I am on it" message, posted by `cmdChat` BEFORE the harness * starts (2026-11). * * It is written by the agent's own user, in the same channel, AFTER the mention * it is answering - which is exactly the shape the delivery check looks for. So * unless it is excluded by id, the check concludes "the model already posted via * MCP" and THROWS AWAY the reply the model actually produced. That is the * "Working on it" then silence bug: the agent wrote a full document draft, the * runner saw its own acknowledgment, and both were dropped. */ export declare const CHAT_ACK_BODY = "Working on it, give me a moment."; export interface ChatReplyOptions { harness: HarnessName; selfMode: boolean; llm?: { baseUrl: string; apiKey: string; model: string; temperature?: number; maxTokens?: number; }; /** Reasoning effort for harnesses that expose it (codex: low|medium|high|xhigh, agy: low|medium|high). */ effort?: string; /** Debug/testing switch (TS_CHAT_ECHO=1): post canned acknowledgments. */ echo?: boolean; /** Project this chat belongs to - recorded as the session title for spend attribution. */ projectId?: string; /** API client for the tool loop (required when selfMode is true). */ api?: import('../api').TeamshareApi; /** Working directory - used by antigravity to find .agents/mcp_config.json. */ cwd?: string; /** Harness session id - stamped on MCP claims so they can be released at exit. */ sessionId?: string; /** Agent row id - scopes machine-local harness session continuation. */ agentId?: string; /** * Chat channel this reply belongs in (2026-10) - from the wake's * `channelId` via `--channel`. * * Every read AND every post in this loop is scoped by it. Unscoped, the * server answers from the project's default General channel, so a mention * in any other channel was unfindable ("Message not found in this channel") * and its notice landed in General instead. Absent = legacy behaviour for * wakes that predate the flag. */ channelId?: string; /** Optional logger for retry/give-up lines (wired to the CLI's log). */ onLog?: (text: string) => void; /** * Id of the runner's own acknowledgment message (see {@link CHAT_ACK_BODY}) * when it was posted successfully. * * The delivery check asks "did this agent post anything after the mention?". * The acknowledgment IS such a message, so without this id every run looked * already-answered and the model's reply was discarded. */ ackMessageId?: string; /** Idle timeout in minutes - killed after this long with no output. Default 20. */ timeoutMin?: number; /** * Task-linked chat (2026-09): present only when the CLI ran the standard * run.ts git flow for this mention (stash -> task branch -> finalize -> * stash pop). Injects the "runner owns git" block and the `## Local git * state` stash section into the reply prompt. Absent for a plain chat * mention, whose prompt stays exactly as it was before task links existed. */ git?: ChatGitContext; /** * Context budget for this conversation, in tokens (2026-12) - the project's * `chatMaxContextTokens`, else the 400k default. `runChatReply` reads it from * the project it already fetches; settable directly for tests. */ contextLimitTokens?: number | null; /** * Fired when the bridge rotated the conversation because it hit the context * budget. Chat posts a short notice so the human knows why the thread starts * fresh; other modes only log. */ onSessionRotated?: (info: { reason: 'context-budget' | 'context-overflow'; estimatedTokens: number; limitTokens: number; }) => void; } /** Git context handed from `cmdChat` to the reply prompt (prep-gated). */ export interface ChatGitContext { /** Task this mention is linked to (already validated as a UUID). */ taskId: string; /** Task title, when it could be fetched - shown in the task-link section. */ taskTitle?: string; /** Branch the run prepared/reuses for this task (when known). */ branch?: string; /** "The runner owns git …" instruction block (run.ts parity). */ ownership: string; /** `## Local git state` markdown section; '' when there is nothing to report. */ localGitState: string; } /** * The harness-session key for ONE chat conversation (2026-12). * * Three separate bugs lived in the old `chat-${projectId}` key: * * 1. **It was never used at all.** The scope was built from `opts.projectId`, * which `cmdChat` never passed - so every chat mention was a brand-new * harness session and the agent forgot the thread between messages. * 2. **Channels shared one conversation.** Two channels in one project are two * conversations; one record meant a mention in #random resumed General's * thread (and the prompt's channel scope disagreed with the model's memory). * 3. **Task-linked chat shared the channel thread.** `#task:` mentions run the * git work pipeline; resuming that transcript for a plain channel chat (and * vice versa) injected "the runner owns git" into ordinary conversation. * * Exported so the key shape is pinned by a test - it is the address the whole * continuity feature depends on. */ export declare function chatConversationScope(args: { agentId?: string; projectId?: string; channelId?: string; /** Task-linked chat (`#task:` reference): its own work conversation. */ taskId?: string; }): { agentId: string; taskId: string; mode: string; } | undefined; /** * Keep the NEWEST messages that fit a character budget (2026-12). * * The newest messages are the ones a reply is about; dropping the oldest is the * only useful truncation. Never returns an empty list for a non-empty input. */ export declare function trimSeed(rows: T[], maxChars: number): T[]; interface ChatRow { id: string; body: string; createdAt: string; /** Set when this message is a threaded reply (2026-11). */ replyToId?: string | null; author?: { id?: string; name?: string; kind?: string; } | null; /** AgentMention id (2026-09) - the deterministic claim handle. */ mentionId?: string | null; } /** * True when the body mentions `@token` in either raw (`@name`) or structured * (`@[userId:name]`) format. Used by the reply loop to match mentions. */ export declare function bodyMentionsToken(body: string, token: string): boolean; /** Display body with structured @[id:Name] → @Name for prompt readability. */ export declare function displayBody(body: string): string; /** * Builds the reply prompt. Exported (pure) so the task-linked git sections * can be verified directly: they must appear ONLY when `git` was handed in * by a session that actually ran the git flow. */ export declare function mentionPrompt(agentName: string, target: ChatRow, context: ChatRow[], projectId: string, projectName?: string, agentUserId?: string, git?: ChatGitContext, /** * Channel this conversation lives in (2026-10). When present the REPLY * DELIVERY block orders the model to pass it to post_chat_message. * * WHY THE PROMPT MUST CARRY IT, not just the runner: the model delivers via * the post_chat_message MCP tool, whose channelId is OPTIONAL and defaults * server-side to General. A runner-scoped post with a model-scoped General * post is the duplicate-reply incident: the runner checks "did WE post in * this channel?", finds nothing, and posts a second copy. */ channelId?: string, /** * The message this wake is a REPLY to (2026-11), when the human used the * Reply action on one of the agent's own messages. Passing it makes the * agent answer in context and thread its answer instead of posting a fresh * message beside the conversation. */ replyTo?: ChatRow | null, /** Idle budget for this run (minutes), so the limits block states the real one. */ timeoutMin?: number): string; /** * Runs the chat reply loop. Heartbeats working/online around the work and * replies to at most ONE mentioning message: * - If `targetId` is given (from the wake event's messageId), reply ONLY * to that specific message. * - Otherwise, reply to the single LATEST mention (not all of them). * One mention → one reply → go to sleep. */ export declare function runChatReply(api: TeamshareApi, agentId: string, projectId: string, mentionToken: string, opts: ChatReplyOptions, targetId?: string): Promise<{ replied: number; skipped: number; }>; /** True when the reply contains actual text (not only harness JSON events). */ export declare function looksLikeRealText(reply: string): boolean; /** * Does one channel row count as "the agent already answered this mention"? * * Pure, so the rule can be tested directly (see * `tests/chat-ack-not-a-reply.test.mjs`). The exclusions, each one a shipped * bug: * - `ackMessageId` - the runner's own "Working on it" post (see * {@link CHAT_ACK_BODY}). Counting it made EVERY run look delivered and * silently discarded the model's reply. * - the mention row itself. * * Identity is the agent's USER id when known, with the display NAME still * accepted as a fallback. Deliberately OR-shaped: a stricter id-only rule * would post a DUPLICATE reply the moment the two ever disagree (an older hub, * a renamed agent, a settings payload that answers an agent id instead of the * user id), and a duplicate is worse than the case it guards against. */ export declare function countsAsAgentReply(row: { id: string; createdAt: string; author?: { id?: string; name?: string; kind?: string; } | null; }, target: { id: string; createdAt: string; }, selfName: string, opts?: { ackMessageId?: string; agentUserId?: string; }): boolean; export {};