From c49e80da6c23f678ae743162eda4f90bde82116a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 27 Nov 2026 14:47:15 +0000 Subject: [PATCH] fix(voice): exclude voice transport from tool health sweep and clarify Speko callback opt-in (#23116) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Speko voice connections create a channel-scoped tool connection with `transport: "voice"` so the assigned agent can call the responsible person through `call_my_phone`. > - The background tool-connection health sweep excluded `chat_sdk` and `runtime_auth` transports, but omitted `voice`. > - Every 15 minutes, the sweep called `checkConnectionHealth` on active Speko connections, hit `unsupportedToolConnectionTransport()`, and overwrote their health state to `error`. > - In addition, when `call_my_phone` was not present in an agent's tools for a task, the Speko skill did not explain how to help the user check Call my phone opt-in, tool access, or task eligibility. > - This pull request replaces the duplicated negative transport filters with a single positive `HEALTH_SWEEP_TRANSPORTS` allowlist, repairs already-corrupted active Speko voice connections in bounded atomic batches (while preserving real errors), handles `transport: "voice"` safely in manual `checkConnectionHealth`, and updates the Speko skill guidance. > - The benefit is that active Speko voice connections self-heal and stay healthy instead of degrading into false errors every 15 minutes, and agents give accurate troubleshooting guidance when `call_my_phone` is absent. ## Linked Issues or Issue Description Refs #23052 **Describe the bug** Active Speko voice connections (`transport: "voice"`) are picked up by the scheduled tool-connection health sweep after 15 minutes and marked `healthStatus: "error"` with `"This connection has no supported tool integration. Add a supported account or MCP connection from Connectors."`. **Steps to reproduce** 1. Connect and activate a Speko voice endpoint. 2. Wait 15 minutes for the scheduled tool-connection health sweep (or call `sweepConnectionHealth({ staleAfterMs: 0 })` / `scheduledHealth.load(companyId)`). 3. Inspect the Speko `tool_connections` row. **Expected behavior** Voice channel connections (`transport: "voice"`) are excluded from the generic tool-connection health sweep via a shared positive transport allowlist, previously corrupted active Speko voice rows self-heal without clearing real errors, and manual health checks do not overwrite them to `error`. ## What Changed - Export `UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE` from `server/src/services/tool-access/catalog/failures.ts`. - Export `HEALTH_SWEEP_TRANSPORTS`, `healthSweepConnectionWhere()`, and `repairUnsupportedVoiceConnectionHealth()` in `server/src/services/tool-access/catalog/health.ts`; use the shared allowlist in both `sweepConnectionHealth` and `connectionHealthSchedule.load`. - Repair active Speko voice connections previously marked with `UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE` (only when the paired active Speko endpoint has `last_error IS NULL`), registering health/chat notifications before the batch update, running once per `connectionHealthSchedule` instance, and handling `transport: "voice"` safely in `checkConnectionHealth`. - Update `server/src/services/voice/speko-skill.ts` so agents check task eligibility, tool access, and the `Call my phone` (`Allow this agent to call me about my tasks`) setting when `call_my_phone` is absent. - Add red-green regression tests in `server/src/__tests__/tool-access-service.test.ts` (including `scheduledHealth.load`, `sweepConnectionHealth`, `checkHealth`, multi-batch repair, and real-error preservation) and `server/src/__tests__/voice-session-store.integration.test.ts`. ## Verification - `pnpm --filter @paperclipai/server exec vitest run -t "sweeps enabled active connection health|repairs active Speko voice connections|delivers Speko guidance to existing agents" src/__tests__/tool-access-service.test.ts src/__tests__/voice-session-store.integration.test.ts` (3 passed) - `pnpm --filter @paperclipai/server typecheck` (passed, 0 errors across `below`, `cycle`, `above`, `tests`, `test-tree-0`, `test-tree-1`, `test-tree-2`) ## Risks - Low risk: excludes non-tool transports from the generic MCP/REST health sweep via an explicit allowlist of the four supported transports (`mcp_remote`, `rest_api`, `local_stdio`, `plugin`), repairs only rows matching the exact unsupported-transport error message on active Speko endpoints with `last_error IS NULL`, and refines one sentence of Speko skill text. No schema migrations or breaking API changes. ## Model Used - Google Gemini (Antigravity agentic coding assistant with extended reasoning, tool use, and local command 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 --- .../src/__tests__/tool-access-service.test.ts | 253 +++++++++++++++++- .../voice-session-store.integration.test.ts | 3 + .../services/tool-access/catalog/failures.ts | 5 +- .../tool-access/catalog/health-schedule.ts | 14 +- .../services/tool-access/catalog/health.ts | 130 ++++++++- server/src/services/voice/speko-skill.ts | 7 +- 6 files changed, 394 insertions(+), 18 deletions(-) diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index f690121937f..ddefd6a9cfd 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -1,4 +1,6 @@ import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; +import { UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE } from "../services/tool-access/catalog/failures.js"; +import { repairUnsupportedVoiceConnectionHealth } from "../services/tool-access/catalog/health.js"; const googleSignIn = vi.hoisted(() => ({ cloudHosted: true })); vi.mock("../services/google-sign-in-availability.js", () => ({ paperclipGoogleSignInAvailable: () => googleSignIn.cloudHosted })); import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; @@ -24,6 +26,7 @@ import { activityLog, agents, authUsers, + chatEndpoints, companies, companyMemberships, companySecretBindings, @@ -20962,6 +20965,40 @@ describeEmbeddedPostgres("tool access service", () => { lastHealthAt: new Date(0), }) .returning(); + const [voiceApplication] = await db + .insert(toolApplications) + .values({ + companyId: company.id, + applicationKey: `chat:speko:${randomUUID()}`, + name: "Speko voice", + type: "chat", + status: "active", + metadata: { sourceTemplateKey: "speko", purpose: "channel" }, + }) + .returning(); + const [voiceConnection] = await db + .insert(toolConnections) + .values({ + companyId: company.id, + applicationId: voiceApplication!.id, + name: "Speko agent", + uid: `chat-speko-${randomUUID()}`, + connectionKind: "managed", + connectionPurpose: "channel", + ownership: "customer", + transport: "voice", + authKind: "api_key", + credentialPolicy: "shared", + status: "active", + enabled: true, + config: { provider: "speko" }, + transportConfig: {}, + healthStatus: "healthy", + healthMessage: "Connected; conversation test optional", + healthCheckedAt: new Date(0), + lastHealthAt: new Date(0), + }) + .returning(); const [pluginApplication] = await db.insert(toolApplications).values({ companyId: company.id, applicationKey: `paperclip_plugin:fixture-${randomUUID()}`, @@ -20992,7 +21029,10 @@ describeEmbeddedPostgres("tool access service", () => { status: "active", })); - const sweep = await service.sweepConnectionHealth({ staleAfterMs: 0, limit: 1 }); + const scheduledDeadlines = await service.scheduledHealth.load(company.id); + expect(scheduledDeadlines.map((deadline) => deadline.id)).toEqual([connection.id]); + + const sweep = await service.sweepConnectionHealth({ staleAfterMs: 0, limit: 5 }); const [updatedConnection] = await db .select() .from(toolConnections) @@ -21001,6 +21041,10 @@ describeEmbeddedPostgres("tool access service", () => { .select() .from(toolConnections) .where(eq(toolConnections.id, chatConnection!.id)); + const [untouchedVoiceConnection] = await db + .select() + .from(toolConnections) + .where(eq(toolConnections.id, voiceConnection!.id)); const [untouchedPlugin] = await db.select().from(toolConnections) .where(eq(toolConnections.id, pluginConnection!.id)); @@ -21024,6 +21068,213 @@ describeEmbeddedPostgres("tool access service", () => { healthCheckedAt: new Date(0), lastHealthAt: new Date(0), }); + expect(untouchedVoiceConnection).toMatchObject({ + healthStatus: "healthy", + healthMessage: "Connected; conversation test optional", + lastError: null, + healthCheckedAt: new Date(0), + lastHealthAt: new Date(0), + }); + }); + + it("repairs active Speko voice connections falsely marked unsupported by the old health sweep without clearing real errors", async () => { + const company = await createCompany(db); + const service = createTestToolAccessService(db); + const [agent] = await db.insert(agents).values({ + companyId: company.id, + name: "Speko Voice Agent", + role: "general", + adapterType: "claude_local", + adapterConfig: {}, + runtimeConfig: {}, + }).returning(); + const [voiceApplication] = await db.insert(toolApplications).values({ + companyId: company.id, + applicationKey: `chat:speko:${randomUUID()}`, + name: "Speko voice", + type: "chat", + status: "active", + metadata: { sourceTemplateKey: "speko", purpose: "channel" }, + }).returning(); + const [corruptedVoice] = await db.insert(toolConnections).values({ + companyId: company.id, + applicationId: voiceApplication!.id, + name: "Speko corrupted by old sweep", + uid: `chat-speko-${randomUUID()}`, + connectionKind: "managed", + connectionPurpose: "channel", + ownership: "customer", + transport: "voice", + authKind: "api_key", + credentialPolicy: "shared", + status: "active", + enabled: true, + config: { provider: "speko" }, + transportConfig: {}, + healthStatus: "error", + healthMessage: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + lastError: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + healthCheckedAt: new Date(0), + lastHealthAt: new Date(0), + }).returning(); + await db.insert(chatEndpoints).values({ + companyId: company.id, + connectionId: corruptedVoice!.id, + provider: "speko", + publicId: `speko-${randomUUID()}`, + status: "active", + assignedAgentId: agent!.id, + healthMessage: "Connected; conversation test optional", + }); + const [realErrorVoice] = await db.insert(toolConnections).values({ + companyId: company.id, + applicationId: voiceApplication!.id, + name: "Speko real error", + uid: `chat-speko-${randomUUID()}`, + connectionKind: "managed", + connectionPurpose: "channel", + ownership: "customer", + transport: "voice", + authKind: "api_key", + credentialPolicy: "shared", + status: "active", + enabled: true, + config: { provider: "speko" }, + transportConfig: {}, + healthStatus: "error", + healthMessage: "Speko API key rejected", + lastError: "Speko API key rejected", + healthCheckedAt: new Date(0), + lastHealthAt: new Date(0), + }).returning(); + await db.insert(chatEndpoints).values({ + companyId: company.id, + connectionId: realErrorVoice!.id, + provider: "speko", + publicId: `speko-${randomUUID()}`, + status: "active", + assignedAgentId: agent!.id, + healthMessage: "Speko API key rejected", + lastError: "Speko API key rejected", + }); + const [endpointErrorVoice] = await db.insert(toolConnections).values({ + companyId: company.id, + applicationId: voiceApplication!.id, + name: "Speko endpoint error", + uid: `chat-speko-${randomUUID()}`, + connectionKind: "managed", + connectionPurpose: "channel", + ownership: "customer", + transport: "voice", + authKind: "api_key", + credentialPolicy: "shared", + status: "active", + enabled: true, + config: { provider: "speko" }, + transportConfig: {}, + healthStatus: "error", + healthMessage: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + lastError: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + healthCheckedAt: new Date(0), + lastHealthAt: new Date(0), + }).returning(); + await db.insert(chatEndpoints).values({ + companyId: company.id, + connectionId: endpointErrorVoice!.id, + provider: "speko", + publicId: `speko-${randomUUID()}`, + status: "active", + assignedAgentId: agent!.id, + healthMessage: "Speko webhook failed", + lastError: "Speko webhook failed", + }); + + // Scheduled load repairs only the false unsupported-transport error and returns no voice deadlines. + expect(await service.scheduledHealth.load(company.id)).toEqual([]); + const [repaired] = await db.select().from(toolConnections).where(eq(toolConnections.id, corruptedVoice!.id)); + expect(repaired).toMatchObject({ + healthStatus: "healthy", + healthMessage: "Connected; conversation test optional", + lastError: null, + }); + const [preservedRealError] = await db.select().from(toolConnections).where(eq(toolConnections.id, realErrorVoice!.id)); + expect(preservedRealError).toMatchObject({ + healthStatus: "error", + healthMessage: "Speko API key rejected", + lastError: "Speko API key rejected", + }); + const [preservedEndpointError] = await db.select().from(toolConnections).where(eq(toolConnections.id, endpointErrorVoice!.id)); + expect(preservedEndpointError).toMatchObject({ + healthStatus: "error", + healthMessage: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + }); + + // sweepConnectionHealth also repairs corrupted active Speko voice connections without probing them. + await db.update(toolConnections).set({ + healthStatus: "error", + healthMessage: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + lastError: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + }).where(eq(toolConnections.id, corruptedVoice!.id)); + expect(await service.sweepConnectionHealth({ staleAfterMs: 0, limit: 5 })).toMatchObject({ checked: 0, healthy: 0, failed: 0 }); + const [repairedBySweep] = await db.select().from(toolConnections).where(eq(toolConnections.id, corruptedVoice!.id)); + expect(repairedBySweep).toMatchObject({ + healthStatus: "healthy", + healthMessage: "Connected; conversation test optional", + lastError: null, + }); + + // Manual health check on a voice connection also self-heals instead of throwing 422. + await db.update(toolConnections).set({ + healthStatus: "error", + healthMessage: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + lastError: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + }).where(eq(toolConnections.id, corruptedVoice!.id)); + const manual = await service.checkHealth(corruptedVoice!.id); + expect(manual.connection).toMatchObject({ + healthStatus: "healthy", + healthMessage: "Connected; conversation test optional", + lastError: null, + }); + + // Multi-batch repair drains beyond a single batch size. + const [secondCorruptedVoice] = await db.insert(toolConnections).values({ + companyId: company.id, + applicationId: voiceApplication!.id, + name: "Speko second corrupted", + uid: `chat-speko-${randomUUID()}`, + connectionKind: "managed", + connectionPurpose: "channel", + ownership: "customer", + transport: "voice", + authKind: "api_key", + credentialPolicy: "shared", + status: "active", + enabled: true, + config: { provider: "speko" }, + transportConfig: {}, + healthStatus: "error", + healthMessage: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + lastError: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + healthCheckedAt: new Date(0), + lastHealthAt: new Date(0), + }).returning(); + await db.insert(chatEndpoints).values({ + companyId: company.id, + connectionId: secondCorruptedVoice!.id, + provider: "speko", + publicId: `speko-${randomUUID()}`, + status: "active", + assignedAgentId: agent!.id, + healthMessage: "Connected", + }); + await db.update(toolConnections).set({ + healthStatus: "error", + healthMessage: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + lastError: UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, + }).where(eq(toolConnections.id, corruptedVoice!.id)); + expect(await repairUnsupportedVoiceConnectionHealth(db, { companyId: company.id, batchSize: 1 })).toBe(2); + const [repairedSecond] = await db.select().from(toolConnections).where(eq(toolConnections.id, secondCorruptedVoice!.id)); + expect(repairedSecond).toMatchObject({ healthStatus: "healthy", healthMessage: "Connected", lastError: null }); }); it("enriches listConnections with lastUsedAt from the most recent tool-call event", async () => { diff --git a/server/src/__tests__/voice-session-store.integration.test.ts b/server/src/__tests__/voice-session-store.integration.test.ts index 48f2cc4f093..2f75d13e446 100644 --- a/server/src/__tests__/voice-session-store.integration.test.ts +++ b/server/src/__tests__/voice-session-store.integration.test.ts @@ -2210,6 +2210,9 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu expect(markdown).toContain("one focused clarification"); expect(markdown).toContain("durable Paperclip continuation"); expect(markdown).toContain("never blindly redial"); + expect(markdown).toContain("Call my phone"); + expect(markdown).toContain("Allow this agent to call me about my tasks"); + expect(markdown).toContain("tool access"); expect(markdown).not.toContain("+12015551234"); for (const adapter of ["paperclip_runner", "claude_local", "codex_local"]) { expect((await prepareConnectorSkillDelivery({ ...config, engine: "cli" }, adapter)).config.paperclipRuntimeSkills).toEqual([skill]); diff --git a/server/src/services/tool-access/catalog/failures.ts b/server/src/services/tool-access/catalog/failures.ts index 0bf296a46cf..6c1831ac33c 100644 --- a/server/src/services/tool-access/catalog/failures.ts +++ b/server/src/services/tool-access/catalog/failures.ts @@ -51,9 +51,12 @@ function isAwsConfigurationFailureCode(code: string): boolean { return code.startsWith("aws_") && code !== "aws_unavailable"; } +export const UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE = + "This connection has no supported tool integration. Add a supported account or MCP connection from Connectors."; + export function unsupportedToolConnectionTransport() { return unprocessable( - "This connection has no supported tool integration. Add a supported account or MCP connection from Connectors.", + UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, { code: "tool_connection_transport_unsupported" }, ); } diff --git a/server/src/services/tool-access/catalog/health-schedule.ts b/server/src/services/tool-access/catalog/health-schedule.ts index 130e0d0ee53..3080b45bc61 100644 --- a/server/src/services/tool-access/catalog/health-schedule.ts +++ b/server/src/services/tool-access/catalog/health-schedule.ts @@ -1,16 +1,22 @@ import { logger } from "../../../middleware/logger.js"; -import { and, asc, eq, gt, ne, sql } from "drizzle-orm"; +import { and, asc, eq, gt, sql } from "drizzle-orm"; import { toolApplications, toolConnections, type Db } from "@paperclipai/db"; import { isConnectorFeatureEnabled } from "@paperclipai/shared"; import { instanceSettingsService } from "../../instance-settings.js"; import { connectionSetupApp } from "../connections/setup-policy.js"; -import type { ConnectionHealth } from "./health.js"; +import { healthSweepConnectionWhere, repairUnsupportedVoiceConnectionHealth, type ConnectionHealth } from "./health.js"; export type ConnectionHealthDeadline = { id: string; companyId: string; applicationId: string; dueAt: number }; const HEALTH_FRESHNESS_MS = 15 * 60_000; export function connectionHealthSchedule(db: Db, checkHealth: ConnectionHealth["checkConnectionHealth"]) { + let voiceHealthRepaired = false; async function load(companyId?: string, connectionId?: string, applicationId?: string, signal?: AbortSignal): Promise { + if (!voiceHealthRepaired && connectionId === undefined && applicationId === undefined) { + signal?.throwIfAborted(); + await repairUnsupportedVoiceConnectionHealth(db, { companyId, signal }); + voiceHealthRepaired = true; + } const deadlines: ConnectionHealthDeadline[] = []; let cursor: string | undefined; while (true) { @@ -26,9 +32,7 @@ export function connectionHealthSchedule(db: Db, checkHealth: ConnectionHealth[" eq(toolApplications.id, toolConnections.applicationId), eq(toolApplications.companyId, toolConnections.companyId), )).where(and( - eq(toolConnections.enabled, true), eq(toolConnections.status, "active"), - ne(toolConnections.transport, "chat_sdk"), ne(toolConnections.transport, "runtime_auth"), - ne(toolApplications.type, "paperclip_plugin"), + healthSweepConnectionWhere(), companyId === undefined ? undefined : eq(toolConnections.companyId, companyId), connectionId === undefined ? undefined : eq(toolConnections.id, connectionId), applicationId === undefined ? undefined : eq(toolConnections.applicationId, applicationId), diff --git a/server/src/services/tool-access/catalog/health.ts b/server/src/services/tool-access/catalog/health.ts index 16551c87b82..4b2da79090c 100644 --- a/server/src/services/tool-access/catalog/health.ts +++ b/server/src/services/tool-access/catalog/health.ts @@ -1,7 +1,7 @@ import { notifyChatConnectionObservation } from "../../chat-channels/configuration-work-notifications.js"; import { assertPluginConnectionWorker, PLUGIN_CONNECTOR_UNAVAILABLE_CODE } from "../../plugin-connector-runtime.js"; import { findPluginWorkerUnavailableError } from "../../plugin-worker-unavailable-error.js"; -import { writeToolConnectionHealthChange } from "../../tool-connection-health-notifications.js"; +import { notifyToolConnectionHealth, writeToolConnectionHealthChange } from "../../tool-connection-health-notifications.js"; import { connectionActorUserId } from "../actor.js"; import { assertSupportedConnection } from "../connections/setup-policy.js"; import { connectionSetupUrl, connectionReconnectUrl } from "../identifiers.js"; @@ -12,10 +12,10 @@ import { nativeProviderCatalogFor } from "../../native-provider-catalogs.js"; import { restConnectorFor } from "../../connectors/rest-registry.js"; import { retainMcpConnectionFailure } from "../../mcp-connection-failure.js"; import { isBrowserUseConnection } from "../../browser-use-client.js"; -import { and, asc, eq, isNull, lte, ne, or, sql } from "drizzle-orm"; +import { and, asc, eq, inArray, isNull, lte, ne, or, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; -import { connectionGrants, toolApplications, toolConnections, toolRuntimeSlots } from "@paperclipai/db"; -import type { ToolConnectionHealthCheckResult, ToolConnectionHealthStatus } from "@paperclipai/shared"; +import { chatEndpoints, connectionGrants, toolApplications, toolConnections, toolRuntimeSlots } from "@paperclipai/db"; +import type { ToolConnectionHealthCheckResult, ToolConnectionHealthStatus, ToolConnectionTransport } from "@paperclipai/shared"; import { HttpError, unprocessable } from "../../../errors.js"; import type { ToolAccessAudit } from "../audit.js"; @@ -23,7 +23,111 @@ import type { ConnectionCredentialAccess } from "../credential-access.js"; import type { ConnectionSetupPolicy } from "../connections/setup-policy.js"; import { toConnection } from "../connections/projection.js"; import { isAgentMailConnection, type ToolCatalogDiscovery } from "./discovery.js"; -import { healthFailureHttpStatus, isCallerAuthorizationFailure, sanitizeHttpFailure, unreachableServerRemediation, unsupportedToolConnectionTransport } from "./failures.js"; +import { healthFailureHttpStatus, isCallerAuthorizationFailure, sanitizeHttpFailure, unreachableServerRemediation, UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE, unsupportedToolConnectionTransport } from "./failures.js"; + +export const HEALTH_SWEEP_TRANSPORTS: readonly ToolConnectionTransport[] = [ + "mcp_remote", + "rest_api", + "local_stdio", + "plugin", +]; + +export function healthSweepConnectionWhere() { + return and( + eq(toolConnections.enabled, true), + eq(toolConnections.status, "active"), + inArray(toolConnections.transport, HEALTH_SWEEP_TRANSPORTS), + ne(toolApplications.type, "paperclip_plugin"), + ); +} + +/** + * Repair active Speko voice connections previously marked error by the generic + * tool health sweep before voice transport was excluded from sweeps. + */ +export async function repairUnsupportedVoiceConnectionHealth( + db: Db, + options: { + companyId?: string; + connectionId?: string; + now?: () => Date; + batchSize?: number; + signal?: AbortSignal; + } = {}, +): Promise { + const batchSize = Math.max(1, options.batchSize ?? 100); + const nowFn = options.now ?? (() => new Date()); + let totalRepaired = 0; + let cursor: string | undefined; + while (true) { + options.signal?.throwIfAborted(); + const candidates = await db + .selectDistinctOn([toolConnections.id], { + id: toolConnections.id, + companyId: toolConnections.companyId, + }) + .from(toolConnections) + .innerJoin(chatEndpoints, and( + eq(chatEndpoints.connectionId, toolConnections.id), + eq(chatEndpoints.companyId, toolConnections.companyId), + )) + .where(and( + eq(toolConnections.transport, "voice"), + eq(toolConnections.enabled, true), + eq(toolConnections.status, "active"), + eq(toolConnections.healthStatus, "error"), + eq(toolConnections.healthMessage, UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE), + eq(chatEndpoints.provider, "speko"), + eq(chatEndpoints.status, "active"), + isNull(chatEndpoints.lastError), + options.companyId === undefined ? undefined : eq(toolConnections.companyId, options.companyId), + options.connectionId === undefined ? undefined : eq(toolConnections.id, options.connectionId), + cursor === undefined ? undefined : sql`${toolConnections.id} > ${cursor}`, + )) + .orderBy(asc(toolConnections.id), asc(chatEndpoints.id)) + .limit(batchSize); + if (candidates.length === 0) break; + const candidateIds = candidates.map((row) => row.id); + cursor = candidateIds[candidateIds.length - 1]; + const repairedAt = nowFn().toISOString(); + const repairedRows = await db.transaction(async (tx) => { + // Register delivery work before the write so drain/sleep checks observe it. + for (const candidate of candidates) { + await notifyToolConnectionHealth(tx, { id: candidate.id, companyId: candidate.companyId }); + await notifyChatConnectionObservation(tx, candidate.id, "voice"); + } + return tx.execute<{ id: string; company_id: string }>(sql` + update ${toolConnections} as tc + set + health_status = 'healthy', + health_message = coalesce(ce.health_message, 'Connected'), + last_error = null, + updated_at = ${repairedAt}::timestamptz + from ( + select distinct on (connection_id) + connection_id, + company_id, + health_message + from ${chatEndpoints} + where provider = 'speko' and status = 'active' and last_error is null + order by connection_id, id + ) as ce + where tc.id in (${sql.join(candidateIds.map((id) => sql`${id}`), sql`, `)}) + and tc.id = ce.connection_id + and tc.company_id = ce.company_id + and tc.transport = 'voice' + and tc.enabled = true + and tc.status = 'active' + and tc.health_status = 'error' + and tc.health_message = ${UNSUPPORTED_TOOL_CONNECTION_TRANSPORT_MESSAGE} + returning tc.id, tc.company_id + `); + }); + totalRepaired += repairedRows.length; + if (candidates.length < batchSize) break; + } + return totalRepaired; +} function asRecord(value: unknown): Record { if (value && typeof value === "object" && !Array.isArray(value)) return value as Record; @@ -87,6 +191,15 @@ export function createConnectionHealth(db: Db, { now, audit, getConnectionRow, d ): Promise { const connection = await getConnectionRow(connectionId); if (connection.connectionPurpose === "ai") return { connection: toConnection(connection), runtimeSlot: null }; + if (connection.transport === "voice") { + const repaired = await repairUnsupportedVoiceConnectionHealth(db, { + companyId: connection.companyId, + connectionId: connection.id, + now, + }); + const current = repaired > 0 ? await getConnectionRow(connectionId) : connection; + return { connection: toConnection(current), runtimeSlot: null }; + } await assertConnectorConnectionSetupEnabled(connection); const unavailableServices: string[] = []; try { @@ -252,6 +365,7 @@ export function createConnectionHealth(db: Db, { now, audit, getConnectionRow, d async function sweepConnectionHealth( input: { staleAfterMs?: number; limit?: number } = {}, ) { + await repairUnsupportedVoiceConnectionHealth(db, { now }); const generatedAt = now(); const staleAfterMs = input.staleAfterMs ?? 15 * 60 * 1000; const limit = input.limit ?? 25; @@ -269,11 +383,7 @@ export function createConnectionHealth(db: Db, { now, audit, getConnectionRow, d )) .where( and( - eq(toolConnections.enabled, true), - eq(toolConnections.status, "active"), - ne(toolConnections.transport, "chat_sdk"), - ne(toolConnections.transport, "runtime_auth"), - ne(toolApplications.type, "paperclip_plugin"), + healthSweepConnectionWhere(), or(isNull(toolConnections.healthCheckedAt), lte(toolConnections.healthCheckedAt, cutoff)), ), ) diff --git a/server/src/services/voice/speko-skill.ts b/server/src/services/voice/speko-skill.ts index c66933a7eb7..388bf2c0204 100644 --- a/server/src/services/voice/speko-skill.ts +++ b/server/src/services/voice/speko-skill.ts @@ -27,7 +27,12 @@ Discover the assigned connection's call_my_phone tool through Paperclip's govern tool catalog. It calls only the responsible person's saved, opted-in number for the current task. Always pass the message parameter with the concise update, announcement, or question you want spoken immediately when they pick up; their spoken response will -be transcribed and recorded on this issue. Tool availability and Allowed / Ask first +be transcribed and recorded on this issue. If call_my_phone is not present in your +tools for this task, check task eligibility and tool access before assuming +callbacks are disabled: the gateway hides the tool when the responsible person +has not enabled Call my phone ("Allow this agent to call me about my tasks") in +the Speko connection's Settings tab, when tool access is off, or when the task is +not eligible. Tell them what to check before trying again. Tool availability and Allowed / Ask first / Off controls still apply. Never choose another recipient or bypass an approval. If creation has an uncertain outcome, inspect the existing attempt; never blindly redial. Report provider failures accurately without promising a callback.