Files
PaperClipAI/server/src/services/chat-channels/setup-probes.ts
T
DottaandPaperclip 2caedfe7b0 feat(voice): support outbound call messages, issue transcripts, and optional setup test for Speko (#23052)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The Speko voice connection lets agents call a person's saved phone
number via `call_my_phone` and receive inbound phone calls that create
or continue tasks.
> - Outbound `call_my_phone` took no parameters, so the agent could not
speak a specific update or question when the person picked up, and
outbound call transcripts were not projected onto the bound issue.
> - Setup also blocked activation behind a mandatory two-turn browser
microphone test and failed with HTTP 400 when a Speko persona used a
cascade-only voice on `runMode: "s2s"`.
> - This pull request adds an optional `message` parameter to
`call_my_phone`, projects outbound and inbound phone call transcripts
onto the bound issue, derives inbound task titles from the caller's
request, falls back to a supported S2S voice on 400, and lets verified
Speko setups finish without a browser microphone test.
> - The benefit is that both agent-initiated phone updates (with
responses recorded in the issue) and inbound phone tasks work end-to-end
with reliable setup and full issue transcript visibility.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Speko voice connection setup (`POST
/api/chat-endpoints/:endpointId/finish`, `ChatEndpointSetup`), outbound
agent phone callbacks (`call_my_phone`), outbound/inbound phone
transcript projection (`voiceCallReports`), and incoming low-trust task
creation (`voiceInboundService`).

**Subsystem affected**
Cross-cutting (multiple of the above)

**Current behavior**
- `call_my_phone` accepts no arguments (`properties: {}`) and always
opens with `"Hi, this is your Paperclip agent calling as requested. Is
now a good time?"`.
- Outbound `call.pre_call` sets `idleRePrompts` to `"I'm still working
on it."` every 10 seconds.
- `voiceCallReports.projectTranscript` only writes the transcript
document onto issues for `guest_intake` sessions, omitting authenticated
outbound and inbound phone calls.
- Incoming `guest_intake` tasks always use the generic title `"Incoming
phone conversation"`.
- Activating a Speko connection requires completing a two-turn browser
microphone conversation before **Call my phone** and **Incoming calls**
settings become accessible.
- `configureVoiceDefaults` fails with HTTP 400 if the selected Speko
persona uses a cascade-only voice when switching to `runMode: "s2s"`.

**Proposed behavior**
- `call_my_phone` accepts an optional `message` string (1–2000 chars)
while still strictly rejecting recipient/phone arguments. Speko speaks
`message` immediately as `firstMessage` and instructs the voice model to
submit caller replies via `submit_request`.
- Outbound `call.pre_call` uses a 25-second conversational check-in
re-prompt instead of `"I'm still working on it."`.
- `voiceCallReports.projectTranscript` writes `"Outbound phone call
transcript"` / `"Phone conversation transcript"` onto the bound issue
for all phone calls (`outbound_phone` and `inbound_phone`), preserving
quarantine guards for `guest_intake`.
- Incoming `guest_intake` tasks derive a readable title from the
caller's first spoken request.
- Verified Speko connections can finish setup via `POST
/api/chat-endpoints/:endpointId/finish` (**Skip test & finish**) without
requiring a browser microphone test.
- `configureVoiceDefaults` falls back to S2S voice `"marin"` if Speko
returns HTTP 400 on `runMode: "s2s"`.

**Reason and benefit**
Makes both core phone workflows usable in production: agents can call an
opted-in person to deliver a concrete update and capture their spoken
response in the issue, callers can phone an agent to start a titled
task, and operators can complete Speko setup without a microphone or
cascade-voice failure.

**Breaking changes**
None. `message` is optional on `call_my_phone` so `{}` callers remain
compatible; existing recipient restrictions (`additionalProperties:
false`) and quarantine boundaries are preserved.

## What Changed

- Added optional `message` parameter to `call_my_phone` in
`server/src/services/voice/speko-agent-tools.ts`, threaded
`openingMessage` into `voice-session-service.ts`, `voice-prompts.ts`
(`buildOutboundPhoneVoicePrompt`), and `speko-provider.ts`
(`createPhoneSession`), and updated `speko-skill.ts`.
- Extended `voiceCallReports.projectTranscript` in
`server/src/services/voice/voice-call-reports.ts` to project phone call
transcripts onto the bound issue for `outbound_phone` and
`inbound_phone` sessions while keeping `guest_intake` quarantine
enforcement intact.
- Derived readable issue titles from the first `submit_request` text for
incoming `guest_intake` calls and refined outbound `call.pre_call`
`idleRePrompts` in `server/src/services/voice/voice-inbound-service.ts`.
- Added S2S voice fallback (`voice: "marin"`) on HTTP 400 in
`speko-provider.ts` (`configureVoiceDefaults`).
- Enabled optional test skip (`POST
/api/chat-endpoints/:endpointId/finish`) for verified Speko endpoints in
`server/src/services/chat-channels/setup-probes.ts` and added a **Skip
test & finish** button in
`ui/src/pages/apps/chat/ChatEndpointSetup.tsx`.
- Updated `packages/shared/src/app-definitions/speko.json` guidance
copy.
- Added unit and real-Postgres integration regressions in
`server/src/__tests__/speko-provider.test.ts` and
`server/src/__tests__/voice-session-store.integration.test.ts`.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/server typecheck && pnpm --filter @paperclipai/ui
typecheck` — passed (0 errors across server layers and UI).
- `pnpm exec vitest run server/src/__tests__/speko-provider.test.ts
server/src/__tests__/speko-protocol.test.ts
server/src/__tests__/speko-call-report.test.ts
server/src/routes/voice-sessions.auth.test.ts` — 53/53 passed.
- `pnpm exec vitest run
server/src/__tests__/voice-session-store.integration.test.ts` — 133/133
passed (including new `call_my_phone` message + outbound transcript
projection, derived inbound title, and Speko finish-without-test
regressions).
- `pnpm exec vitest run ui/src/api/voiceSessions.test.ts
ui/src/components/voice/ ui/src/lib/voice-call-attempt.test.ts
ui/src/lib/voice-session-controller.test.ts
ui/src/lib/voice-transcript.test.ts
server/src/__tests__/chat-channels/slack-setup-and-registration.integration.test.ts`
— 161/161 passed.
- `pnpm run check:token-gates` — all 4 gates clean.
- Live local verification against Speko API + webhook-only Cloudflare
quick tunnel: verified Speko setup + `/finish` activation, live
`claude_local` MCP discovery of `call_my_phone` with `message`, live
Speko session create/inspect/end + signed `call.status`/`call.report`
callbacks through tunnel, and inbound `call.pre_call` + `submit_request`
creating a titled task.

## Risks

- Low risk. Additive optional schema field on `call_my_phone` (still
rejects unknown keys such as `to`). No database migrations required.
Transcript projection for authenticated calls writes only to the
session's bound issue under the existing per-session advisory lock. Live
PSTN audio still requires real-phone end-to-end confirmation after
staging rollout.

## Model Used

- Google Gemini 4 Neon (High) via Antigravity with tool use and local
code execution.

## 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 tests locally and they pass
- [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>
2026-11-27 06:52:33 -06:00

365 lines
16 KiB
TypeScript

import { notifyChatConnectionHealth } from "./connection-health-notifications.js";
import type { ConnectionManagementContext } from "../connection-management.js";
import type { EndpointRow, DbOrTransaction } from "./runtime-types.js";
import { notifyChatEndpointWork } from "../chat-work-notifications.js";
import { chatCredentialMutationLease } from "../chat-credential-mutation-lease.js";
import { githubChatManagementService } from "../chat-github-management.js";
import {
and,
asc,
desc,
eq,
gte,
inArray,
isNotNull,
or,
sql,
} from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
chatActions,
chatConversations,
chatDeliveries,
chatEndpoints,
chatIdentityLinks,
chatMessageLinks,
chatPublications,
heartbeatRuns,
issueComments,
toolConnections,
} from "@paperclipai/db";
import type {
ChatEndpoint,
ChatEndpointSetupState,
} from "@paperclipai/shared";
import {
conflict,
forbidden,
notFound,
} from "../../errors.js";
import {
logActivity,
} from "../activity-log.js";
import {
githubRunReplyState,
} from "../chat-run-publications.js";
import type { EndpointRecord } from "./runtime-types.js";
type SetupProbesOptions = {
endpointRecord: (endpointId: string) => Promise<EndpointRecord | null>;
withCredentialMutationLease: ReturnType<typeof chatCredentialMutationLease>;
fetchImpl: typeof fetch;
findAuthorizedIdentityLink: (endpoint: EndpointRow, userId: string) => Promise<{ id: string } | null>;
runtimeGeneration: (setup: ChatEndpointSetupState) => number;
lockCurrentPrincipalAuthorization: (tx: DbOrTransaction, endpoint: EndpointRow, principalId: string) => Promise<{ allowed: boolean }>;
get: (endpointId: string) => Promise<ChatEndpoint>;
setupTestActivationBarrier?: () => Promise<void>;
};
export function createSetupProbes(db: Db, options: SetupProbesOptions) {
const { endpointRecord, withCredentialMutationLease, fetchImpl, findAuthorizedIdentityLink, runtimeGeneration, lockCurrentPrincipalAuthorization, get } = options;
async function setupTestStatus(endpointId: string, userId: string) {
const record = await endpointRecord(endpointId);
if (!record) throw notFound("Chat endpoint not found");
const startedAt = record.endpoint.setup.testStartedAt;
if (!startedAt) return { messageReceivedAt: null };
const links = await db.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(
eq(chatIdentityLinks.companyId, record.endpoint.companyId), eq(chatIdentityLinks.endpointId, endpointId),
eq(chatIdentityLinks.paperclipUserId, userId), eq(chatIdentityLinks.status, "linked"),
));
if (!links.length) return { messageReceivedAt: null };
const principalIds = links.map((link) => link.principalId);
const [delivery, command] = await Promise.all([
db.select({ at: chatDeliveries.createdAt }).from(chatDeliveries).where(and(
eq(chatDeliveries.companyId, record.endpoint.companyId), eq(chatDeliveries.endpointId, endpointId),
inArray(chatDeliveries.principalId, principalIds), gte(chatDeliveries.createdAt, new Date(startedAt)),
inArray(chatDeliveries.eventKind, ["message", "mention"]),
)).orderBy(asc(chatDeliveries.createdAt)).limit(1).then((rows) => rows[0]),
db.select({ at: chatActions.createdAt }).from(chatActions).where(and(
eq(chatActions.companyId, record.endpoint.companyId), eq(chatActions.endpointId, endpointId),
inArray(chatActions.principalId, principalIds), eq(chatActions.kind, "slash_task_start"), gte(chatActions.createdAt, new Date(startedAt)),
)).orderBy(asc(chatActions.createdAt)).limit(1).then((rows) => rows[0]),
]);
const at = [delivery?.at, command?.at].filter((value): value is Date => Boolean(value)).sort((a, b) => a.getTime() - b.getTime())[0];
return { messageReceivedAt: at?.toISOString() ?? null };
}
async function test(endpointId: string, finishOptions?: { optionalSlackTestForUser: string }, managementContext?: ConnectionManagementContext) {
await managementContext?.reauthorize();
const initial = await endpointRecord(endpointId);
if (!initial) throw notFound("Chat endpoint not found");
return withCredentialMutationLease(
initial.endpoint,
async (credentialLease) => {
// Reload only after owning the same lane as reconnect, pause, removal,
// and credential rotation. Qualification and activation must describe
// one exact provider runtime, never a setup snapshot that a concurrent
// reconnect has already superseded.
const record = await endpointRecord(endpointId);
if (!record) throw notFound("Chat endpoint not found");
const endpoint = record.endpoint;
if (endpoint.status !== "verifying" || endpoint.setup.step !== "test") {
throw conflict("This connection is not waiting for a setup test", {
code: "chat_endpoint_not_testing",
});
}
if (endpoint.provider === "github" && endpoint.setup.github) {
const verified = await githubChatManagementService(db, fetchImpl).verification(endpoint.id);
if (!verified.ready && !(finishOptions?.optionalSlackTestForUser && verified.connectionReady)) throw conflict("Finish verifying the App, repositories, and assigned agent's tools before activating this bot", { checks: verified.checks });
}
const testStartedAtValue = endpoint.setup.testStartedAt;
const testStartedAt = testStartedAtValue
? new Date(testStartedAtValue)
: null;
const optionalSlackTest = Boolean(finishOptions?.optionalSlackTestForUser);
if (optionalSlackTest) {
if (endpoint.provider === "speko") {
if (!endpoint.providerAccountId || !endpoint.botExternalId || runtimeGeneration(endpoint.setup) < 1) {
throw conflict("Verify the Speko connection before finishing setup");
}
} else {
if (!["slack", "github"].includes(endpoint.provider) || !endpoint.setup.webhookVerifiedAt || !endpoint.providerAccountId) {
throw conflict("Verify the connection before finishing setup");
}
const linked = await findAuthorizedIdentityLink(endpoint, finishOptions!.optionalSlackTestForUser);
if (!linked) throw forbidden("Connect your account before finishing setup");
}
}
if (!optionalSlackTest) {
if (
!endpoint.lastEventAt ||
!testStartedAtValue ||
!testStartedAt ||
Number.isNaN(testStartedAt.getTime()) ||
endpoint.lastEventAt < testStartedAt
) {
throw conflict(
"Send the test message in the provider before completing setup",
{
code: "chat_test_message_missing",
},
);
}
const requiredTrigger =
["telegram", "imessage-photon"].includes(endpoint.provider)
? "direct_message"
: "subscribed_message";
const qualifyingDelivery = await db
.select({
id: chatDeliveries.id,
conversationId: chatDeliveries.conversationId,
processedAt: chatDeliveries.processedAt,
})
.from(chatDeliveries)
.where(
and(
eq(chatDeliveries.companyId, endpoint.companyId),
eq(chatDeliveries.endpointId, endpoint.id),
eq(chatDeliveries.state, "processed"),
gte(chatDeliveries.processedAt, testStartedAt),
sql`${chatDeliveries.normalizedEvent}->>'trigger' = ${requiredTrigger}`,
),
)
.orderBy(desc(chatDeliveries.processedAt))
.limit(1)
.then((rows) => rows[0] ?? null);
if (
!qualifyingDelivery?.conversationId ||
!qualifyingDelivery.processedAt
) {
throw conflict(
["telegram", "imessage-photon"].includes(endpoint.provider)
? "Send the test direct message before completing setup"
: "Reply once without mentioning the agent before completing setup",
{ code: "chat_test_follow_up_missing" },
);
}
const finalPublication = await db
.select({
commentId: chatPublications.commentId,
payload: chatPublications.payload,
})
.from(chatPublications)
.innerJoin(
issueComments,
and(
eq(issueComments.id, chatPublications.commentId),
eq(issueComments.companyId, chatPublications.companyId),
eq(issueComments.issueId, chatPublications.issueId),
eq(issueComments.authorType, "agent"),
eq(issueComments.authorAgentId, endpoint.assignedAgentId),
),
)
.innerJoin(
chatMessageLinks,
and(
eq(chatMessageLinks.companyId, chatPublications.companyId),
eq(chatMessageLinks.endpointId, chatPublications.endpointId),
eq(
chatMessageLinks.conversationId,
chatPublications.conversationId,
),
eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),
eq(chatMessageLinks.direction, "inbound"),
isNotNull(chatMessageLinks.commentId),
),
)
.innerJoin(
heartbeatRuns,
and(
eq(heartbeatRuns.id, issueComments.createdByRunId),
eq(heartbeatRuns.companyId, chatPublications.companyId),
eq(heartbeatRuns.agentId, endpoint.assignedAgentId),
eq(heartbeatRuns.status, "succeeded"),
eq(
sql<string>`${heartbeatRuns.contextSnapshot} ->> 'issueId'`,
sql<string>`${chatPublications.issueId}::text`,
),
or(
sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'wakeCommentId'`,
sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot} ->> 'commentId'`,
sql`coalesce(${heartbeatRuns.contextSnapshot} -> 'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,
),
),
)
.where(
and(
eq(chatPublications.companyId, endpoint.companyId),
eq(chatPublications.endpointId, endpoint.id),
eq(
chatPublications.conversationId,
qualifyingDelivery.conversationId,
),
eq(chatPublications.state, "published"),
gte(chatPublications.publishedAt, qualifyingDelivery.processedAt),
),
)
.orderBy(desc(chatPublications.publishedAt))
.then((rows) =>
rows.find(
(row) =>
row.payload.interactionId === undefined &&
row.payload.progressState === undefined &&
row.commentId !== null,
),
);
let githubToolReply = false;
if (!finalPublication && endpoint.provider === "github") {
const setupRuns = await db.select({ id: heartbeatRuns.id, issueId: chatConversations.issueId })
.from(heartbeatRuns)
.innerJoin(chatMessageLinks, and(
eq(chatMessageLinks.companyId, endpoint.companyId),
eq(chatMessageLinks.endpointId, endpoint.id),
eq(chatMessageLinks.deliveryId, qualifyingDelivery.id),
eq(chatMessageLinks.direction, "inbound"),
or(
sql`${chatMessageLinks.commentId}::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'`,
sql`coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? ${chatMessageLinks.commentId}::text`,
),
))
.innerJoin(chatConversations, and(
eq(chatConversations.id, qualifyingDelivery.conversationId),
eq(chatConversations.id, chatMessageLinks.conversationId),
eq(chatConversations.companyId, endpoint.companyId),
sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${chatConversations.issueId}::text`,
))
.where(and(eq(heartbeatRuns.companyId, endpoint.companyId),
eq(heartbeatRuns.agentId, endpoint.assignedAgentId), eq(heartbeatRuns.status, "succeeded")))
.orderBy(desc(heartbeatRuns.createdAt)).limit(20);
for (const run of setupRuns) {
if (await githubRunReplyState(db, { companyId: endpoint.companyId, endpointId: endpoint.id,
issueId: run.issueId, runId: run.id }) === "confirmed") {
githubToolReply = true;
break;
}
}
}
if (!finalPublication && !githubToolReply) {
throw conflict(
"Wait for the Paperclip agent to reply to the setup turn before completing setup",
{
code: "chat_test_round_trip_incomplete",
},
);
}
}
await options.setupTestActivationBarrier?.();
await managementContext?.reauthorize();
const expectedGeneration = runtimeGeneration(endpoint.setup);
await db.transaction(async (tx) => {
await credentialLease.assertOwned(tx);
if (optionalSlackTest && endpoint.provider !== "speko") {
const linked = await tx.select({ principalId: chatIdentityLinks.principalId }).from(chatIdentityLinks).where(and(
eq(chatIdentityLinks.endpointId, endpoint.id), eq(chatIdentityLinks.paperclipUserId, finishOptions!.optionalSlackTestForUser), eq(chatIdentityLinks.status, "linked"),
)).limit(1).then((rows) => rows[0]);
if (!linked || !(await lockCurrentPrincipalAuthorization(tx, endpoint, linked.principalId)).allowed) throw forbidden("Your connected account is no longer authorized");
}
await notifyChatEndpointWork(tx, endpoint.connectionId, endpoint.companyId);
const [activated] = await tx
.update(chatEndpoints)
.set({
status: "active",
setup: {
...endpoint.setup,
step: "complete",
testStartedAt: null,
testSkipped: optionalSlackTest,
},
healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",
activatedAt: endpoint.activatedAt ?? new Date(),
updatedAt: new Date(),
})
.where(
and(
eq(chatEndpoints.id, endpointId),
eq(chatEndpoints.status, "verifying"),
sql`${chatEndpoints.setup}->>'step' = 'test'`,
sql`coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::integer, 0) = ${expectedGeneration}`,
sql`${chatEndpoints.setup}->>'testStartedAt' = ${testStartedAtValue}`,
),
)
.returning({ id: chatEndpoints.id });
if (!activated) {
throw conflict("This setup test was superseded by a reconnect", {
code: "chat_endpoint_test_superseded",
});
}
await notifyChatConnectionHealth(tx, endpoint);
await tx
.update(toolConnections)
.set({
status: "active",
enabled: true,
healthStatus: "healthy",
healthMessage: optionalSlackTest ? "Connected; conversation test optional" : "Connected",
lastError: null,
healthCheckedAt: new Date(),
updatedAt: new Date(),
})
.where(eq(toolConnections.id, endpoint.connectionId));
if (optionalSlackTest) await logActivity(tx as unknown as Db, {
companyId: endpoint.companyId, ...(managementContext?.audit ?? { actorType: "user" as const, actorId: finishOptions!.optionalSlackTestForUser }),
action: "chat.setup_completed", entityType: "chat_endpoint", entityId: endpointId,
details: { conversationTestOptional: true },
});
await credentialLease.assertOwned(tx);
});
return get(endpointId);
},
);
}
return { setupTestStatus, test };
}