Merge branch 'codex/speko-voice-ui' into codex/speko-voice-qualification

* codex/speko-voice-ui:
  fix(voice): retain newly expired admissions until provider cleanup
  fix(voice): bound inbound admission and deliver live task guidance and questions
  fix(voice): clear rejected call admission before a new attempt
This commit is contained in:
Dotta committed 2026-10-09 15:30:55 -05:00
commit 4906aeadcd
9 files changed
+107 -59

No files matched your search

@@ -481,6 +481,21 @@ const support = await getEmbeddedPostgresTestSupport();
const push = () => f.service.pushReplies(25, f.companyId, f.endpointId);
return {...f, session, publication, push};
}
it("notifies phone questions once and waits for authorized retrieval before later answers", async () => {
const f = await pushFixture(), interactionId = randomUUID();
await db.insert(issueThreadInteractions).values({id: interactionId, companyId: f.companyId, issueId: f.issueId, kind: "ask_user_questions", status: "pending", addresseeUserId: f.callerId, effectiveResolverPolicy: "addressee_only", payload: {version: 1, questions: [{id: "color", prompt: "Which color?", selectionMode: "single", required: true, options: [{id: "cobalt", label: "Cobalt"}]}]}});
await db.update(chatPublications).set({payload: {text: "Which color?", interactionId}}).where(eq(chatPublications.id, f.publication.id));
const [later] = await db.insert(chatPublications).values({companyId: f.companyId, endpointId: f.endpointId, conversationId: f.conversationId, issueId: f.issueId, idempotencyKey: randomUUID(), state: "published", payload: {text: "Approved later answer"}}).returning();
await f.store.enqueuePublication(f.companyId, later.id);
await f.push(); await f.push();
expect(f.transport.sendCallMessage).toHaveBeenCalledOnce();
expect(f.transport.sendCallMessage.mock.calls[0]?.[1]).toContain("Call get_updates");
const [reply] = await db.select().from(chatVoiceReplies).where(eq(chatVoiceReplies.publicationId, f.publication.id));
expect(reply.deliveredAt).toBeNull();
expect(await f.store.runTool(f.toolInput("get_updates", {cursor: 0}))).toMatchObject({updates: [{question: {interactionId}}]});
await f.push();
expect(f.transport.sendCallMessage).toHaveBeenCalledTimes(2);
});
it("pushes a published phone answer exactly once across concurrent dispatch and restart", async () => {
const f = await pushFixture();
await Promise.all([f.push(), f.push()]); await f.push();
@@ -619,21 +634,44 @@ const support = await getEmbeddedPostgresTestSupport();
const response = await f.service.inbound.lifecycle(endpoint.publicId, signed.body, signed.headers);
const capability = (response as {toolSecrets: {paperclip_session_token: string}}).toolSecrets.paperclip_session_token;
const [call] = await db.select().from(chatVoiceInboundCalls).where(eq(chatVoiceInboundCalls.providerSessionId, providerSessionId));
const tool = (name: "submit_request" | "get_updates", args: unknown, toolId = randomUUID()) => {
const tool = async (name: "submit_request" | "get_updates", args: unknown, toolId = randomUUID()) => {
const signed = sign({session_id: providerSessionId, tool_call_id: toolId, idempotency_key: `${providerSessionId}:${toolId}`, tool: name, args});
return f.service.tool(endpoint.publicId, signed.body, {...signed.headers, authorization: `Bearer ${capability}`});
const result = await f.service.tool(endpoint.publicId, signed.body, {...signed.headers, authorization: `Bearer ${capability}`});
Object.assign(call, (await db.select().from(chatVoiceInboundCalls).where(eq(chatVoiceInboundCalls.id, call.id)))[0]);
return result;
};
return {...f, call, event, signed, sign, response, endpoint, capability, tool};
}
it("bounds admission and retains no task for abandoned public rings", async () => {
const f = await inboundFixture(true);
expect(f.call.intakeIssueId).toBeNull(); expect(f.call.sessionId).toBeNull();
expect(await f.tool("get_updates", {cursor: 0})).toMatchObject({status: "ready_for_intake"});
for (let i = 1; i < 10; i++) {
const sessionId = randomUUID();
const signed = f.sign({...f.event, call_id: sessionId, session_id: sessionId});
await f.service.inbound.lifecycle(f.endpoint.publicId, signed.body, signed.headers);
}
const blockedId = randomUUID(), blocked = f.sign({...f.event, call_id: blockedId, session_id: blockedId});
await expect(f.service.inbound.lifecycle(f.endpoint.publicId, blocked.body, blocked.headers)).rejects.toMatchObject({status: 409});
expect(await f.service.inbound.lifecycle(f.endpoint.publicId, f.signed.body, f.signed.headers)).toEqual(f.response);
expect(await db.select().from(issues).where(eq(issues.originId, f.endpointId))).toHaveLength(0);
expect((await db.select().from(chatVoiceSessions).where(eq(chatVoiceSessions.endpointId, f.endpointId))).map(session => session.id)).toEqual([f.sessionId]);
const ended = f.sign({type: "call.status", call_id: f.event.call_id, status: "ended"});
await f.service.inbound.lifecycle(f.endpoint.publicId, ended.body, ended.headers);
await db.update(chatVoiceInboundCalls).set({expiresAt: new Date(Date.now() - 8 * 86_400_000), updatedAt: new Date(Date.now() - 8 * 86_400_000)}).where(eq(chatVoiceInboundCalls.id, f.call.id));
await f.service.inbound.reconcile(100);
expect(await db.select().from(chatVoiceInboundCalls).where(eq(chatVoiceInboundCalls.id, f.call.id))).toHaveLength(0);
});
it("pins a connection-selected sandbox only to its new public task", async () => {
const sandboxId = randomUUID();
await db.insert(environments).values({id: sandboxId, name: `Phone sandbox ${sandboxId}`, driver: "sandbox", config: {provider: "daytona"}});
const f = await inboundFixture(true, sandboxId);
expect(f.call.intakeIssueId).toBeNull();
expect((await f.tool("submit_request", {text: "Hello"})).status).toBe("accepted");
const [task] = await db.select().from(issues).where(eq(issues.id, f.call.intakeIssueId!));
const [agent] = await db.select().from(agents).where(eq(agents.id, f.agentId));
expect(task.executionWorkspaceSettings).toMatchObject({mode: "isolated_workspace", environmentId: sandboxId, workspaceStrategy: {type: "cloud_sandbox"}});
expect(agent.defaultEnvironmentId).not.toBe(sandboxId);
expect((await f.tool("submit_request", {text: "Hello"})).status).toBe("accepted");
await db.update(issues).set({executionWorkspaceSettings: {mode: "isolated_workspace", environmentId: randomUUID()}}).where(eq(issues.id, task.id));
await expect(f.tool("get_updates", {cursor: 0})).rejects.toMatchObject({status: 403});
});
@@ -653,6 +691,9 @@ const support = await getEmbeddedPostgresTestSupport();
expect(f.response.systemPrompt).toContain("How much disk space do you have on your computer?");
expect(f.response.systemPrompt).toContain("What is the capital of France?");
expect(f.response.idleRePrompts).toMatchObject({enabled: true, delayMs: 5000, maxPrompts: 10, messages: ["I'm still working on it."]});
expect(f.call.intakeIssueId).toBeNull();
const first = await f.tool("submit_request", {text: "Help me draft a public inquiry"}, toolId);
expect(first).toMatchObject({status: "accepted", authorization: "guest_intake"});
const [task] = await db.select().from(issues).where(eq(issues.id, f.call.intakeIssueId!));
expect(task.description).toContain("You are on a live phone call");
expect(task.description).toContain("Immediately post a brief, caller-safe task comment");
@@ -660,8 +701,6 @@ const support = await getEmbeddedPostgresTestSupport();
const [conversation] = await db.select().from(chatConversations).where(eq(chatConversations.issueId, task.id));
expect(conversation.communicationGuidance).toContain("Keep your existing identity, runtime, tools");
expect(conversation.communicationGuidance).toContain("own low-trust task");
const first = await f.tool("submit_request", {text: "Help me draft a public inquiry"}, toolId);
expect(first).toMatchObject({status: "accepted", authorization: "guest_intake"});
expect(await f.tool("submit_request", {text: "Help me draft a public inquiry"}, toolId)).toEqual(first);
await expect(f.tool("submit_request", {text: "Changed replay"}, toolId)).rejects.toMatchObject({status: 409});
expect(await f.service.inbound.lifecycle(f.endpoint.publicId, f.signed.body, f.signed.headers)).toEqual(f.response);
@@ -715,6 +754,7 @@ const support = await getEmbeddedPostgresTestSupport();
});
it("retains both spoken sides once on the public call task and preserves quarantine", async () => {
const f = await inboundFixture(true), now = new Date().toISOString();
await f.tool("submit_request", {text: "Help draft an inquiry"});
f.transport.callReport.mockResolvedValue({complete: true, transcript: [
{id: "caller-turn", index: 0, speaker: "caller", text: "Help draft an inquiry", startedAt: now, endedAt: null, interrupted: false},
{id: "agent-turn", index: 1, speaker: "agent", text: "Here is your draft", startedAt: now, endedAt: null, interrupted: true},
@@ -2834,7 +2834,7 @@ export function createHeartbeatRunPreparation(db: Db) {
chatAssignedAgentId: chatEndpoints.assignedAgentId,
chatProvider: chatEndpoints.provider,
// Select only the public command, never the rest of setup state.
chatSlackCommand: sql<string | null>`case when ${chatEndpoints.status} in ('active', 'verifying') then ${chatEndpoints.setup}->>'command' end`,
chatSlackCommand: sql<string | null>`case when ${chatEndpoints.provider} = 'slack' and ${chatEndpoints.status} in ('active', 'verifying') then ${chatEndpoints.setup}->>'command' end`,
externalConversationState: externalConversationStateSql(),
conversationAgentId: issues.conversationAgentId,
conversationUserId: issues.conversationUserId,
@@ -2877,7 +2877,6 @@ export function createHeartbeatRunPreparation(db: Db) {
.leftJoin(chatEndpoints, and(
eq(chatEndpoints.companyId, chatConversations.companyId),
eq(chatEndpoints.id, chatConversations.endpointId),
eq(chatEndpoints.provider, "slack"),
))
.where(and(eq(issues.id, issueId), eq(issues.companyId, companyId)))
.then((rows) => rows[0] ?? null);
@@ -1,8 +1,8 @@
import { logger } from "../../middleware/logger.js";
import { createHash, createHmac, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
import { and, asc, desc, eq, inArray, lte, isNull, sql } from "drizzle-orm";
import { and, asc, desc, eq, gte, inArray, lte, isNull, sql } from "drizzle-orm";
import { z } from "zod";
import { chatEndpointResources, chatConversations, chatActions, chatEndpoints, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, chatVoiceSessions, issues, activityLog, type Db } from "@paperclipai/db";
import { chatEndpointResources, chatConversations, chatActions, chatEndpoints, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, chatVoiceSessions, activityLog, type Db } from "@paperclipai/db";
import { LOW_TRUST_REVIEW_PRESET, LOW_TRUST_REVIEW_PRESET_VERSION, LOW_TRUST_REVIEW_RAW_OUTPUT_DISPOSITION } from "@paperclipai/shared";
import { buildChatCommunicationGuidance } from "../chat-communication-guidance.js";
import { environmentService } from "../environments.js";
@@ -110,25 +110,20 @@ export function voiceInboundService(db: Db, options: {
if (!line || line.providerNumberId !== event.phone_number_id || line.phoneNumber !== event.dialed_number) throw forbidden("Incoming calls are not enabled for this number");
const capability = token(row, providerSessionId, context.generation, credentials.signingSecret);
const fingerprint = createHash("sha256").update(JSON.stringify(event)).digest("hex");
const [admission] = await db.insert(chatVoiceInboundCalls).values({companyId: row.companyId, endpointId: row.id, providerSessionId, state: line.guestIntake ? "guest_intake" : "awaiting_approval", approvalCode: String(randomInt(100000, 1000000)), generation: context.generation, credentialFingerprint: context.fingerprint, toolTokenHash: voiceTokenHash(capability), requestFingerprint: fingerprint, callerAuthority: line.guestIntake ? "guest_intake" : null, expiresAt: new Date(Date.now() + (line.guestIntake ? 600_000 : 120_000))}).onConflictDoNothing().returning();
const existing = admission ?? (await db.select().from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.companyId, row.companyId), eq(chatVoiceInboundCalls.endpointId, row.id), eq(chatVoiceInboundCalls.providerSessionId, providerSessionId))))[0];
const existing = await db.transaction(async tx => {
// Serialize admission per endpoint so concurrent rings cannot bypass quotas.
await tx.execute(sql`set local lock_timeout = '500ms'`);
await tx.execute(sql`set local statement_timeout = '2000ms'`);
await tx.select({id: chatEndpoints.id}).from(chatEndpoints).where(eq(chatEndpoints.id, row.id)).for("update");
const [prior] = await tx.select().from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.companyId, row.companyId), eq(chatVoiceInboundCalls.endpointId, row.id), eq(chatVoiceInboundCalls.providerSessionId, providerSessionId)));
if (prior) return prior;
const recent = await tx.select({state: chatVoiceInboundCalls.state, expiresAt: chatVoiceInboundCalls.expiresAt}).from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.companyId, row.companyId), eq(chatVoiceInboundCalls.endpointId, row.id), gte(chatVoiceInboundCalls.createdAt, new Date(Date.now() - 3_600_000)))).limit(60);
if (recent.length >= 60 || recent.filter(call => ["guest_intake", "awaiting_approval", "approving"].includes(call.state) && call.expiresAt.getTime() > Date.now()).length >= 10) throw conflict("This phone line has reached its incoming call limit. Try again later.");
const [admission] = await tx.insert(chatVoiceInboundCalls).values({companyId: row.companyId, endpointId: row.id, providerSessionId, state: line.guestIntake ? "guest_intake" : "awaiting_approval", approvalCode: String(randomInt(100000, 1000000)), generation: context.generation, credentialFingerprint: context.fingerprint, toolTokenHash: voiceTokenHash(capability), requestFingerprint: fingerprint, callerAuthority: line.guestIntake ? "guest_intake" : null, expiresAt: new Date(Date.now() + (line.guestIntake ? 600_000 : 120_000))}).onConflictDoNothing().returning();
return admission;
});
if (!existing || existing.requestFingerprint !== fingerprint || existing.toolTokenHash !== voiceTokenHash(capability) || !["awaiting_approval", "guest_intake"].includes(existing.state) || existing.expiresAt.getTime() <= Date.now()) throw forbidden("Incoming call is no longer pending");
if (existing.state === "guest_intake") {
await db.transaction(async tx => {
const current = await store.endpointContext(tx, row.companyId, row.id);
const [call] = await tx.select().from(chatVoiceInboundCalls).where(eq(chatVoiceInboundCalls.id, existing.id)).for("update");
const [enabledLine] = await tx.select().from(chatVoicePhoneLines).where(and(eq(chatVoicePhoneLines.endpointId, row.id), eq(chatVoicePhoneLines.companyId, row.companyId), eq(chatVoicePhoneLines.enabled, true), eq(chatVoicePhoneLines.guestIntake, true))).for("share");
if (!call || call.state !== "guest_intake" || !enabledLine || current.fingerprint !== call.credentialFingerprint || current.generation !== call.generation) throw forbidden("Incoming call configuration changed");
if (call.sessionId) return;
const taskId = randomUUID(), conversationId = randomUUID(), threadId = `speko:${conversationId}`;
const reviewPreset = {id: LOW_TRUST_REVIEW_PRESET, version: LOW_TRUST_REVIEW_PRESET_VERSION, rawOutputDisposition: LOW_TRUST_REVIEW_RAW_OUTPUT_DISPOSITION};
const task = await issueSvc.create(row.companyId, {id: taskId, title: "Incoming phone conversation", description: "Conversation with an unverified phone caller. The agent runs under a task-scoped low-trust policy. You are on a live phone call and must attempt to answer as quickly as possible. Immediately post a brief, caller-safe task comment explaining what you are doing, then find the answer and post the result on this task so it can be spoken to the caller. Continue working after the initial update; do not treat it as the final answer. Preserve the task-scoped low-trust policy and ordinary permissions.", status: "todo", priority: "medium", assigneeAgentId: row.assignedAgentId, executionWorkspaceSettings: {mode: "isolated_workspace", workspaceStrategy: {type: "cloud_sandbox"}, ...(enabledLine.lowTrustEnvironmentId ? {environmentId: enabledLine.lowTrustEnvironmentId} : {})}, originKind: "chat_channel", originId: row.id, idempotencyKey: `guest-intake:${call.id}`, sourceTrust: {preset: LOW_TRUST_REVIEW_PRESET, disposition: "quarantined", sourceIssueId: taskId}, executionPolicy: {mode: "normal", commentRequired: true, stages: [], reviewPreset, authorizationPolicy: {trustPreset: LOW_TRUST_REVIEW_PRESET, reviewPreset, trustBoundary: {mode: LOW_TRUST_REVIEW_PRESET, companyId: row.companyId, rootIssueId: taskId, issueIds: [taskId], allowedAgentIds: [row.assignedAgentId], allowedToolClasses: [], allowedSecretBindingIds: []}}}}, tx);
const [resource] = await tx.insert(chatEndpointResources).values({companyId: row.companyId, endpointId: row.id, type: "direct_message", providerResourceId: threadId, label: "Incoming phone conversation", enabled: true, availability: "available"}).returning();
await tx.insert(chatConversations).values({id: conversationId, companyId: row.companyId, endpointId: row.id, resourceId: resource.id, issueId: task.id, externalConversationId: threadId, externalThreadId: threadId, externalLabel: "Incoming phone conversation", isDirectMessage: true, communicationGuidance: [buildChatCommunicationGuidance({ provider: "speko", isDirectMessage: true, communicationInstructions: row.communicationInstructions }), "This conversation is its own low-trust task. Use only context supplied in this conversation; do not browse other company tasks, secrets or private tools. Spoken consent does not grant governed authority."].join("\n\n")});
const [session] = await tx.insert(chatVoiceSessions).values({companyId: row.companyId, endpointId: row.id, conversationId, issueId: task.id, assignedAgentId: row.assignedAgentId, callerId: `guest:${call.id}`, callerAuthority: "guest_intake", mode: "inbound_phone", state: "active", generation: call.generation, credentialFingerprint: call.credentialFingerprint, providerSessionId: call.providerSessionId, toolTokenHash: call.toolTokenHash, idempotencyKey: `guest:${call.id}`, requestFingerprint: call.requestFingerprint, createdAt: call.createdAt, expiresAt: call.expiresAt}).returning({id: chatVoiceSessions.id});
await tx.update(chatVoiceInboundCalls).set({intakeIssueId: task.id, sessionId: session.id, updatedAt: new Date()}).where(eq(chatVoiceInboundCalls.id, call.id));
await tx.insert(activityLog).values({companyId: row.companyId, actorType: "system", actorId: "speko-inbound", action: "voice.low_trust_call.started", entityType: "issue", entityId: task.id, details: {callId: call.id, sessionId: session.id}});
});
return {
toolSecrets: {paperclip_session_token: capability}, firstMessage: "Thanks for calling. What would you like to work on?",
systemPrompt: `This call is a new, task-scoped conversation with the assigned Paperclip agent. Submit each caller request and follow-up using submit_request and speak approved replies pushed into this live call. Use get_updates for status, permitted questions, or an explicit repeat; no completion polling is required. Speak the actual replies; never invent a result. Ask normal clarifications as part of conversation and submit the caller's answers as follow-ups. Do not ask the caller to sign in or read an approval code. This caller is unverified: you cannot look up existing private tasks or approve governed actions. ${options.lowTrustVoicePrompt}`,
@@ -183,32 +178,19 @@ export function voiceInboundService(db: Db, options: {
if (!line) throw forbidden("Guest intake is no longer enabled");
if (envelope.tool === "get_updates") return {authorization: "guest_intake", status: call.intakeIssueId ? "intake_received" : "ready_for_intake", updates: [], cursor: 0};
if (envelope.tool !== "submit_request") throw forbidden("Guest callers cannot answer private questions or approve actions");
const actionId = `speko_guest:${call.id}:${envelope.tool_call_id}`;
const fingerprint = createHash("sha256").update(JSON.stringify(envelope)).digest("hex");
const [receipt] = await tx.select().from(chatActions).where(and(eq(chatActions.companyId, row.companyId), eq(chatActions.endpointId, row.id), eq(chatActions.providerActionId, actionId)));
if (receipt) { if (receipt.payload.fingerprint !== fingerprint) throw conflict("Guest request identity was reused for different content"); return receipt.result; }
const receipts = await tx.select({id: chatActions.id}).from(chatActions).where(and(eq(chatActions.companyId, row.companyId), eq(chatActions.endpointId, row.id), eq(chatActions.kind, "speko_guest_intake"), sql`${chatActions.payload}->>'callId' = ${call.id}`));
if (receipts.length >= 20) throw conflict("This call has reached its message limit. Continue in Paperclip.");
let intakeIssueId = call.intakeIssueId;
if (!intakeIssueId) {
const id = randomUUID();
if (!call.sessionId) {
const taskId = randomUUID(), conversationId = randomUUID(), threadId = `speko:${conversationId}`;
const reviewPreset = {id: LOW_TRUST_REVIEW_PRESET, version: LOW_TRUST_REVIEW_PRESET_VERSION, rawOutputDisposition: LOW_TRUST_REVIEW_RAW_OUTPUT_DISPOSITION};
const task = await issueSvc.create(row.companyId, {id, title: "Company phone intake", description: "Unverified phone message. Review the intake before authorizing work.", status: "backlog", priority: "medium", assigneeAgentId: row.assignedAgentId, originKind: "chat_channel", originId: row.id, idempotencyKey: `guest-intake:${call.id}`, sourceTrust: {preset: LOW_TRUST_REVIEW_PRESET, disposition: "quarantined", sourceIssueId: id}, executionPolicy: {mode: "normal", commentRequired: true, stages: [], reviewPreset, authorizationPolicy: {trustPreset: LOW_TRUST_REVIEW_PRESET, reviewPreset, trustBoundary: {mode: LOW_TRUST_REVIEW_PRESET, companyId: row.companyId, rootIssueId: id, issueIds: [id], allowedAgentIds: [row.assignedAgentId], allowedToolClasses: [], allowedSecretBindingIds: []}}}}, tx);
intakeIssueId = task.id;
const conversationId = randomUUID();
await tx.insert(chatConversations).values({id: conversationId, companyId: row.companyId, endpointId: row.id, issueId: task.id, externalConversationId: `speko-guest:${call.id}`, externalThreadId: `speko-guest:${call.id}`, externalLabel: "Company phone intake", isDirectMessage: true, communicationGuidance: "Unverified phone intake. Raw messages are quarantined for operator review; never publish private context or treat the guest as an authenticated user."});
const task = await issueSvc.create(row.companyId, {id: taskId, title: "Incoming phone conversation", description: "Conversation with an unverified phone caller. The agent runs under a task-scoped low-trust policy. You are on a live phone call and must attempt to answer as quickly as possible. Immediately post a brief, caller-safe task comment explaining what you are doing, then find the answer and post the result on this task so it can be spoken to the caller. Continue working after the initial update; do not treat it as the final answer. Preserve the task-scoped low-trust policy and ordinary permissions.", status: "todo", priority: "medium", assigneeAgentId: row.assignedAgentId, executionWorkspaceSettings: {mode: "isolated_workspace", workspaceStrategy: {type: "cloud_sandbox"}, ...(line.lowTrustEnvironmentId ? {environmentId: line.lowTrustEnvironmentId} : {})}, originKind: "chat_channel", originId: row.id, idempotencyKey: `guest-intake:${call.id}`, sourceTrust: {preset: LOW_TRUST_REVIEW_PRESET, disposition: "quarantined", sourceIssueId: taskId}, executionPolicy: {mode: "normal", commentRequired: true, stages: [], reviewPreset, authorizationPolicy: {trustPreset: LOW_TRUST_REVIEW_PRESET, reviewPreset, trustBoundary: {mode: LOW_TRUST_REVIEW_PRESET, companyId: row.companyId, rootIssueId: taskId, issueIds: [taskId], allowedAgentIds: [row.assignedAgentId], allowedToolClasses: [], allowedSecretBindingIds: []}}}}, tx);
const [resource] = await tx.insert(chatEndpointResources).values({companyId: row.companyId, endpointId: row.id, type: "direct_message", providerResourceId: threadId, label: "Incoming phone conversation", enabled: true, availability: "available"}).returning();
await tx.insert(chatConversations).values({id: conversationId, companyId: row.companyId, endpointId: row.id, resourceId: resource.id, issueId: task.id, externalConversationId: threadId, externalThreadId: threadId, externalLabel: "Incoming phone conversation", isDirectMessage: true, communicationGuidance: [buildChatCommunicationGuidance({ provider: "speko", isDirectMessage: true, communicationInstructions: row.communicationInstructions }), "This conversation is its own low-trust task. Use only context supplied in this conversation; do not browse other company tasks, secrets or private tools. Spoken consent does not grant governed authority."].join("\n\n")});
const [session] = await tx.insert(chatVoiceSessions).values({companyId: row.companyId, endpointId: row.id, conversationId, issueId: task.id, assignedAgentId: row.assignedAgentId, callerId: `guest:${call.id}`, callerAuthority: "guest_intake", mode: "inbound_phone", state: "active", generation: call.generation, credentialFingerprint: call.credentialFingerprint, providerSessionId: call.providerSessionId, toolTokenHash: call.toolTokenHash, idempotencyKey: `guest:${call.id}`, requestFingerprint: call.requestFingerprint, createdAt: call.createdAt, expiresAt: call.expiresAt}).returning({id: chatVoiceSessions.id});
await tx.update(chatVoiceInboundCalls).set({intakeIssueId, sessionId: session.id, updatedAt: new Date()}).where(eq(chatVoiceInboundCalls.id, call.id));
await tx.update(chatVoiceInboundCalls).set({intakeIssueId: task.id, sessionId: session.id, updatedAt: new Date()}).where(eq(chatVoiceInboundCalls.id, call.id));
await tx.insert(activityLog).values({companyId: row.companyId, actorType: "system", actorId: "speko-inbound", action: "voice.low_trust_call.started", entityType: "issue", entityId: task.id, details: {callId: call.id, sessionId: session.id}});
}
const [task] = await tx.select().from(issues).where(and(eq(issues.companyId, row.companyId), eq(issues.id, intakeIssueId))).for("update");
if (!task || task.originKind !== "chat_channel" || task.originId !== row.id || task.sourceTrust?.disposition !== "quarantined" || task.assigneeAgentId !== row.assignedAgentId || ["done", "cancelled"].includes(task.status)) throw forbidden("This guest intake is no longer available");
await issueSvc.addComment(task.id, envelope.args.text, {}, {authorType: "system", sourceTrust: {preset: LOW_TRUST_REVIEW_PRESET, disposition: "quarantined", sourceIssueId: task.id}}, tx);
const result = {authorization: "guest_intake", status: "accepted", intakeStatus: "awaiting_operator_review"};
await tx.insert(chatActions).values({companyId: row.companyId, endpointId: row.id, kind: "speko_guest_intake", providerActionId: actionId, status: "completed", payload: {fingerprint, callId: call.id}, result});
await tx.insert(activityLog).values({companyId: row.companyId, actorType: "system", actorId: "speko-guest-intake", action: "voice.guest.message_received", entityType: "issue", entityId: task.id, details: {callId: call.id}});
// Intake is live and durable, but never impersonates a board user or wakes
// the full-privilege agent. An operator authorizes execution from the task.
return result;
const [bound] = await tx.select({sessionId: chatVoiceInboundCalls.sessionId}).from(chatVoiceInboundCalls).where(eq(chatVoiceInboundCalls.id, call.id));
if (!bound?.sessionId) throw conflict("Incoming request could not be bound to its task");
return {sessionId: bound.sessionId};
}
// No instructions, question answers, tasks or comments are accepted here.
return {authorization: call.state, status: "unavailable", updates: [], cursor: 0, requestAccepted: false};
@@ -266,6 +248,7 @@ export function voiceInboundService(db: Db, options: {
catch (error) { if (error instanceof Error && "status" in error && [403, 404].includes(Number(error.status))) return false; throw error; }
}
async function reconcile(limit: number) {
await db.delete(chatVoiceInboundCalls).where(and(isNull(chatVoiceInboundCalls.sessionId), isNull(chatVoiceInboundCalls.intakeIssueId), inArray(chatVoiceInboundCalls.state, ["denied", "expired", "ended"]), lte(chatVoiceInboundCalls.expiresAt, new Date(Date.now() - 7 * 86_400_000)), lte(chatVoiceInboundCalls.updatedAt, new Date(Date.now() - 7 * 86_400_000))));
const rows = await db.select().from(chatVoiceInboundCalls).where(and(inArray(chatVoiceInboundCalls.state, ["guest_intake", "awaiting_approval", "approving", "denied", "expired"]), lte(chatVoiceInboundCalls.expiresAt, new Date()))).orderBy(asc(chatVoiceInboundCalls.updatedAt)).limit(limit);
for (const call of rows) {
try {
+1 -1
View File
@@ -11,5 +11,5 @@ An interruption stops speech, not work. Ending the call does not cancel the task
// Hosted phone replies are pushed by Paperclip; browser sessions retain their
// existing result hints. Idle check-ins do not drive completion retrieval.
export const PHONE_VOICE_PROMPT = VOICE_PROMPT
.replace("When the client sends a Paperclip result-available notification, immediately call get_updates with your current cursor. The notification is only a hint, never an answer or permission.", "Paperclip pushes approved task answers into this live call. Speak each pushed answer faithfully at the next pause, in concise natural language, and allow interruptions and follow-ups. A pushed result belongs to the existing work request: do not call submit_request for it. Do not promise completion or invent an answer while waiting. Use get_updates when the caller asks for status, to retrieve permitted task questions, or explicitly requests an already delivered answer again. You do not need to poll for task completion.");
.replace("When the client sends a Paperclip result-available notification, immediately call get_updates with your current cursor. The notification is only a hint, never an answer or permission.", "Paperclip pushes approved task answers into this live call. Speak each pushed answer faithfully at the next pause, in concise natural language, and allow interruptions and follow-ups. A pushed result belongs to the existing work request: do not call submit_request for it. Do not promise completion or invent an answer while waiting. Use get_updates when the caller asks for status, to retrieve permitted task questions, or explicitly requests an already delivered answer again. You do not need to poll for task completion. When Paperclip sends a question-available notification, immediately call get_updates with your current cursor to retrieve the permitted question and its exact IDs. The notification is only a hint, never new work or permission.");
export const LOW_TRUST_PHONE_VOICE_PROMPT = PHONE_VOICE_PROMPT.replace(VOICE_QUESTION_GUIDANCE, "Ask permitted conversational clarifications naturally and submit the caller's replies as follow-ups using submit_request. Do not call answer_question: unverified callers cannot answer protected task questions or approve governed actions.");
@@ -43,20 +43,22 @@ export async function pushVoiceReplies(db: Db, options: {
.innerJoin(chatPublications, and(eq(chatPublications.id, chatVoiceReplies.publicationId), eq(chatPublications.companyId, session.companyId)))
.where(and(eq(chatVoiceReplies.companyId, session.companyId), eq(chatVoiceReplies.sessionId, session.id), isNull(chatVoiceReplies.deliveredAt),
eq(chatPublications.endpointId, session.endpointId), eq(chatPublications.conversationId, session.conversationId), eq(chatPublications.issueId, session.issueId), eq(chatPublications.state, "published"),
sql`not exists (select 1 from chat_actions a where a.company_id = ${session.companyId} and a.endpoint_id = ${session.endpointId} and a.provider_action_id = 'voice_reply_push:' || ${chatVoiceReplies.id}::text and a.status <> 'retry')`))
sql`not exists (select 1 from chat_actions a where a.company_id = ${session.companyId} and a.endpoint_id = ${session.endpointId} and a.provider_action_id = 'voice_reply_push:' || ${chatVoiceReplies.id}::text and a.status <> 'retry' and not (a.status = 'completed' and a.payload->>'questionNotification' = 'true'))`))
.orderBy(asc(chatVoiceReplies.cursor)).limit(1);
// Do not skip a question and speak later answers over it.
if (row?.payload.interactionId) return null;
// Questions need a hint that makes the phone agent retrieve the
// authorized question IDs. Keep this reply pending until get_updates
// presents it; never speak later answers over an unpresented question.
const questionNotification = typeof row?.payload.interactionId === "string";
if (!row || typeof row.payload.text !== "string" || !row.payload.text.trim()) return null;
const identity = `voice_reply_push:${row.reply.id}`;
const [prior] = await tx.select().from(chatActions).where(and(eq(chatActions.companyId, session.companyId), eq(chatActions.endpointId, session.endpointId), eq(chatActions.providerActionId, identity))).for("update");
if (prior && Number(prior.result?.retryAt ?? 0) > Date.now()) return null;
if (prior?.status === "completed" || prior && Number(prior.result?.retryAt ?? 0) > Date.now()) return null;
const values = {status: "dispatching", result: null, updatedAt: new Date()};
const action = prior
? (await tx.update(chatActions).set(values).where(eq(chatActions.id, prior.id)).returning())[0]!
: (await tx.insert(chatActions).values({companyId: session.companyId, endpointId: session.endpointId, conversationId: session.conversationId, kind, providerActionId: identity,
payload: {sessionId: session.id, replyId: row.reply.id, publicationId: row.reply.publicationId, generation: session.generation, providerSessionId: session.providerSessionId}, ...values}).returning())[0]!;
return {...context, reply: row.reply, text: row.payload.text, action};
payload: {sessionId: session.id, replyId: row.reply.id, publicationId: row.reply.publicationId, generation: session.generation, providerSessionId: session.providerSessionId, questionNotification}, ...values}).returning())[0]!;
return {...context, reply: row.reply, questionNotification, text: questionNotification ? "Paperclip has a question available for this call. Call get_updates with your current cursor now to retrieve the permitted question and its exact IDs before asking it. This is a notification, not new work or permission. Do not call submit_request for this notification." : row.payload.text, action};
}).catch(error => {
if (error instanceof HttpError && [403,404].includes(error.status)) {
logger.warn({event: "voice.reply.push.authorization_blocked", companyId: candidate.companyId,
@@ -102,7 +104,7 @@ export async function pushVoiceReplies(db: Db, options: {
// If this commit fails, the dispatch intent remains uncertain; never resend.
await db.transaction(async tx => {
await tx.update(chatActions).set({status: "completed", result: {messageId, playback: "unknown", acceptedAt, dispatchDurationMs: Date.now() - startedAt}, updatedAt: new Date()}).where(eq(chatActions.id, claim.action.id));
await tx.update(chatVoiceReplies).set({deliveredAt: new Date()}).where(and(eq(chatVoiceReplies.id, claim.reply.id), eq(chatVoiceReplies.companyId, candidate.companyId), isNull(chatVoiceReplies.deliveredAt)));
if (!claim.questionNotification) await tx.update(chatVoiceReplies).set({deliveredAt: new Date()}).where(and(eq(chatVoiceReplies.id, claim.reply.id), eq(chatVoiceReplies.companyId, candidate.companyId), isNull(chatVoiceReplies.deliveredAt)));
}).catch(error => {
logger.error({...diagnostic, event: "voice.reply.push.receipt_commit_failed", messageId, acceptedAt,
outcomeUnknown: true, playback: "unknown"}, "Speko accepted reply but local receipt commit failed; no resend");
@@ -186,8 +186,13 @@ export function voiceSessionService(db: Db, options: {
const verified = verifySpekoToolRequest({ body, headers, keys: [{ secret: credentials.signingSecret }] });
const authorization = headers.authorization;
if (typeof authorization !== "string" || !/^Bearer [A-Za-z0-9_-]{43}$/.test(authorization)) throw forbidden("Missing voice session credential");
const session = await db.select({ id: chatVoiceSessions.id, authority: chatVoiceSessions.callerAuthority, mode: chatVoiceSessions.mode }).from(chatVoiceSessions).where(and(eq(chatVoiceSessions.companyId, endpoint.companyId), eq(chatVoiceSessions.endpointId, endpoint.id), eq(chatVoiceSessions.providerSessionId, verified.envelope.session_id))).then((rows) => rows[0]);
if (!session) return inbound.pendingTool(endpoint, verified.envelope, authorization.slice(7));
let session = await db.select({ id: chatVoiceSessions.id, authority: chatVoiceSessions.callerAuthority, mode: chatVoiceSessions.mode }).from(chatVoiceSessions).where(and(eq(chatVoiceSessions.companyId, endpoint.companyId), eq(chatVoiceSessions.endpointId, endpoint.id), eq(chatVoiceSessions.providerSessionId, verified.envelope.session_id))).then((rows) => rows[0]);
if (!session) {
const pending = await inbound.pendingTool(endpoint, verified.envelope, authorization.slice(7));
if (!("sessionId" in pending) || typeof pending.sessionId !== "string") return pending;
session = await db.select({id: chatVoiceSessions.id, authority: chatVoiceSessions.callerAuthority, mode: chatVoiceSessions.mode}).from(chatVoiceSessions).where(and(eq(chatVoiceSessions.id, pending.sessionId), eq(chatVoiceSessions.companyId, endpoint.companyId), eq(chatVoiceSessions.endpointId, endpoint.id))).then(rows => rows[0]);
if (!session) throw conflict("Incoming request could not be bound to its task");
}
const result = await store.runTool({ ...verified, companyId: endpoint.companyId, endpointId: endpoint.id, sessionId: session.id, token: authorization.slice(7), accept: store.stageDelivery });
// Do not await execution within Speko's four-second webhook budget. The
// shared delivery service deduplicates retries; its sweep repairs crashes.
@@ -317,6 +317,10 @@ export function voiceSessionStore(db: Db, options: { allowLocalBoard: boolean; n
if (replay) throw conflict("Voice webhook id was already used for a different tool call");
let deliveryId: string | null = null, response: Record<string, unknown>;
if (input.envelope.tool === "submit_request") {
if (session.callerAuthority === "guest_intake") {
const requests = await tx.select({id: chatVoiceToolCalls.id}).from(chatVoiceToolCalls).where(and(eq(chatVoiceToolCalls.sessionId, session.id), eq(chatVoiceToolCalls.tool, "submit_request"))).limit(20);
if (requests.length >= 20) throw conflict("This call has reached its message limit. Continue in Paperclip.");
}
deliveryId = await input.accept(tx, context, input.envelope.args.text, input.envelope.tool_call_id);
const delivery = await tx.select({ id: chatDeliveries.id }).from(chatDeliveries).where(and(eq(chatDeliveries.id, deliveryId), eq(chatDeliveries.companyId, session.companyId), eq(chatDeliveries.endpointId, session.endpointId))).then((rows) => rows[0]);
if (!delivery) throw conflict("Voice request was not durably accepted");
+10
View File
@@ -14,6 +14,16 @@ function fixture() {
return { rows, storage, client, journal };
}
describe("voice reload recovery", () => {
it.each([400, 401, 403, 404, 422])("allows a new endpoint after definitive admission rejection %s", async (status) => {
const f = fixture();
f.client.start.mockRejectedValueOnce(new ApiError("Rejected", status, {error: "Rejected"}));
const attempt = createVoiceCallAttempt("company", f.client, f.journal);
await expect(attempt.start({endpointId: "stale"})).rejects.toBeInstanceOf(ApiError);
expect(f.journal.read()).toBeUndefined();
await attempt.start({endpointId: "valid", issueId: "new-task"});
expect(f.client.start.mock.calls[1]?.[1]).toMatchObject({endpointId: "valid", issueId: "new-task"});
expect(f.client.start.mock.calls[1]?.[1].idempotencyKey).not.toBe(f.client.start.mock.calls[0]?.[1].idempotencyKey);
});
it("retains exact cleanup identity and a safe credit reason after a rejected creation", async () => {
const f=fixture();f.client.start.mockRejectedValue(new ApiError("private provider detail",409,{details:{code:"voice_credits_required",sessionId:"failed-call"}}));
const attempt=createVoiceCallAttempt("company",f.client,f.journal);
+5
View File
@@ -54,6 +54,11 @@ export function createVoiceCallAttempt(companyId: string, client: typeof voiceSe
try { journal?.write(attempt); } catch { /* Exact identity still reaches cleanup. */ }
throw new VoiceSessionStartError(attempt.sessionId, body.details.code === "voice_credits_required" ? "credits_required" : undefined);
}
if (error instanceof ApiError && [400, 401, 403, 404, 422].includes(error.status)) {
// These responses reject admission before creating a provider call.
// Network errors and ambiguous provider outcomes keep their identity.
journal?.clear(); attempt = undefined; recovering = false;
}
throw error;
}
attempt.sessionId = result.session.id;