mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 01:24:30 +01:00
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>
This commit is contained in:
1 parent
9c91c097bd
commit
2caedfe7b0
13 files changed
+283
-43
No files matched your search
@@ -93,12 +93,27 @@ describe("Speko hosted provider transport", () => {
|
||||
expect(body.systemPrompt).toContain("answer_question with its exact interaction and question IDs");
|
||||
expect(body.systemPrompt).toContain("Do not repeatedly poll while pending.");
|
||||
});
|
||||
it("uses the hosted phone endpoint with scoped secrets and returns no media or phone number", async () => {
|
||||
it("falls back to a supported S2S voice only for S2S_VOICE_UNSUPPORTED 400s", async () => {
|
||||
let calls = 0;
|
||||
const transport = vi.fn<typeof fetch>(async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) return Response.json({ code: "S2S_VOICE_UNSUPPORTED" }, { status: 400 });
|
||||
return Response.json({ id: input.agentId });
|
||||
});
|
||||
await createSpekoProvider("key", transport).configureVoiceDefaults(input.agentId);
|
||||
expect(transport).toHaveBeenCalledTimes(2);
|
||||
expect(JSON.parse(String(transport.mock.calls[1]![1]?.body))).toMatchObject({ runMode: "s2s", voice: "marin", idleRePrompts: { enabled: false } });
|
||||
|
||||
const unrelated = vi.fn<typeof fetch>(async () => Response.json({ code: "VALIDATION_ERROR" }, { status: 400 }));
|
||||
await expect(createSpekoProvider("key", unrelated).configureVoiceDefaults(input.agentId)).rejects.toMatchObject({ httpStatus: 400, providerCode: "VALIDATION_ERROR" });
|
||||
expect(unrelated).toHaveBeenCalledOnce();
|
||||
});
|
||||
it("uses the hosted phone endpoint with scoped secrets, optional firstMessage, and returns no media or phone number", async () => {
|
||||
const transport = vi.fn<typeof fetch>(async () => Response.json({ sessionId: "phone_test", status: "dialing", to: "+12015551234", callControlId: "private-control" }));
|
||||
expect(await createSpekoProvider("private-key", transport).createPhoneSession({ ...input, to: "+12015551234" })).toEqual({ sessionId: "phone_test", status: "dialing" });
|
||||
expect(await createSpekoProvider("private-key", transport).createPhoneSession({ ...input, to: "+12015551234", firstMessage: "The staging deploy succeeded. Ready to ship?" })).toEqual({ sessionId: "phone_test", status: "dialing" });
|
||||
expect(transport).toHaveBeenCalledOnce();
|
||||
expect(transport.mock.calls[0]![0]).toBe("https://api.speko.dev/v1/sessions/phone");
|
||||
expect(JSON.parse(String(transport.mock.calls[0]![1]?.body))).toMatchObject({ runMode: "s2s", maxDurationSeconds: 600, toolSecrets: { paperclip_session_token: input.toolToken } });
|
||||
expect(JSON.parse(String(transport.mock.calls[0]![1]?.body))).toMatchObject({ runMode: "s2s", maxDurationSeconds: 600, firstMessage: "The staging deploy succeeded. Ready to ship?", toolSecrets: { paperclip_session_token: input.toolToken } });
|
||||
});
|
||||
it("validates phone parameters before changing the persona or placing a call", async () => {
|
||||
const transport = vi.fn<typeof fetch>(); const provider = createSpekoProvider("key", transport);
|
||||
|
||||
@@ -24,7 +24,7 @@ import { VOICE_RESULT_NOTIFICATION } from "@paperclipai/shared";
|
||||
import { createHash, createHmac, randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { applyPendingMigrations, chatActions, instanceUserRoles, principalPermissionGrants, environments, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, heartbeatRuns, toolProfileBindings, chatVoiceCallbacks, agentWakeupRequests, issueThreadInteractions, issueQuestionResponseDeliveries, issueComments, agents, chatConversations, chatDeliveries, chatEndpoints, chatPublications, chatVoiceReplies, chatVoiceSessions, chatVoiceToolCalls, companies, companyMemberships, companySecrets, connectionGrants, connectionGrantMembers, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, issues, toolApplications, toolConnections, toolConnectionInstalls } from "@paperclipai/db";
|
||||
import { applyPendingMigrations, chatActions, instanceUserRoles, principalPermissionGrants, environments, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, heartbeatRuns, toolCatalogEntries, toolProfileBindings, chatVoiceCallbacks, agentWakeupRequests, issueThreadInteractions, issueQuestionResponseDeliveries, issueComments, agents, chatConversations, chatDeliveries, chatEndpoints, chatPublications, chatVoiceReplies, chatVoiceSessions, chatVoiceToolCalls, companies, companyMemberships, companySecrets, connectionGrants, connectionGrantMembers, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, issues, toolApplications, toolConnections, toolConnectionInstalls } from "@paperclipai/db";
|
||||
import { configureSpekoSessionTools } from "../services/voice/speko-tool-setup.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { chatChannelService } from "../services/chat-channels.js";
|
||||
@@ -1716,6 +1716,7 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
expect(comments.map(c => c.body)).toEqual(["Help draft a public inquiry", "Keep it short"]);
|
||||
expect(comments.every(c => !c.authorUserId && c.sourceTrust?.preset === "low_trust_review")).toBe(true);
|
||||
const [task] = await db.select().from(issues).where(eq(issues.id, f.call.intakeIssueId!));
|
||||
expect(task.title).toBe("Help draft a public inquiry");
|
||||
expect(task.executionWorkspaceSettings).toMatchObject({mode: "isolated_workspace", workspaceStrategy: {type: "cloud_sandbox"}});
|
||||
expect(task.executionPolicy?.authorizationPolicy).toMatchObject({trustBoundary: {issueIds: [task.id], allowedToolClasses: [], allowedSecretBindingIds: []}});
|
||||
await db.update(chatVoicePhoneLines).set({guestIntake: false}).where(eq(chatVoicePhoneLines.endpointId, f.endpointId));
|
||||
@@ -2249,17 +2250,80 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
const tools = await f.gateway.listToolsForSession(f.gatewaySession.token);
|
||||
const tool = tools.find(tool => tool.providerType === "paperclip_speko_voice");
|
||||
expect(tool).toMatchObject({ upstreamToolName: "call_my_phone", connectionId: f.connectionId });
|
||||
const call = { sessionToken: f.gatewaySession.token, tool: tool!.name, parameters: {}, idempotencyKey: randomUUID() };
|
||||
const message = "The release build is green. Should I deploy to production?";
|
||||
const call = { sessionToken: f.gatewaySession.token, tool: tool!.name, parameters: { message }, idempotencyKey: randomUUID() };
|
||||
const result = await f.gateway.executeTool(call);
|
||||
expect(result).toBeDefined();
|
||||
expect(f.transport.createPhoneSession).toHaveBeenCalledOnce();
|
||||
expect(f.transport.createPhoneSession.mock.calls[0]![0]).toMatchObject({ to: "+12015551234", bindingId: expect.any(String) });
|
||||
expect(f.transport.createPhoneSession.mock.calls[0]![0]).toMatchObject({
|
||||
to: "+12015551234",
|
||||
bindingId: expect.any(String),
|
||||
firstMessage: message,
|
||||
systemPrompt: expect.stringContaining(message),
|
||||
});
|
||||
await f.gateway.executeTool(call);
|
||||
expect(f.transport.createPhoneSession).toHaveBeenCalledOnce();
|
||||
const sessions = await db.select().from(chatVoiceSessions).where(eq(chatVoiceSessions.endpointId, f.endpointId));
|
||||
expect(sessions.filter(s => s.mode === "outbound_phone")).toHaveLength(1);
|
||||
const outbound = sessions.filter(s => s.mode === "outbound_phone");
|
||||
expect(outbound).toHaveLength(1);
|
||||
expect(JSON.stringify(result)).not.toContain("+12015551234");
|
||||
expect(JSON.stringify(result)).not.toContain("short-lived-media-token");
|
||||
|
||||
// Verify outbound call transcript is projected onto the bound issue idempotently.
|
||||
const now = new Date().toISOString();
|
||||
await db.update(chatVoiceSessions).set({ state: "ended", endedAt: new Date() }).where(eq(chatVoiceSessions.id, outbound[0]!.id));
|
||||
f.transport.callReport.mockImplementation(((async (sessionId: string) => ({
|
||||
complete: true,
|
||||
transcript: sessionId === outbound[0]!.providerSessionId ? [
|
||||
{ id: "agent-0", index: 0, speaker: "agent", text: message, startedAt: now, endedAt: null, interrupted: false },
|
||||
{ id: "caller-1", index: 1, speaker: "caller", text: "Yes, go ahead and deploy to prod.", startedAt: now, endedAt: null, interrupted: false },
|
||||
] : [],
|
||||
costMicroUsd: "80000",
|
||||
durationSeconds: 18,
|
||||
providerUpdatedAt: new Date(),
|
||||
})) as unknown) as never);
|
||||
await f.service.reconcile(1000);
|
||||
const docs = documentService(db);
|
||||
const transcriptDoc = await docs.getIssueDocumentByKey(f.issueId, `voice-transcript-${outbound[0]!.id}`);
|
||||
expect(transcriptDoc?.title).toBe("Outbound phone call transcript");
|
||||
expect(transcriptDoc?.body).toContain(message);
|
||||
expect(transcriptDoc?.body).toContain("Yes, go ahead and deploy to prod.");
|
||||
// Reconciling an unchanged report keeps a single revision.
|
||||
await db.update(chatVoiceReports).set({ nextCheckAt: new Date(0) }).where(eq(chatVoiceReports.sessionId, outbound[0]!.id));
|
||||
await f.service.reconcile(1000);
|
||||
const repeatedDoc = await docs.getIssueDocumentByKey(f.issueId, `voice-transcript-${outbound[0]!.id}`);
|
||||
expect(repeatedDoc?.latestRevisionId).toBe(transcriptDoc?.latestRevisionId);
|
||||
});
|
||||
|
||||
it("redacts sensitive credentials from call_my_phone opening messages and enforces saved catalog schema", async () => {
|
||||
const f = await phoneToolFixture();
|
||||
// An unrefreshed legacy catalog entry with empty schema properties must not accept message.
|
||||
await db.update(toolCatalogEntries).set({
|
||||
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
||||
versionHash: "legacy-empty-schema-hash",
|
||||
schemaHash: "legacy-empty-schema-hash",
|
||||
}).where(eq(toolCatalogEntries.connectionId, f.connectionId));
|
||||
const legacyTools = await spekoToolsForSession(db, f.gatewaySession);
|
||||
expect(legacyTools[0]?.parametersSchema).toEqual({ type: "object", properties: {}, additionalProperties: false });
|
||||
await expect(executeSpekoVoiceTool(db, f.gatewaySession, f.endpointId, { message: "Should be blocked on legacy schema" }, randomUUID())).rejects.toThrow();
|
||||
|
||||
// Refresh via owner sync restores the message schema; credentials inside message are redacted before egress.
|
||||
const [endpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, f.endpointId));
|
||||
await db.transaction(tx => syncSpekoVoiceTools(tx, endpoint!, f.callerId, true));
|
||||
await executeSpekoVoiceTool(db, f.gatewaySession, f.endpointId, { message: "Deploy ready. Do not leak sk-ant-api03-1234567890abcdef1234567890abcdef!" }, randomUUID());
|
||||
const sent = f.transport.createPhoneSession.mock.calls[0]![0] as unknown as { firstMessage?: string; systemPrompt: string };
|
||||
expect(sent.firstMessage).not.toContain("sk-ant-api03");
|
||||
expect(sent.systemPrompt).not.toContain("sk-ant-api03");
|
||||
expect(sent.systemPrompt).toContain("Always use answer_question");
|
||||
|
||||
// A max-length message whose sanitization expands characters (e.g. @here) stays <= 2000 and succeeds cleanly.
|
||||
const f2 = await phoneToolFixture();
|
||||
const expanded = `@here ${"a".repeat(1994)}`;
|
||||
expect(expanded.length).toBe(2000);
|
||||
await executeSpekoVoiceTool(db, f2.gatewaySession, f2.endpointId, { message: expanded }, randomUUID());
|
||||
const sent2 = f2.transport.createPhoneSession.mock.calls[0]![0] as unknown as { firstMessage?: string };
|
||||
expect(sent2.firstMessage).toBeDefined();
|
||||
expect(sent2.firstMessage!.length).toBeLessThanOrEqual(2000);
|
||||
});
|
||||
it("does not restore an agent's removed tool binding when callback settings are saved again", async () => {
|
||||
const f = await phoneToolFixture();
|
||||
@@ -2320,4 +2384,34 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu
|
||||
} finally { if (previousUrl === undefined) delete process.env.PAPERCLIP_API_URL; else process.env.PAPERCLIP_API_URL = previousUrl; }
|
||||
});
|
||||
|
||||
it("allows finishing verified Speko setup without requiring a browser voice test and rejects unverified drafts", async () => {
|
||||
const f = await phoneToolFixture();
|
||||
const testStartedAt = new Date().toISOString();
|
||||
const chat = chatChannelService(db, {
|
||||
heartbeat: { wakeup: vi.fn(async () => ({ accepted: true })) },
|
||||
deferWebhookProcessing: true,
|
||||
});
|
||||
try {
|
||||
// Missing provider verification (runtimeGeneration 0) must still fail closed.
|
||||
await db.update(chatEndpoints).set({
|
||||
status: "verifying",
|
||||
providerAccountId: null,
|
||||
botExternalId: null,
|
||||
setup: { step: "test", runtimeGeneration: 0, testStartedAt } as never,
|
||||
}).where(eq(chatEndpoints.id, f.endpointId));
|
||||
await expect(chat.finishSlackSetup(f.endpointId, f.callerId)).rejects.toMatchObject({ status: 409 });
|
||||
|
||||
// Verified provider + runtimeGeneration >= 1 activates cleanly without a browser mic test.
|
||||
await db.update(chatEndpoints).set({
|
||||
status: "verifying",
|
||||
providerAccountId: `org_${f.companyId}`,
|
||||
botExternalId: "agent_speko_finish_test",
|
||||
setup: { step: "test", runtimeGeneration: 1, testStartedAt } as never,
|
||||
}).where(eq(chatEndpoints.id, f.endpointId));
|
||||
const activated = await chat.finishSlackSetup(f.endpointId, f.callerId);
|
||||
expect(activated.status).toBe("active");
|
||||
expect(activated.setup.step).toBe("complete");
|
||||
} finally { await chat.shutdown(); }
|
||||
});
|
||||
|
||||
});
|
||||
Reference in new issue
Block a user