feat(chat): deliver proactive task messages to agent chats (#18374)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Agent Chat gives each person a persistent conversation with each
agent.
> - Tasks and routines produce results outside that conversation.
> - Those runs need a safe way to bring a requested result back to the
person.
> - The server must select the agent's own chat and check the source
task's access rules.
> - This pull request adds proactive chat messages and unread
indicators.
> - People can see the result, open its source task, and reply in the
same chat.

## Linked Issues or Issue Description

**Subsystem affected**

Server, native runner tools, shared contracts, database, and UI.

**Problem or motivation**

An agent can report progress on a task or comment on an authorized task.
It cannot send a routine result to its own standing chat with the
responsible person. A morning review routine therefore cannot leave a
visible digest in that person's chat.

**Proposed solution**

Add `send_chat_message({body, idempotencyKey})` and `POST
/api/agents/me/chat/messages`. The server selects the company, agent,
and responsible person from the active run. It saves an attributed
comment and audit record in one transaction. The chat shows a
source-task link and per-person unread state.

**Alternatives considered**

A destination parameter on a generic comment tool would expose
unnecessary routing authority. A new delivery worker would add another
durable delivery path. This change uses a dedicated tool and the
existing comment and live-event paths.

**Roadmap alignment**

This extends the experimental Agent Chat capability in `ROADMAP.md`. The
existing `enableAgentChat` setting controls it. Related public work:
Refs #13282, Refs #13283, and Refs #14408. Searches for proactive chat
and unread chat found no duplicate PR.

## What Changed

- Add a focused messaging service shared by the native tool and HTTP
route. It checks current run ownership, execution mode, recipient
membership, task access, and task privacy.
- Reuse the canonical company/agent/person conversation. Save the
comment and audit record together. Keep task completion and chat
execution separate from delivery.
- Add source-task provenance and source-scoped retry keys. Identical
retries return the saved receipt. Changed content returns a conflict.
- Enforce the conversation's fixed agent at the shared comment-write
boundary. Keep normal reply cancellation and session checks.
- Add chat unread state, accessible agent dots, aggregate Chat
indicators, and visible-message read cutoffs. Refresh through existing
live events.
- Add the request-key constraint, native tool contracts, documentation,
capability maps, stories, and regression coverage.

## Verification

- Local delivery/security proof: all 38 proactive-message cases pass.
Eight credential-scope regressions and four quota regressions fail
against the prior source. The repaired delivery and canonical
cross-issue cap suites pass all 49 cases; all 31 OpenAPI tests, server
typecheck, and capability-map checks pass. The shared per-run cap covers
native and HTTP sends, mixed ordinary mutations, concurrent last-slot
contention, and retry/recovery without double charging.
- Credential tests preserve the authenticated person and authorizer;
reject bridge/test credentials and persisted skill-test runs after
task-mode changes; and recheck API-key revocation, scope, and
responsible person after destination locking. The earlier
delivery/native-authority suites passed all 74 cases before the four
quota additions.
- Four PostgreSQL contention cases cover native and HTTP sends plus
retries during a native chat mutation. All four deadlock against the
earlier source and pass with destination-before-source/run locking.
Recovery and human-reply delivery enqueue only the human comment; a
proactive digest never wakes the chat agent.
- Passed 108 companion conversation, native-authority, and OpenAPI
tests; 112 runner catalog/workflow-report tests; 47 completion-delivery
tests; and 25 project-handoff tests. Focused runner tests cover native
tool availability without generic API tools.
- All 327 affected UI tests, UI typecheck, token gates, and catalog
checks pass. The read hook retries at most three times, respects server
retry delay, coalesces only seen cutoffs, recovers on reconnect, and
cancels on scope changes.
- Real browser journeys with a deterministic process agent verify
routine-to-chat delivery, first-chat creation, unread state across
reload, the source link, secondary chat navigation, and a follow-up
reply referring to the digest. This does not qualify live GitHub
retrieval or model output quality.
- The Storybook showcase uses production components with deterministic
network fixtures. Rendered interactions pass for the landing, ordinary
read success, transient read recovery, and persistent failure after
bounded retries. Both Chat navigation variants update from two unread
chats to one while only Kodi's dot clears. Mobile and light variants
were reviewed. The existing Coordinator Recents label contrast finding
is unchanged; no Linux visual baseline archive exists.
- Current master's independent sandbox migration retains 0418.
Regenerated the feature migration as 0419 from the combined schema and
retained exactly the newest five snapshots; numbering/safety, replay,
and schema-drift checks pass.
- Workspace typecheck and build passed before PR preparation; canonical
server/UI typechecks passed again on the combined tree. Migration
`0419_slippery_impossible_man.sql` passes safety and schema drift checks
on disposable PostgreSQL, including interrupted index repair, concurrent
migrators, one-time owner read-state backfill, preserved receipts, and
two SQL replays. A default five-second local snapshot comparison timed
out; a diagnostic 30-second run passed without drift.
- Earlier failures are retained in the record: full local `pnpm
test:run` and broad shards encountered embedded-PostgreSQL startup,
timing, and provider-recovery failures. Thirteen selected
external-channel cases pass in isolation on the original and changed
sources; an unordered comment-row assertion now explicitly orders both
reads. The earlier route registry, native tool count, runner catalog,
and accessible Chat badge-name failures were fixed and passed full
remote CI on `920b3bb7db`.
- Repeated managed-skill server8 failures came from CI's newer synthetic
merge: its Cloud guard correctly rejected the old local-disk fixture.
Master independently repaired the fixture in #18385; this branch keeps
that repair unchanged. All 57 managed-skill and Cloud prerequisite cases
pass on the combined tree, and that fixture has no remaining PR diff.
- Current reviewed head `dc16f314739a6d977bed21cb1446d0e80a541578`:
Greptile 5/5 with no findings, Superagent security assessment passed,
advisory Paperclip Review 5/5 with no findings, and zero open review
threads. All 55 current-head check runs pass, with five expected skips
and the advisory review neutral at 5/5; Snyk also passes. No checks are
pending or failing. Protected squash auto-merge is enabled and is
waiting for required code-owner approval. A normal exact-head merge was
refused by the base-branch policy; no admin bypass was used. The
previous head's Superagent quota finding is fixed and covered above.

## Risks

- Chat remains company-visible. Delivery rejects a source task with
private-task, project, or ancestor restrictions.
- Read state uses a comment timestamp cutoff. The server retains
database precision and never moves a read receipt backward.
- The new unique constraint changes comment query planning. An existing
regression now uses an explicit row order. The migration builds the
unique index concurrently, then takes a brief table lock to attach it.
It uses the existing top-level migration and interrupted-index recovery
path.
- The upgrade backfills missing chat-owner read-state rows at the latest
existing agent comment. Existing read receipts remain intact. New chats
can still be unread before the human participates.
- Quota observation commits atomically with delivery. A rejected send
rolls back its attempted denial audit row and any first-chat creation;
the canonical warning remains in server logs, and previously spent quota
remains enforced. Identical/conflicting retries and receipt recovery
spend no extra slot.
- This version delivers in-app only. It adds no external-channel, push,
or email delivery.
- Local full-suite acceptance remains limited by the failures recorded
above. The feature stays behind `enableAgentChat`.

## Model Used

OpenAI Codex. PR preparation and CI work used `gpt-6.1-sol` with tool
use and code execution. The earlier implementation also used Codex, but
its exact model ID was not recorded in the visible session. The
context-window size was not provided.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run focused tests locally and they pass; the broad local
failures are recorded above
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-10-30 21:39:07 -05:00
1 parent 7114582c63
commit 8ff812cdde
77 files changed
+2275 -70

No files matched your search

@@ -0,0 +1,405 @@
import { createHash, randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { eq, sql } from "drizzle-orm";
import { activityLog, agentApiKeys, agents, authUsers, chatCompletionDeliveries, chatTaskHandoffs, companyMemberships, heartbeatRuns, issueComments, issueThreadInteractions, issues, projects } from "@paperclipai/db";
import type { AgentApiKeyScope } from "@paperclipai/shared";
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
import { sendAgentChatMessage } from "../services/agent-chat-messages.js";
import { withConversationReadState } from "../services/agent-chat-read-state.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { issueService } from "../services/issues.js";
import { activityService } from "../services/activity.js";
import { recordAcceptedChatHandoff } from "../services/chat-completion-delivery.js";
import { conversationReplay, deliverConversationComments, undeliveredConversationComments } from "../services/agent-conversations.js";
import { PaperclipRunnerToolAuthority } from "../services/native-runtime/paperclip-runner-tool-authority.js";
import { CROSS_ISSUE_INFLUENCE_LIMIT } from "../services/cross-issue-influence-limit.js";
import { startRunnerApiTestServer } from "./helpers/runner-api-server.js";
import { recoveryPostgresSupport as support } from "./helpers/recovery-postgres.js";
(support.supported ? describe : describe.skip)("proactive agent chat messages", () => {
let server: Awaited<ReturnType<typeof startRunnerApiTestServer>>;
const originalSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
beforeAll(async () => {
process.env.PAPERCLIP_AGENT_JWT_SECRET = randomUUID();
server = await startRunnerApiTestServer({ humanSessions: true });
await instanceSettingsService(server.db).updateExperimental({ enableAgentChat: true });
}, 60_000);
afterAll(async () => {
await server?.close();
if (originalSecret === undefined) delete process.env.PAPERCLIP_AGENT_JWT_SECRET;
else process.env.PAPERCLIP_AGENT_JWT_SECRET = originalSecret;
});
const fixture = () => server.fixture({ connectionScenario: "fresh", apiToolsEnabled: false, disableWakeOnDemand: true });
type Fixture = Awaited<ReturnType<typeof fixture>>;
const input = { body: "## Morning review\n\nThree PRs need your review.", idempotencyKey: "morning-pr-digest" };
const send = (f: Fixture, value: unknown = input) => sendAgentChatMessage(server.db, f, value);
const httpSend = (f: Fixture, value: unknown = input, keyScope: AgentApiKeyScope = { kind: "standard" }, authorizingUserId?: string) => fetch(`${server.apiUrl}/api/agents/me/chat/messages`, {
method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${createLocalAgentJwt(f.agentId, f.companyId, "paperclip_runner", f.runId, f.responsibleUserId, keyScope, authorizingUserId)}` },
body: JSON.stringify(value),
});
const apiKey = async (f: Fixture, scopeConfig: AgentApiKeyScope = { kind: "standard" }) => {
const token = `pcp_${randomUUID()}`;
const [key] = await server.db.insert(agentApiKeys).values({ companyId: f.companyId, agentId: f.agentId, name: "Chat delivery test",
responsibleUserId: f.responsibleUserId, scopeConfig, keyHash: createHash("sha256").update(token).digest("hex") }).returning();
return { ...key, token };
};
const keySend = (f: Fixture, token: string, value: unknown = input) => fetch(`${server.apiUrl}/api/agents/me/chat/messages`, {
method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, "x-paperclip-run-id": f.runId },
body: JSON.stringify(value),
});
const spendInfluence = (f: Fixture, count: number) => server.db.insert(activityLog).values(Array.from({ length: count }, (_, index) => ({
companyId: f.companyId, actorType: "agent" as const, actorId: f.agentId, agentId: f.agentId, runId: f.runId,
action: "issue.cross_issue_influence_observed", entityType: "issue", entityId: f.issueId,
details: { kind: ["comment", "update", "interaction_resolution"][index % 3] },
})));
it.each(["native", "http"])("enforces the shared run cap for %s delivery without creating an empty chat", async transport => {
const f = await fixture();
await spendInfluence(f, CROSS_ISSUE_INFLUENCE_LIMIT);
if (transport === "native") {
await expect(f.authority.execute({ tool: "send_chat_message", arguments: input, callId: randomUUID() }))
.rejects.toMatchObject({ status: 429, details: { code: "cross_issue_influence_cap_exceeded", cap: CROSS_ISSUE_INFLUENCE_LIMIT } });
} else {
const response = await httpSend(f);
expect(response.status, await response.clone().text()).toBe(429);
expect(await response.json()).toMatchObject({ details: { code: "cross_issue_influence_cap_exceeded", cap: CROSS_ISSUE_INFLUENCE_LIMIT } });
}
const snapshot = await f.snapshot();
expect(snapshot.comments).toEqual([]);
expect(snapshot.issues.filter(issue => issue.conversationAgentId)).toEqual([]);
expect(snapshot.activity).toHaveLength(CROSS_ISSUE_INFLUENCE_LIMIT);
});
it("charges a committed message once across retries, recovery and conflicting content", async () => {
const f = await fixture(), receipt = (await send(f))!;
expect((await httpSend(f)).status).toBe(200);
expect(await f.authority.recover({ tool: "send_chat_message", arguments: input, callId: randomUUID() }))
.toMatchObject({ result: { commentId: receipt.commentId, replayed: true } });
expect((await httpSend(f, { ...input, body: "Different content" })).status).toBe(409);
expect(await f.authority.recover({ tool: "send_chat_message", arguments: { ...input, idempotencyKey: "not-committed" }, callId: randomUUID() })).toBeNull();
expect((await f.snapshot()).activity.filter(row => row.action === "issue.cross_issue_influence_observed")).toHaveLength(1);
expect((await f.snapshot()).comments).toHaveLength(1);
});
it("cannot race native and HTTP delivery past the shared final slot", async () => {
const f = await fixture();
await spendInfluence(f, CROSS_ISSUE_INFLUENCE_LIMIT - 1);
const outcomes = await Promise.all([
f.authority.execute({ tool: "send_chat_message", arguments: { ...input, idempotencyKey: "native-last-slot" }, callId: randomUUID() })
.then(() => 201, error => error.status),
httpSend(f, { ...input, idempotencyKey: "http-last-slot" }).then(response => response.status),
]);
expect(outcomes.sort()).toEqual([201, 429]);
const snapshot = await f.snapshot();
expect(snapshot.activity.filter(row => row.action === "issue.cross_issue_influence_observed")).toHaveLength(CROSS_ISSUE_INFLUENCE_LIMIT);
expect(snapshot.comments).toHaveLength(1);
expect(snapshot.issues.filter(issue => issue.conversationAgentId)).toHaveLength(1);
});
it("supports standard task API keys without changing agent and run attribution", async () => {
const f = await fixture(), key = await apiKey(f);
const response = await keySend(f, key.token);
expect(response.status, await response.clone().text()).toBe(201);
expect((await f.snapshot()).activity).toContainEqual(expect.objectContaining({ action: "issue.comment_added",
actorId: f.agentId, agentId: f.agentId, runId: f.runId, responsibleUserId: f.responsibleUserId }));
});
it("preserves an external authorizer's current access intersection", async () => {
const f = await fixture();
expect((await httpSend(f, input, { kind: "standard" }, randomUUID())).status).toBe(403);
await expect(sendAgentChatMessage(server.db, { ...f, authorizingUserId: randomUUID() }, input)).rejects.toMatchObject({ status: 403 });
expect((await f.snapshot()).issues.filter(issue => issue.conversationAgentId)).toEqual([]);
expect((await f.snapshot()).comments).toEqual([]);
});
it("keeps skill-test JWT and API-key scopes confined to their own task", async () => {
const f = await fixture(), scope = { kind: "skill_test", issueId: f.issueId } as const;
const key = await apiKey(f, scope);
expect((await httpSend(f, input, scope)).status).toBe(403);
expect((await keySend(f, key.token)).status).toBe(403);
expect((await f.snapshot()).issues.filter(issue => issue.conversationAgentId)).toEqual([]);
expect((await f.snapshot()).comments).toEqual([]);
});
it.each(["admitted", "legacy", "saved-task"])("retains a persisted %s skill-test run boundary after task mode changes", async kind => {
const f = await fixture();
const contextSnapshot = kind === "admitted" ? { paperclipAgentJwtScope: { kind: "skill_test", issueId: f.issueId } }
: kind === "legacy" ? { paperclipSkillTest: { id: randomUUID() } }
: { paperclipIssue: { id: f.issueId, workMode: "skill_test" } };
await server.db.update(heartbeatRuns).set({ contextSnapshot }).where(eq(heartbeatRuns.id, f.runId));
await server.db.update(issues).set({ workMode: "skill_test" }).where(eq(issues.id, f.issueId));
await server.db.update(issues).set({ workMode: "standard" }).where(eq(issues.id, f.issueId));
expect((await httpSend(f)).status).toBe(403);
await expect(sendAgentChatMessage(server.db, f, input, { receiptOnly: true })).rejects.toThrow(/skill.test/i);
expect((await f.snapshot()).issues.filter(issue => issue.conversationAgentId)).toEqual([]);
expect((await f.snapshot()).comments).toEqual([]);
});
it("does not let task-bridge credentials publish outside their admitted task", async () => {
const f = await fixture(), key = await apiKey(f, { kind: "task_bridge", parentIssueId: f.issueId });
expect((await keySend(f, key.token)).status).toBe(403);
expect((await f.snapshot()).issues.filter(issue => issue.conversationAgentId)).toEqual([]);
});
it.each(["revoked", "narrowed", "responsible-human"])("rechecks a %s API key after waiting for the destination", async kind => {
const f = await fixture(), receipt = (await send(f))!, key = await apiKey(f);
let unlock!: () => void, ready!: (pid: number) => void;
const locked = new Promise<number>(resolve => { ready = resolve; });
const release = new Promise<void>(resolve => { unlock = resolve; });
const gate = server.db.transaction(async tx => {
const [{ pid }] = await tx.execute(sql<{ pid: number }>`select pg_backend_pid() as pid`);
await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, receipt.conversationId)).for("update");
ready(pid); await release;
});
const pid = await locked;
const delivery = keySend(f, key.token, { ...input, idempotencyKey: "key-after-wait" });
try {
await vi.waitFor(async () => {
const [row] = await server.db.execute(sql<{ blocked: boolean }>`select exists(select 1 from pg_stat_activity
where datname=current_database() and ${pid}=any(pg_blocking_pids(pid))) as blocked`);
expect(row.blocked).toBe(true);
}, { timeout: 5_000, interval: 10 });
await server.db.update(agentApiKeys).set(kind === "revoked" ? { revokedAt: new Date() }
: kind === "narrowed" ? { scopeConfig: { kind: "skill_test", issueId: f.issueId } }
: { responsibleUserId: randomUUID() }).where(eq(agentApiKeys.id, key.id));
unlock(); await gate;
expect((await delivery).status).toBe(403);
expect((await f.snapshot()).comments).toHaveLength(1);
} finally { unlock(); await gate; await delivery; }
}, 30_000);
it("publishes through the native tool without generic API tools, without starting a turn or changing the source", async () => {
const f = await fixture();
expect(f.authority.definitions().map(d => d.name)).toContain("send_chat_message");
const before = await issueService(server.db).getById(f.issueId);
const receipt = await f.authority.execute({ tool: "send_chat_message", arguments: input, callId: randomUUID() }) as { commentId: string; conversationId: string; chatUrl: string };
const snapshot = await f.snapshot();
const comment = snapshot.comments.find(c => c.id === receipt.commentId)!;
expect(comment).toMatchObject({ body: input.body, authorAgentId: f.agentId, createdByRunId: f.runId, onBehalfOfUserId: f.responsibleUserId,
metadata: { chatMessage: { sourceTaskId: f.issueId, sourceRunId: f.runId } } });
expect(snapshot.issues.find(i => i.id === receipt.conversationId)).toMatchObject({ conversationAgentId: f.agentId,
conversationUserId: f.responsibleUserId, conversationState: "waiting", executionRunId: null, status: "in_review" });
expect(await issueService(server.db).getById(f.issueId)).toEqual(before);
expect(await server.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(1);
expect(snapshot.activity.filter(a => a.action === "issue.comment_added")).toHaveLength(1);
expect(await activityService(server.db).runsForIssue(f.companyId, receipt.conversationId)).toEqual([]);
expect(receipt.chatUrl).toContain(`/chats/${f.agentId}`);
expect(await withConversationReadState(server.db, f.companyId, f.responsibleUserId!, [{ id: receipt.conversationId }])).toMatchObject([{ isUnreadForMe: true }]);
expect(await f.authority.recover({ tool: "send_chat_message", arguments: input, callId: randomUUID() }))
.toMatchObject({ result: { commentId: receipt.commentId, replayed: true } });
});
it("creates once under concurrent first sends and recovers a committed response across run retries", async () => {
const f = await fixture();
expect(await f.authority.recover({ tool: "send_chat_message", arguments: input, callId: randomUUID() })).toBeNull();
expect((await f.snapshot()).issues.filter(i => i.conversationAgentId)).toHaveLength(0);
const [a, b] = await Promise.all([send(f), send(f)]);
expect(a!.commentId).toBe(b!.commentId);
expect((await f.snapshot()).comments).toHaveLength(1);
const other = await send(f, { ...input, idempotencyKey: "second" });
expect(other!.commentId).not.toBe(a!.commentId);
await expect(send(f, { ...input, body: "Different digest" })).rejects.toThrow(/different content/);
const nextRunId = randomUUID();
await server.db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.runId));
await server.db.insert(heartbeatRuns).values({ id: nextRunId, companyId: f.companyId, agentId: f.agentId,
status: "running", nativeIssueId: f.issueId, responsibleUserId: f.responsibleUserId });
await server.db.update(issues).set({ executionRunId: nextRunId }).where(eq(issues.id, f.issueId));
expect(await send({ ...f, runId: nextRunId })).toMatchObject({ commentId: a!.commentId, replayed: true });
expect((await f.snapshot()).comments).toHaveLength(2);
});
it("supports HTTP routine delivery during an active chat reply and after a context reset", async () => {
const f = await fixture();
await server.db.update(heartbeatRuns).set({ invocationSource: "automation", triggerDetail: "routine" }).where(eq(heartbeatRuns.id, f.runId));
const first = await httpSend(f);
expect(first.status, await first.clone().text()).toBe(201);
const receipt = await first.json();
const replyRun = randomUUID();
await server.db.insert(heartbeatRuns).values({ id: replyRun, companyId: f.companyId, agentId: f.agentId, status: "running",
nativeIssueId: receipt.conversationId, responsibleUserId: f.responsibleUserId, contextSnapshot: { issueId: receipt.conversationId, conversationSessionGeneration: 0 } });
await server.db.update(issues).set({ executionRunId: replyRun, conversationState: "active" }).where(eq(issues.id, receipt.conversationId));
const before = await issueService(server.db).getById(receipt.conversationId);
expect((await httpSend(f, { ...input, idempotencyKey: "during-reply" })).status).toBe(201);
const after = await issueService(server.db).getById(receipt.conversationId);
expect(after).toMatchObject({ executionRunId: replyRun, conversationState: before!.conversationState, status: before!.status });
await server.db.update(issues).set({ conversationSessionGeneration: 1, conversationState: "waiting", executionRunId: null }).where(eq(issues.id, receipt.conversationId));
expect((await httpSend(f, { ...input, idempotencyKey: "after-new" })).status).toBe(201);
await expect(issueService(server.db).addComment(receipt.conversationId, "Stale reply", { agentId: f.agentId, runId: replyRun })).rejects.toThrow(/earlier session/);
expect(await server.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(2);
expect((await f.snapshot()).comments).toHaveLength(3);
});
it("never enqueues a digest during recovery or the next human reply", async () => {
const f = await fixture(), svc = issueService(server.db);
const receipt = (await send(f))!;
const conversation = (await svc.getById(receipt.conversationId))!;
const enqueue = vi.fn(async (_agentId: string, _options: unknown) => null);
expect(await undeliveredConversationComments(server.db, f.companyId, conversation.id)).toEqual([]);
await deliverConversationComments(server.db, conversation, enqueue);
expect(enqueue).not.toHaveBeenCalled();
const reply = await svc.addComment(conversation.id, "Which PR should I review first?", { userId: f.responsibleUserId! }, { clientRequestId: randomUUID() });
expect((await undeliveredConversationComments(server.db, f.companyId, conversation.id)).map(comment => comment.id)).toEqual([reply.id]);
await deliverConversationComments(server.db, conversation, enqueue);
expect(enqueue).toHaveBeenCalledOnce();
expect(enqueue.mock.calls[0]?.[1]).toMatchObject({ requestedByActorType: "user", requestedByActorId: f.responsibleUserId,
contextSnapshot: { wakeCommentId: reply.id, wakeCommentIds: [reply.id] } });
expect(await conversationReplay(server.db, f.companyId, conversation.id, reply.id))
.toContain(JSON.stringify({ author: "agent", body: input.body }));
});
it.each([
{ transport: "native", replay: false }, { transport: "native", replay: true },
{ transport: "http", replay: false }, { transport: "http", replay: true },
])("serializes $transport delivery with a native chat mutation, replay=$replay", async ({ transport, replay }) => {
const f = await fixture(), receipt = (await send(f))!, chatRunId = randomUUID();
await server.db.update(agents).set({ runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: false, maxConcurrentRuns: 2 } } }).where(eq(agents.id, f.agentId));
await server.db.insert(heartbeatRuns).values({ id: chatRunId, companyId: f.companyId, agentId: f.agentId, status: "running",
runtimeMode: "native", nativeIssueId: receipt.conversationId, responsibleUserId: f.responsibleUserId,
contextSnapshot: { issueId: receipt.conversationId, conversationSessionGeneration: 0 } });
await server.db.update(issues).set({ executionRunId: chatRunId, conversationState: "active" }).where(eq(issues.id, receipt.conversationId));
const chat = new PaperclipRunnerToolAuthority(server.db, { companyId: f.companyId, agentId: f.agentId,
issueId: receipt.conversationId, runId: chatRunId, apiUrl: server.apiUrl, apiToolsEnabled: false });
let unlock!: () => void, ready!: (pid: number) => void;
const locked = new Promise<number>(resolve => { ready = resolve; });
const release = new Promise<void>(resolve => { unlock = resolve; });
const gate = server.db.transaction(async tx => {
const [{ pid }] = await tx.execute(sql<{ pid: number }>`select pg_backend_pid() as pid`);
await tx.select({ id: agents.id }).from(agents).where(eq(agents.id, f.agentId)).for("update");
ready(pid);
await release;
});
const pid = await locked;
const waitForBlocked = async (count: number) => vi.waitFor(async () => {
const [row] = await server.db.execute(sql<{ count: number }>`with recursive blocked(pid) as (
select pid from pg_stat_activity where datname = current_database() and ${pid} = any(pg_blocking_pids(pid))
union select activity.pid from pg_stat_activity activity join blocked on blocked.pid = any(pg_blocking_pids(activity.pid))
where activity.datname = current_database()
) select count(*)::int as count from blocked`);
expect(row.count).toBeGreaterThanOrEqual(count);
}, { timeout: 5000, interval: 10 });
const message = replay ? input : { ...input, idempotencyKey: "concurrent-message" };
let settled: Promise<PromiseSettledResult<unknown>[]> | undefined;
let observedDelivery: Promise<PromiseSettledResult<unknown>[]> | undefined;
try {
const delivery = transport === "native"
? f.authority.execute({ tool: "send_chat_message", arguments: message, callId: randomUUID() })
: httpSend(f, message).then(async response => {
expect(response.status, await response.clone().text()).toBe(replay ? 200 : 201);
return response.json();
});
observedDelivery = Promise.allSettled([delivery]);
await waitForBlocked(1);
const mutation = chat.execute({ tool: "write_document", callId: randomUUID(), arguments: {
key: "concurrent-note", title: "Concurrent note", body: "The chat reply stays independent.", baseRevisionId: null, idempotencyKey: "concurrent-note",
} });
settled = Promise.allSettled([delivery, mutation]);
await waitForBlocked(2);
unlock();
await gate;
const results = await settled;
expect(results.map(result => result.status), JSON.stringify(results)).toEqual(["fulfilled", "fulfilled"]);
expect(results[1]).toMatchObject({ status: "fulfilled", value: { disposition: "applied", document: { key: "concurrent-note" } } });
expect(await issueService(server.db).getById(receipt.conversationId)).toMatchObject({ conversationState: "active" });
} finally {
unlock();
await gate;
await settled;
await observedDelivery;
}
}, 30_000);
it("isolates two humans sharing an agent and two agents serving one human", async () => {
const f = await fixture();
const a = await send(f);
const userId = randomUUID();
await server.db.insert(authUsers).values({ id: userId, name: "Second human", email: `${userId}@fixture.invalid`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() });
await server.db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "member" });
await server.db.update(heartbeatRuns).set({ responsibleUserId: userId }).where(eq(heartbeatRuns.id, f.runId));
const b = await send(f);
expect(b!.conversationId).not.toBe(a!.conversationId);
const [agent] = await server.db.insert(agents).values({ companyId: f.companyId, name: "Second agent", status: "active", adapterType: "process" }).returning();
const runId = randomUUID();
await server.db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: agent.id, status: "running", issueId: f.issueId, responsibleUserId: userId });
await server.db.update(issues).set({ assigneeAgentId: agent.id, executionRunId: runId }).where(eq(issues.id, f.issueId));
const c = await send({ ...f, agentId: agent.id, runId });
expect(new Set([a!.conversationId, b!.conversationId, c!.conversationId]).size).toBe(3);
await expect(issueService(server.db).addComment(a!.conversationId, "Wrong agent", { agentId: agent.id, runId })).rejects.toThrow(/Only this conversation/);
await expect(issueService(server.db).addComment(b!.conversationId, "Bypass", { agentId: f.agentId, runId: f.runId })).rejects.toThrow(/earlier session/);
});
it("delivers to its own chat while preserving pending questions and the original handoff completion", async () => {
const f = await fixture(), svc = issueService(server.db);
const own = await svc.create(f.companyId, { title: "Own chat", assigneeAgentId: f.agentId,
conversationAgentId: f.agentId, conversationUserId: f.responsibleUserId!, conversationState: "waiting", status: "in_review" });
const [coordinator] = await server.db.insert(agents).values({ companyId: f.companyId, name: "Coordinator", status: "active", adapterType: "process" }).returning();
const origin = await svc.create(f.companyId, { title: "Origin chat", assigneeAgentId: coordinator.id,
conversationAgentId: coordinator.id, conversationUserId: f.responsibleUserId!, conversationState: "waiting", status: "in_review" });
await recordAcceptedChatHandoff(server.db, (await svc.getById(f.issueId))!, origin);
const [question] = await server.db.insert(issueThreadInteractions).values({ companyId: f.companyId, issueId: own.id,
kind: "request_confirmation", status: "pending", payload: { version: 1, prompt: "Proceed?" } }).returning();
expect(await send(f)).toMatchObject({ conversationId: own.id });
expect(await server.db.select().from(issueComments).where(eq(issueComments.issueId, origin.id))).toEqual([]);
expect(await server.db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, question.id))).toEqual([question]);
expect(await server.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(1);
await svc.update(f.issueId, { status: "done" });
expect(await server.db.select().from(chatCompletionDeliveries).where(eq(chatCompletionDeliveries.taskId, f.issueId)))
.toMatchObject([{ status: "pending", responseCommentId: null }]);
expect(await server.db.select().from(chatTaskHandoffs).where(eq(chatTaskHandoffs.taskId, f.issueId)))
.toMatchObject([{ conversationId: origin.id, agentId: coordinator.id }]);
});
it.each(["ask", "planning", "review", "watchdog", "stopped", "stale", "missing-human", "revoked", "private-task", "private-project", "private-ancestor", "paused-agent"])("rejects %s before creating a chat", async kind => {
const f = await fixture();
if (kind === "ask" || kind === "planning") await server.db.update(issues).set({ workMode: kind }).where(eq(issues.id, f.issueId));
if (kind === "review") await server.db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, nativeReviewInteractionId: randomUUID(), nativeReviewDecisionId: randomUUID() } }).where(eq(heartbeatRuns.id, f.runId));
if (kind === "watchdog") await server.db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, taskWatchdog: true, watchedIssueId: f.issueId } }).where(eq(heartbeatRuns.id, f.runId));
if (kind === "stopped") await server.db.update(heartbeatRuns).set({ resultJson: { executionCancellation: { state: "requested" } } }).where(eq(heartbeatRuns.id, f.runId));
if (kind === "stale") await server.db.update(issues).set({ executionRunId: null }).where(eq(issues.id, f.issueId));
if (kind === "missing-human") await server.db.update(heartbeatRuns).set({ responsibleUserId: null }).where(eq(heartbeatRuns.id, f.runId));
if (kind === "revoked") await server.db.delete(companyMemberships).where(eq(companyMemberships.principalId, f.responsibleUserId!));
if (kind === "private-task") await server.db.update(issues).set({ visibility: "private" }).where(eq(issues.id, f.issueId));
if (kind === "private-project") await server.db.update(projects).set({ visibility: "private", privacyOwnerUserId: f.responsibleUserId }).where(eq(projects.id, f.projectId));
if (kind === "private-ancestor") {
await server.db.update(issues).set({ visibility: "private" }).where(eq(issues.id, f.blockerId));
await server.db.update(issues).set({ parentId: f.blockerId, privacyParentIssueId: f.blockerId, privacyRootIssueId: f.blockerId }).where(eq(issues.id, f.issueId));
}
if (kind === "paused-agent") await server.db.update(agents).set({ status: "paused" }).where(eq(agents.id, f.agentId));
await expect(send(f)).rejects.toThrow();
expect((await f.snapshot()).comments).toHaveLength(0);
expect((await f.snapshot()).issues.filter(i => i.conversationAgentId)).toHaveLength(0);
});
it("rejects forged destinations and server-owned provenance, and respects the feature gate", async () => {
const f = await fixture();
expect((await httpSend(f, { ...input, agentId: f.agentId })).status).toBe(400);
await instanceSettingsService(server.db).updateExperimental({ enableAgentChat: false });
try { expect((await httpSend(f)).status).toBe(404); }
finally { await instanceSettingsService(server.db).updateExperimental({ enableAgentChat: true }); }
const receipt = await send(f);
const [comment] = await server.db.select().from(issueComments).where(eq(issueComments.id, receipt!.commentId));
await expect(issueService(server.db).addComment(f.issueId, "Forged source", { agentId: f.agentId, runId: f.runId }, { metadata: comment.metadata! })).rejects.toThrow(/server-owned/);
});
it("keeps unseen concurrent arrivals unread with exact comment cutoffs and monotonic receipts", async () => {
const f = await fixture();
const a = (await send(f))!, b = (await send(f, { ...input, idempotencyKey: "later" }))!;
await server.db.update(issueComments).set({ createdAt: sql`'2026-10-30 12:00:00.123456+00'::timestamptz` }).where(eq(issueComments.id, a.commentId));
await server.db.update(issueComments).set({ createdAt: sql`'2026-10-30 12:00:00.123789+00'::timestamptz` }).where(eq(issueComments.id, b.commentId));
const cookie = await server.humanSession(f.responsibleUserId!);
const mark = (id: string) => fetch(`${server.apiUrl}/api/issues/${a.conversationId}/read`, { method: "POST", headers: { Cookie: cookie, Origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ throughCommentId: id }) });
const unread = async () => (await withConversationReadState(server.db, f.companyId, f.responsibleUserId!, [{ id: a.conversationId }]))[0].isUnreadForMe;
const response = await mark(a.commentId);
expect(response.status, await response.text()).toBe(200);
expect(await unread()).toBe(true);
expect((await mark(b.commentId)).status).toBe(200);
expect(await unread()).toBe(false);
await mark(a.commentId);
expect(await unread()).toBe(false);
const foreign = await server.fixture({ connectionScenario: "fresh" });
const foreignMessage = (await send(foreign))!;
expect((await mark(foreignMessage.commentId)).status).toBe(404);
const chats = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/chats`, { headers: { Cookie: cookie } });
expect(chats.status).toBe(200);
expect(await chats.json()).toMatchObject([{ id: a.conversationId, isUnreadForMe: false }]);
});
});
@@ -29,9 +29,9 @@ import {
issues,
} from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./helpers/embedded-postgres.js";
recoveryPostgresSupport as support,
startRecoveryPostgres,
} from "./helpers/recovery-postgres.js";
import { issueService } from "../services/issues.js";
import { documentService } from "../services/documents.js";
import { getTaskPlanContext } from "../services/task-plan-context.js";
@@ -58,16 +58,15 @@ import {
heartbeatService,
} from "../services/heartbeat.js";
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)(
"persistent agent conversations",
() => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let database: Awaited<ReturnType<typeof startRecoveryPostgres>>;
let db: ReturnType<typeof createDb>;
let companyId: string;
let agentId: string;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase(
database = await startRecoveryPostgres(
"paperclip-agent-conversations-",
);
db = createDb(database.connectionString);
@@ -61038,7 +61038,8 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
const beforeComments = await db
.select({ id: issueComments.id })
.from(issueComments)
.where(eq(issueComments.issueId, conversation.issueId));
.where(eq(issueComments.issueId, conversation.issueId))
.orderBy(issueComments.id);
const beforeWakes = wakeup.mock.calls.length;
const providerRuntime = runtime.endpoints.get(endpoint.id)!;
const beforeProvider = {
@@ -61195,7 +61196,8 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
db
.select({ id: issueComments.id })
.from(issueComments)
.where(eq(issueComments.issueId, conversation.issueId)),
.where(eq(issueComments.issueId, conversation.issueId))
.orderBy(issueComments.id),
).resolves.toEqual(beforeComments);
expect(wakeup.mock.calls.length).toBe(beforeWakes);
expect({
@@ -5,7 +5,7 @@ import { and, asc, eq } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { agents, agentWakeupRequests, chatCompletionDeliveries as deliveries, chatTaskHandoffs as handoffs,
companies, createDb, documents, environmentLeases, heartbeatRuns, issueComments, issueRecoveryActions, issueThreadInteractions, issues } from "@paperclipai/db";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { recoveryPostgresSupport as support, startRecoveryPostgres } from "./helpers/recovery-postgres.js";
import { settleInterruptedNativeBootstrap, terminalizeLegacyExecution } from "../services/legacy-execution-recovery.js";
import { getExecutionBlocker } from "../services/execution-blocker.js";
import { settleUnrecoverableExecutions } from "../services/execution-recovery-resolution.js";
@@ -16,12 +16,11 @@ import { instanceSettingsService } from "../services/instance-settings.js";
import { chatCompletionDeliveryService, isCompletedOnboardingHandoffWake, prepareChatCompletionTurn, recordChatCompletion, recordChatHandoff } from "../services/chat-completion-delivery.js";
import { heartbeatService, shouldQueueFollowupForRunningIssueWake } from "../services/heartbeat.js";
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("chat completion delivery", () => {
let db: ReturnType<typeof createDb>;
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let temporary: Awaited<ReturnType<typeof startRecoveryPostgres>>;
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase("chat-completion-"); db = createDb(temporary.connectionString);
temporary = await startRecoveryPostgres("chat-completion-"); db = createDb(temporary.connectionString);
await instanceSettingsService(db).updateExperimental({ enableAgentChat: true });
}, 30_000);
afterAll(async () => { await temporary?.cleanup(); });
@@ -11,9 +11,8 @@ import { issueService } from "../services/issues.js";
import { documentService } from "../services/documents.js";
import { activityService } from "../services/activity.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import { getEmbeddedPostgresTestSupport } from "./helpers/embedded-postgres.js";
import { recoveryPostgresSupport as support } from "./helpers/recovery-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
(support.supported ? describe : describe.skip)("chat project tool handoff", () => {
let server: Awaited<ReturnType<typeof startRunnerApiTestServer>>;
const originalSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
@@ -23,6 +23,7 @@ const apiPrefixes: Record<string, string> = {
"agents.ts": "/api",
"agent-project-access.ts": "/api",
"agent-commentary.ts": "/api",
"agent-chat-messages.ts": "/api",
"agent-avatars.ts": "/api",
"agent-profile-avatar.ts": "/api",
"announcements.ts": "/api",
+2
View File
@@ -127,6 +127,7 @@ import {
import { smokeLabRoutes } from "./routes/smoke-lab.js";
import { costRoutes } from "./routes/costs.js";
import { agentCommentaryRoutes } from "./routes/agent-commentary.js";
import { agentChatMessageRoutes } from "./routes/agent-chat-messages.js";
import { activityRoutes } from "./routes/activity.js";
import { dashboardRoutes } from "./routes/dashboard.js";
import { attentionRoutes } from "./routes/attention.js";
@@ -672,6 +673,7 @@ export async function createApp(
api.use(companySkillPolicyRoutes(db));
api.use(inboxAgentPolicyRoutes(db));
api.use(agentCommentaryRoutes(db));
api.use(agentChatMessageRoutes(db));
api.use(builtInAgentRoutes(db));
api.use(summarySlotRoutes(db));
api.use(statusCardRoutes(db));
+22
View File
@@ -0,0 +1,22 @@
import { Router } from "express";
import type { Db } from "@paperclipai/db";
import { forbidden } from "../errors.js";
import { sendAgentChatMessage } from "../services/agent-chat-messages.js";
import { assertCompanyAccess } from "./authz.js";
export function agentChatMessageRoutes(db: Db) {
const router = Router();
router.post("/agents/me/chat/messages", async (req, res) => {
if (req.actor.type !== "agent" || !req.actor.agentId || !req.actor.companyId || !req.actor.runId) {
throw forbidden("An authenticated task run is required");
}
assertCompanyAccess(req, req.actor.companyId);
const receipt = await sendAgentChatMessage(db, {
companyId: req.actor.companyId, agentId: req.actor.agentId, runId: req.actor.runId, agentApiKeyId: req.actor.keyId,
keyScope: req.actor.keyScope, onBehalfOfUserId: req.actor.onBehalfOfUserId,
authorizingUserId: req.actor.authorizingUserId, source: req.actor.source,
}, req.body);
res.status(receipt!.replayed ? 200 : 201).json(receipt);
});
return router;
}
+20 -4
View File
@@ -10,6 +10,8 @@ import { issueSummariesQuerySchema, type IssueSummary } from "@paperclipai/share
import { listIssueSummaries } from "../services/issue-summaries.js";
import { assertNoCaseHandoffMutation } from "../services/heartbeat/case-handoff-lifecycle.js";
import { assertLegacyRunTaskOwnership } from "../legacy-run-task-ownership.js";
import { withConversationReadState } from "../services/agent-chat-read-state.js";
import { markIssueReadSchema } from "@paperclipai/shared";
import { enqueueFastResponse } from "../services/fast-responses.js";
import { hasRequiredWorkspaceRecovery, LEGACY_WORKSPACE_RECOVERY_SCHEMA } from "../services/workspace-restore-recovery-state.js";
import { hasUnverifiedNativeWorkspaceFinalizationOwner } from "../services/native-runtime/native-workspace-finalization-recovery-state.js";
@@ -12106,11 +12108,22 @@ export function issueRoutes(
res.status(403).json({ error: "Board user context required" });
return;
}
const input = markIssueReadSchema.parse(req.body ?? {});
let readAt: Date | SQL = new Date();
if (input.throughCommentId) {
if (!issue.conversationAgentId || issue.conversationUserId !== req.actor.userId) throw forbidden("Only the chat owner can mark a conversation message read");
const [comment] = await db.select({ createdAt: sql<string>`${issueComments.createdAt}::text` }).from(issueComments).where(and(
eq(issueComments.id, input.throughCommentId), eq(issueComments.companyId, issue.companyId), eq(issueComments.issueId, issue.id),
isNull(issueComments.deletedAt),
));
if (!comment) throw notFound("Chat message not found");
readAt = sql`${comment.createdAt}::timestamptz`;
}
const readState = await svc.markRead(
issue.companyId,
issue.id,
req.actor.userId,
new Date(),
readAt,
);
const actor = getActorInfo(req);
await logActivity(db, {
@@ -18544,7 +18557,7 @@ export function issueRoutes(
if (req.actor.type !== "board" || !req.actor.userId) throw forbidden("Board user access required");
if (!(await instanceSettings.getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled");
const conversations = await svc.listConversations(companyId, req.actor.userId);
res.json(await filterIssuesForActor(req, conversations));
res.json(await withConversationReadState(db, companyId, req.actor.userId, await filterIssuesForActor(req, conversations)));
});
// GET stays read-only. POST resolves the single chat on explicit add or first send/upload.
@@ -18560,7 +18573,10 @@ export function issueRoutes(
const agent = resolved.agent;
const existing = await svc.getConversation(companyId, agent.id, req.actor.userId);
if (existing && !(await assertIssueReadAllowed(req, res, existing))) return;
if (existing || method === "get") { res.json(existing); return; }
if (existing || method === "get") {
res.json(existing ? (await withConversationReadState(db, companyId, req.actor.userId, [existing]))[0] : null);
return;
}
const issue = await svc.create(companyId, {
title: `Chat with ${agent.name}`, assigneeAgentId: agent.id,
conversationAgentId: agent.id, conversationUserId: req.actor.userId,
@@ -18569,7 +18585,7 @@ export function issueRoutes(
await logActivity(db, { companyId, actorType: "user", actorId: req.actor.userId,
action: "issue.conversation_opened", entityType: "issue", entityId: issue.id,
details: { agentId: agent.id } });
res.json(issue);
res.json((await withConversationReadState(db, companyId, req.actor.userId, [issue]))[0]);
});
}
+13 -1
View File
@@ -38,6 +38,8 @@ import {
slackSearchConfigSchema,
// Agent
submitAgentCommentarySchema,
sendChatMessageSchema,
markIssueReadSchema,
agentCommentaryQuerySchema,
AGENT_PALETTE_IDS,
AGENT_AVATAR_SIZES,
@@ -1670,6 +1672,7 @@ function resolveOperationAuthLevel(
|| /^\/api\/companies\/\{companyId\}\/agents\/\{agentId\}\/grok-binding(?:\/(?:routine|verify|retry|stop|recover))?$/.test(path)) return "board";
if (PUBLIC_OPERATIONS.has(key)) return "public";
if (key === "POST /api/companies/{companyId}/agent-commentary") return "agent_heartbeat";
if (key === "POST /api/agents/me/chat/messages") return "agent_heartbeat";
if (method.toUpperCase() === "GET" && path.startsWith("/api/companies/{companyId}/agent-commentary")) return "board";
if (key === "POST /api/mcp/project-tools" || key === "POST /api/companies/{companyId}/slack/tasks/{issueId}/tools") return "agent_run";
if (RUNTIME_TOOLS_OPERATIONS.has(key)) return "runtime_tools";
@@ -4736,7 +4739,7 @@ registry.registerPath({
path: "/api/issues/{id}/read",
tags: ["issues"],
summary: "Mark an issue as read",
request: { params: z.object({ id: z.string() }) },
request: { params: z.object({ id: z.string() }), body: { ...jsonBody(markIssueReadSchema), required: false } },
responses: { 200: r.ok(), 401: r.unauthorized },
});
@@ -5760,6 +5763,15 @@ registry.registerPath({
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
});
registry.registerPath({
method: "post", path: "/api/agents/me/chat/messages", tags: ["agents"],
summary: "Send a task message to the agent's own chat",
description: "Requires the assigned agent's active standard task run, standard credentials and an active responsible human. Resolves or creates that agent's conversation automatically. Company visibility, task permissions, Stop and the shared cross-issue run cap apply. Equivalent retries do not spend another slot. Does not wake the chat agent or change task status.",
request: { body: jsonBody(sendChatMessageSchema) },
responses: { 200: r.ok(), 201: { ...r.ok(), description: "Message saved" }, 400: r.badRequest,
401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict, 429: r.tooManyRequests },
});
const agentCommentaryAcknowledgementSchema = z.object({
id: z.string().uuid(),
kind: z.enum(["complaint", "suggestion"]),
+4
View File
@@ -480,6 +480,10 @@ export function activityService(db: Db) {
.where(
and(
eq(heartbeatRuns.companyId, companyId),
sql`(not exists (select 1 from ${issues} where ${issues.id} = ${issueId}
and ${issues.companyId} = ${companyId} and ${issues.conversationAgentId} is not null)
or coalesce(${heartbeatRuns.nativeIssueId}::text, ${heartbeatRuns.issueId}::text,
${heartbeatRuns.contextSnapshot} ->> 'issueId', ${heartbeatRuns.contextSnapshot} ->> 'taskId') = ${issueId})`,
...(selectedRunIds ? [inArray(heartbeatRuns.id, selectedRunIds)] : []),
or(
eq(heartbeatRuns.issueId, issueId),
+193
View File
@@ -0,0 +1,193 @@
import { createHash } from "node:crypto";
import { and, eq, isNull, sql } from "drizzle-orm";
import { agentApiKeys, agents, companies, companyMemberships, heartbeatRuns, issueComments, issues, nativeRunResults, type Db } from "@paperclipai/db";
import { agentApiKeyScopeSchema, isUuidLike, sendChatMessageSchema, type AgentApiKeyScope } from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound, tooManyRequests } from "../errors.js";
import { agentRunWritesRevoked, assertAgentRunWriteAllowed } from "../agent-run-cancellation.js";
import { authorizationService, canActorReadIssuePrivacy, type AuthorizationActor } from "./authorization.js";
import { persistActivity, publishActivity, type ActivityPublication } from "./activity-log.js";
import { instanceSettingsService } from "./instance-settings.js";
import { issueService } from "./issues.js";
import { issueTreeControlService } from "./issue-tree-control.js";
import { resolveActorSourceTrustForIssue } from "./source-trust.js";
import { resolveTaskWatchdogMutationScope } from "./task-watchdog-scope.js";
import { readNativeReviewAssignmentContext } from "./native-runtime/native-review-participant.js";
import { nativeRunKeyScope } from "./native-runtime/native-skill-test-scope.js";
import { crossIssueInfluenceLimitError, observeCrossIssueInfluence } from "./cross-issue-influence-limit.js";
type Actor = { companyId: string; agentId: string; runId: string; agentApiKeyId?: string | null;
keyScope?: AgentApiKeyScope | null; onBehalfOfUserId?: string | null;
authorizingUserId?: string | null; source?: AuthorizationActor["source"] };
export interface ChatMessageReceipt {
commentId: string;
conversationId: string;
chatUrl: string;
sourceTaskId: string;
replayed: boolean;
}
function runTask(run: typeof heartbeatRuns.$inferSelect) {
return run.nativeIssueId ?? run.issueId ?? run.contextSnapshot?.issueId ?? run.contextSnapshot?.taskId;
}
export async function sendAgentChatMessage(
db: Db,
actor: Actor,
value: unknown,
options: { authorizeNative?: (tx: Db) => Promise<unknown>; receiptOnly?: boolean } = {},
): Promise<ChatMessageReceipt | null> {
const parsed = sendChatMessageSchema.safeParse(value);
if (!parsed.success) throw badRequest("Chat messages require body and idempotencyKey only", parsed.error.issues);
if (![actor.companyId, actor.agentId, actor.runId].every(isUuidLike)) throw forbidden("An authenticated task run is required");
const credentialScope = agentApiKeyScopeSchema.safeParse(actor.keyScope ?? { kind: "standard" });
if (!credentialScope.success) throw forbidden("The agent credential scope is invalid");
if (credentialScope.data.kind !== "standard") throw forbidden("Scoped test and task bridge credentials cannot publish agent chat messages");
const input = parsed.data;
const contentHash = createHash("sha256").update(input.body).digest("hex");
const publications: ActivityPublication[] = [];
const result = await db.transaction(async transaction => {
const tx = transaction as unknown as Db;
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`issue-privacy-tree:${actor.companyId}`}, 0))`);
const runWhere = and(eq(heartbeatRuns.id, actor.runId), eq(heartbeatRuns.companyId, actor.companyId), eq(heartbeatRuns.agentId, actor.agentId));
const [initial] = await tx.select().from(heartbeatRuns).where(runWhere);
const sourceId = initial && runTask(initial);
if (typeof sourceId !== "string" || !isUuidLike(sourceId)) throw forbidden("Chat delivery requires a task-bound run");
const sourceQuery = () => tx.select().from(issues).where(and(eq(issues.id, sourceId), eq(issues.companyId, actor.companyId)));
const [initialSource] = await sourceQuery();
if (!initialSource) throw forbidden("This run no longer owns the source task");
let source = initialSource;
const contextQuery = () => tx.select({ run: heartbeatRuns, agent: agents }).from(heartbeatRuns)
.innerJoin(agents, and(eq(agents.id, heartbeatRuns.agentId), eq(agents.companyId, heartbeatRuns.companyId)))
.where(runWhere);
const validateContext = (context: { run: typeof heartbeatRuns.$inferSelect; agent: typeof agents.$inferSelect } | undefined) => {
if (!context || context.run.status !== "running" || agentRunWritesRevoked(context.run)
|| runTask(context.run) !== sourceId || source.assigneeAgentId !== actor.agentId
|| source.executionRunId !== actor.runId || (source.checkoutRunId && source.checkoutRunId !== actor.runId)
|| ["paused", "terminated", "pending_approval", "error"].includes(context.agent.status)) {
throw forbidden("This run no longer owns the source task");
}
if (source.conversationAgentId) throw forbidden("Reply normally in this conversation; send_chat_message is for execution tasks");
if (nativeRunKeyScope({ contextSnapshot: context.run.contextSnapshot, issueId: source.id, workMode: source.workMode }).kind === "skill_test") {
throw forbidden("Skill-test runs cannot publish agent chat messages");
}
if (source.workMode !== "standard" || ["done", "cancelled"].includes(source.status)
|| readNativeReviewAssignmentContext(context.run.contextSnapshot)) {
throw forbidden("Chat delivery requires an ordinary task in standard execution mode");
}
return context;
};
const [initialContext] = await contextQuery();
const context = validateContext(initialContext);
if (!(await instanceSettingsService(tx).getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled");
const userId = context.run.responsibleUserId;
if (!userId) throw forbidden("This task has no responsible human to receive the message");
if (actor.onBehalfOfUserId !== undefined && actor.onBehalfOfUserId !== userId) throw forbidden("The authenticated responsible human no longer matches this run");
const assertCurrentKey = async (lock: boolean) => {
if (!actor.agentApiKeyId) return;
const query = tx.select().from(agentApiKeys).where(and(eq(agentApiKeys.id, actor.agentApiKeyId),
eq(agentApiKeys.companyId, actor.companyId), eq(agentApiKeys.agentId, actor.agentId), isNull(agentApiKeys.revokedAt)));
const [key] = lock ? await query.for("share") : await query;
const currentScope = key && agentApiKeyScopeSchema.safeParse(key.scopeConfig ?? { kind: "standard" });
if (!key || !currentScope?.success || JSON.stringify(currentScope.data) !== JSON.stringify(credentialScope.data)
|| (key.responsibleUserId?.trim() || null) !== (actor.onBehalfOfUserId ?? userId)) {
throw forbidden("The agent key was revoked or its authority changed");
}
};
await assertCurrentKey(false);
const [membership] = await tx.select({ id: companyMemberships.id }).from(companyMemberships).where(and(
eq(companyMemberships.companyId, actor.companyId), eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, userId), eq(companyMemberships.status, "active"),
)).for("share");
if (!membership) throw forbidden("The responsible human is no longer an active company member");
const authActor: AuthorizationActor = { type: "agent", ...actor, keyId: actor.agentApiKeyId, keyScope: credentialScope.data,
source: actor.source ?? "agent_jwt", onBehalfOfUserId: actor.onBehalfOfUserId ?? userId };
const authorize = async (issueId: string, action: "issue:read" | "issue:comment") => {
const decision = await authorizationService(tx).decide({ actor: authActor, action,
resource: { type: "issue", companyId: actor.companyId, issueId } });
if (!decision.allowed) throw forbidden(decision.explanation);
};
await authorize(source.id, "issue:read");
if (!(await canActorReadIssuePrivacy(tx, { type: "none" }, source))) {
throw forbidden("Restricted task content cannot be sent to a company-visible chat");
}
const svc = issueService(tx);
let conversation = await svc.getConversation(actor.companyId, actor.agentId, userId);
if (!conversation && !options.receiptOnly) {
conversation = await svc.create(actor.companyId, {
title: `Chat with ${context.agent.name}`, assigneeAgentId: actor.agentId,
conversationAgentId: actor.agentId, conversationUserId: userId,
conversationState: "waiting", status: "in_review", createdByAgentId: actor.agentId,
responsibleUserId: userId, trustExplicitResponsibleUserId: true,
});
const opened = await persistActivity(tx, { companyId: actor.companyId, actorType: "agent", actorId: actor.agentId,
agentId: actor.agentId, runId: actor.runId, action: "issue.conversation_opened", entityType: "issue", entityId: conversation.id,
details: { agentId: actor.agentId, conversationUserId: userId } });
publications.push(opened.publication);
}
if (conversation) await tx.select({ id: issues.id }).from(issues).where(and(
eq(issues.id, conversation.id), eq(issues.companyId, actor.companyId),
)).for("update");
const [lockedSource] = await sourceQuery().for("update");
if (!lockedSource) throw forbidden("This run no longer owns the source task");
source = lockedSource;
if (options.authorizeNative) await options.authorizeNative(tx);
const [lockedContext] = await contextQuery().for("update");
const current = validateContext(lockedContext);
if (current.run.responsibleUserId !== userId) throw forbidden("The responsible human changed before this message was saved");
await assertCurrentKey(true);
if ((await resolveTaskWatchdogMutationScope(tx, { ...actor, type: "agent" })).kind !== "none") {
throw forbidden("Chat delivery requires an ordinary task in standard execution mode");
}
await assertAgentRunWriteAllowed(tx, actor.companyId, actor);
if (await issueTreeControlService(tx).getActivePauseHoldGate(actor.companyId, source.id)) throw forbidden("This task is paused");
const [finished] = await tx.select({ id: nativeRunResults.id }).from(nativeRunResults).where(and(
eq(nativeRunResults.companyId, actor.companyId), eq(nativeRunResults.runId, actor.runId), eq(nativeRunResults.schemaStatus, "accepted"),
)).limit(1);
if (finished) throw forbidden("Send the message before finishing the run");
if (!(await instanceSettingsService(tx).getExperimental()).enableAgentChat) throw notFound("Agent Chat is disabled");
await authorize(source.id, "issue:read");
if (!conversation) return null;
await authorize(conversation.id, "issue:comment");
const recipientDecision = await authorizationService(tx).decide({ actor: { type: "board", userId, source: "session", ignoreInstanceAdmin: true },
action: "issue:read", resource: { type: "issue", companyId: actor.companyId, issueId: conversation.id } });
if (!recipientDecision.allowed) throw forbidden("The responsible human cannot access this chat");
const requestId = `chat:${source.id}:${createHash("sha256").update(input.idempotencyKey).digest("hex")}`;
const [prior] = await tx.select().from(issueComments).where(and(eq(issueComments.companyId, actor.companyId),
eq(issueComments.issueId, conversation.id), eq(issueComments.authorAgentId, actor.agentId), eq(issueComments.clientRequestId, requestId)));
const [company] = await tx.select({ prefix: companies.issuePrefix }).from(companies).where(eq(companies.id, actor.companyId));
const receipt = (commentId: string, replayed: boolean): ChatMessageReceipt => ({ commentId, conversationId: conversation!.id,
chatUrl: `/${company.prefix}/chats/${actor.agentId}`, sourceTaskId: source.id, replayed });
if (prior) {
if (prior.metadata?.chatMessage?.contentHash !== contentHash) {
if (options.receiptOnly) return null;
throw conflict("Chat message retry key was already used with different content");
}
return receipt(prior.id, true);
}
if (options.receiptOnly) return null;
const influence = await observeCrossIssueInfluence(tx, { companyId: actor.companyId, agentId: actor.agentId,
runId: actor.runId, responsibleUserId: userId, targetIssueId: conversation.id,
targetIssueIdentifier: conversation.identifier, kind: "comment" });
if (influence && !influence.allowed) {
const denial = crossIssueInfluenceLimitError(influence, { actorLabel: current.agent.name,
assigneeLabel: current.agent.name, issueIdentifier: conversation.identifier });
throw tooManyRequests(denial.error, denial.details);
}
const sourceTrust = await resolveActorSourceTrustForIssue({ db: tx, issue: source,
actor: { actorType: "agent", actorId: actor.agentId, agentId: actor.agentId, runId: actor.runId } });
const comment = await svc.addComment(conversation.id, input.body, { agentId: actor.agentId, runId: actor.runId }, {
clientRequestId: requestId, sourceTrust, proactiveChatMessage: { sourceTaskId: source.id, userId },
metadata: { version: 1, chatMessage: { sourceTaskId: source.id, sourceTaskIdentifier: source.identifier!, sourceRunId: actor.runId, contentHash },
sections: [{ rows: [{ type: "issue_link", issueId: source.id, identifier: source.identifier, label: "Source task" }] }] },
}, tx);
const activity = await persistActivity(tx, { companyId: actor.companyId, actorType: "agent", actorId: actor.agentId,
agentId: actor.agentId, runId: actor.runId, agentApiKeyId: actor.agentApiKeyId,
action: "issue.comment_added", entityType: "issue", entityId: conversation.id,
details: { commentId: comment.id, identifier: conversation.identifier, conversationUserId: userId,
conversationAgentId: actor.agentId, sourceTaskId: source.id } });
publications.push(activity.publication);
return receipt(comment.id, false);
});
for (const publication of publications) publishActivity(publication);
return result;
}
@@ -0,0 +1,21 @@
import { and, eq, inArray, sql } from "drizzle-orm";
import { issueComments, issueReadStates, type Db } from "@paperclipai/db";
export async function withConversationReadState<T extends { id: string }>(db: Db, companyId: string, userId: string, conversations: T[]) {
if (!conversations.length) return [] as Array<T & { isUnreadForMe: boolean; lastExternalCommentAt: Date | null }>;
const rows = await db.select({
issueId: issueComments.issueId,
latest: sql<Date>`max(${issueComments.createdAt})`,
unread: sql<boolean>`bool_or(${issueComments.createdAt} > coalesce(${issueReadStates.lastReadAt}, to_timestamp(0)))`,
}).from(issueComments).leftJoin(issueReadStates, and(
eq(issueReadStates.companyId, companyId), eq(issueReadStates.issueId, issueComments.issueId), eq(issueReadStates.userId, userId),
)).where(and(eq(issueComments.companyId, companyId), inArray(issueComments.issueId, conversations.map(chat => chat.id)),
sql`${issueComments.deletedAt} is null`, sql`${issueComments.authorAgentId} is not null`,
sql`${issueComments.authorType} is distinct from 'system'`,
sql`${issueComments.presentation} ->> 'kind' is distinct from 'system_notice'`,
eq(issueComments.origin, "comment"),
)).groupBy(issueComments.issueId);
const byId = new Map(rows.map(row => [row.issueId, row]));
return conversations.map(chat => ({ ...chat, isUnreadForMe: byId.get(chat.id)?.unread ?? false,
lastExternalCommentAt: byId.get(chat.id)?.latest ?? null }));
}
@@ -526,6 +526,9 @@ export async function undeliveredConversationComments(
eq(issueComments.companyId, companyId),
eq(issueComments.issueId, issueId),
isNull(issueComments.deletedAt),
sql`${issueComments.authorUserId} is not null`,
isNull(issueComments.authorAgentId),
eq(issueComments.origin, "comment"),
sql`${issueComments.clientRequestId} is not null`,
sql`not exists (select 1 from ${agentWakeupRequests} where ${agentWakeupRequests.companyId} = ${companyId}
and ${agentWakeupRequests.idempotencyKey} = 'conversation-comment:' || ${issueComments.id}::text)`,
+26 -7
View File
@@ -30,7 +30,7 @@ import { requestRestorePointDeletion } from "./git-restore-point-ledger.js";
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
import { recordChatHandoff, recordAcceptedChatHandoff, lockAcceptedChatHandoffSource, recordChatCompletion, existingChatCompletionReply, acknowledgeChatCompletionReply } from "./chat-completion-delivery.js";
import { mirrorSlackBoardComment, slackBoardReplyBindings } from "./slack-board-messages.js";
import { assertAgentRunWriteAllowed } from "../agent-run-cancellation.js";
import { agentRunWritesRevoked, assertAgentRunWriteAllowed } from "../agent-run-cancellation.js";
import { assertLegacyRunTaskOwnership } from "../legacy-run-task-ownership.js";
import { retryIdempotentDatabaseOperation } from "../database-retry.js";
import { externalConversationStateSql, nonIdleSlackIssueCondition, resumeSlackConversation } from "./slack-conversation-state.js";
@@ -143,7 +143,7 @@ import {
isUuidLike,
normalizeIssueIdentifier as normalizeIssueReferenceIdentifier,
} from "@paperclipai/shared";
import { conflict, HttpError, notFound, unprocessable } from "../errors.js";
import { conflict, forbidden, HttpError, notFound, unprocessable } from "../errors.js";
import { isForeignKeyViolation } from "../db-errors.js";
import { logger } from "../middleware/logger.js";
import { parseObject } from "../adapters/utils.js";
@@ -1685,6 +1685,7 @@ function withAgentCommentAuthorizationMetadata(
const reason = authorizationReason?.trim() || "internal_agent_write";
return {
version: 1,
...(metadata?.chatMessage ? { chatMessage: metadata.chatMessage } : {}),
...(metadata?.sourceRunId !== undefined
? { sourceRunId: metadata.sourceRunId }
: {}),
@@ -8615,7 +8616,7 @@ export function issueService(db: Db) {
companyId: string,
issueId: string,
userId: string,
readAt: Date = new Date(),
readAt: Date | SQL = new Date(),
) => {
const now = new Date();
const [row] = await db
@@ -8634,7 +8635,7 @@ export function issueService(db: Db) {
issueReadStates.userId,
],
set: {
lastReadAt: readAt,
lastReadAt: sql`greatest(${issueReadStates.lastReadAt}, excluded.last_read_at)`,
updatedAt: now,
},
})
@@ -12827,6 +12828,7 @@ export function issueService(db: Db) {
sourceTrust?: typeof issueComments.$inferInsert.sourceTrust;
createdAt?: Date | string | null;
clientRequestId?: string;
proactiveChatMessage?: { sourceTaskId: string; userId: string };
/** Server-only: authenticated Paperclip messages also belong in the Slack thread. */
mirrorToSlack?: boolean;
},
@@ -12883,11 +12885,28 @@ export function issueService(db: Db) {
return existing;
}
}
if (options?.metadata?.chatMessage && !options.proactiveChatMessage) {
throw forbidden("Chat message provenance is server-owned");
}
if (issue.conversationAgentId && actor.agentId && issue.conversationAgentId !== actor.agentId) {
throw forbidden("Only this conversation's agent can post agent messages");
}
if (issue.conversationAgentId && actor.agentId && !actor.runId) {
throw forbidden("Agent chat messages require an authenticated run");
}
if (issue.conversationAgentId && actor.runId) {
const [run] = await dbOrTx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, actor.runId));
const [current] = await dbOrTx.select().from(issues).where(eq(issues.id, issueId));
if (run?.status === "cancelled") throw conflict("This conversation turn was cancelled; it cannot post a reply");
if (run?.contextSnapshot?.conversationSessionGeneration !== current.conversationSessionGeneration) {
if (agentRunWritesRevoked(run)) throw conflict("This conversation turn was cancelled; it cannot post a reply");
const runTaskId = run?.nativeIssueId ?? run?.issueId ?? run?.contextSnapshot?.issueId ?? run?.contextSnapshot?.taskId;
if (options?.proactiveChatMessage) {
if (run?.status !== "running" || run.agentId !== actor.agentId || run.companyId !== issue.companyId
|| runTaskId !== options.proactiveChatMessage.sourceTaskId || runTaskId === issueId
|| current.conversationUserId !== options.proactiveChatMessage.userId
|| run.responsibleUserId !== current.conversationUserId) {
throw forbidden("Invalid background chat message authority");
}
} else if (runTaskId !== issueId || run?.contextSnapshot?.conversationSessionGeneration !== current.conversationSessionGeneration) {
throw conflict("Conversation session changed; this reply belongs to an earlier session");
}
}
@@ -13022,7 +13041,7 @@ export function issueService(db: Db) {
: (options?.metadata ?? null),
);
let comment: typeof issueComments.$inferSelect | null = null;
if (createdByRunId) {
if (createdByRunId && !options?.proactiveChatMessage) {
const existing = await dbOrTx
.select()
.from(issueComments)
@@ -120,7 +120,7 @@ describe("PaperclipRunnerToolAuthority", () => {
issueId,
runId,
});
expect(authority.definitions()).toHaveLength(50);
expect(authority.definitions()).toHaveLength(51);
expect(authority.definitions().map(tool => tool.name)).toEqual(expect.arrayContaining([
"get_workspace", "list_workspaces", "select_workspace", "prepare_repository",
]));
@@ -26,6 +26,7 @@ import { createReadStream } from "node:fs";
import { publicChatTaskUrl } from "../chat-task-url.js";
import { agentCommentaryToolInputSchema } from "@paperclipai/shared";
import { submitAgentCommentary } from "../agent-commentary.js";
import { sendAgentChatMessage } from "../agent-chat-messages.js";
import type { createAssignedMcpTools } from "./assigned-mcp-tools.js";
import { captureRunnerToolResult, fitRunnerToolResultPage, READ_TOOL_RESULT, READ_TOOL_RESULT_DEFINITION, readToolResultSchema, RUNNER_TOOL_RESULT_MAX_BYTES } from "./runner-tool-results.js";
import { assertAssignableAgent } from "../agent-assignability.js";
@@ -124,6 +125,7 @@ import {
const EXTERNAL_WORKSPACE_OPERATIONS = new Set(["get_workspace", "list_workspaces", "select_workspace", "prepare_repository", "register_deliverable"]);
const IMPLEMENTED_OPERATIONS = new Set([
"send_chat_message",
"submit_complaint", "submit_suggestion",
"read_agent_instructions", "update_agent_instructions", "get_agent_instruction_history", "restore_agent_instructions",
"search_api", "call_api", "hire_agent",
@@ -432,6 +434,7 @@ export class PaperclipRunnerToolAuthority {
// retry, without ever falling through to an uncertain mutation.
let recovered: unknown;
if (call.tool === "set_task_title") recovered = await this.#setTaskTitle(input, true);
else if (call.tool === "send_chat_message") recovered = await this.#sendChatMessage(input, this.#privacyActor(run), true);
else if (call.tool === "submit_complaint" || call.tool === "submit_suggestion") recovered = await this.#submitCommentary(call.tool, input, true);
else if (call.tool === "create_task") recovered = await this.#createTask(input, null, true);
else if (call.tool === "request_human_input") recovered = await this.#requestHumanInput(input, null, true);
@@ -957,6 +960,7 @@ export class PaperclipRunnerToolAuthority {
return { approval, tasks: tasks.filter(row => !readable || readable.has(row.issue.id)).map(row => row.issue) };
}
case "report_progress": return this.#reportProgress(input);
case "send_chat_message": return this.#sendChatMessage(input, this.#privacyActor(context.run));
case "request_human_input": return this.#requestHumanInput(input,
(await captureRunIdentity(this.db, this.binding, { readScope: "identity" })).context?.id ?? null);
case "create_task": return this.#createTask(input,
@@ -1484,6 +1488,14 @@ export class PaperclipRunnerToolAuthority {
return { interactionId: review.interaction.id, status: expectedStatus };
}
async #sendChatMessage(input: Record<string, unknown>, actor: AuthorizationActor, receiptOnly = false) {
const result = await sendAgentChatMessage(this.db, { ...this.binding, keyScope: actor.keyScope,
onBehalfOfUserId: actor.onBehalfOfUserId, authorizingUserId: actor.authorizingUserId, source: actor.source }, input, {
authorizeNative: tx => this.#lockAuthorizedMutationContext(tx), receiptOnly,
});
return result ?? undefined;
}
async #reportProgress(input: Record<string, unknown>): Promise<unknown> {
const body = typeof input.body === "string" ? input.body.trim() : "";
const idempotencyKey = typeof input.idempotencyKey === "string" ? input.idempotencyKey.trim() : "";
@@ -41,6 +41,7 @@ function words(text: string): string[] {
}
function dedicatedTools(method: string, path: string): string[] {
if (method === "POST" && path === "/api/agents/me/chat/messages") return ["send_chat_message"];
if (/\/companies\/\{[^}]+\}\/workflows$/.test(path)) return method === "GET" ? ["list_workflows"] : method === "POST" ? ["create_workflow"] : [];
if (/\/workflows\/\{[^}]+\}$/.test(path)) return method === "GET" ? ["read_workflow"] : method === "PATCH" ? ["update_workflow"] : [];
if (/\/issues\/\{[^}]+\}\/title$/.test(path) && method === "PUT") return ["set_task_title"];