Files
PaperClipAI/server/src/services/chat-runtime.ts
T
DottaandPaperclip 3ec7309d91 feat(voice): add experimental Speko task connection runtime (#15727)
First PR: runtime. UI: #15728. Qualification: #15729.

## Thinking Path

> - Paperclip manages agent work through tasks and governed connections.
> - Chat connections already bind external conversations to those tasks.
> - Speko handles voice and telephony, while the selected Paperclip
agent does the work.
> - A call needs durable session authority, ordered follow-ups, and safe
result delivery.
> - This PR adds an explicit voice transport to the existing connection
runtime.
> - The UI and qualification suites follow in linked PRs. Speko stays
experimental.

## Linked Issues or Issue Description

**Problem or motivation**

Phone and browser voice conversations cannot use the chat connection
task lifecycle. A separate voice runtime is needed to preserve task
authority, retries, and reply history.

**Proposed solution**

Add company-scoped voice sessions, signed callbacks, durable replies,
inbound intake, and an agent-facing outbound-call tool. Reuse existing
tasks, queues, secrets, and publications.

**Roadmap alignment**

This extends the experimental chat connector entry points under Agent
Chat and Connected Apps. The project owner requested this feature.

Refs #11418 for the original provider catalog proposal. This
implementation uses the newer chat connection infrastructure rather than
an MCP catalog-only integration. Refs #15721 for remote OpenCode
startup.

## What Changed

- Add additive voice schema, shared contracts, session APIs, and
provider callbacks.
- Bind browser, inbound, and outbound sessions to an endpoint, task, and
selected agent.
- Add low-trust guest intake in an explicitly selected sandbox and keep
ordinary approval rules.
- Submit task work through session-scoped tools and push approved
replies through Speko POST /v1/calls/{id}/messages.
- Distinguish provider acceptance from confirmed spoken playback.
Reconcile reports without downloading recordings.
- Add protocol, migration, persistence, provider, and
delivery-diagnostic tests.

## Verification

- Master 3389bea708 is integrated. Database/shared builds, server
typecheck, migration upgrade/replay checks, and 46
communication-guidance/provider/protocol tests passed.
- The final persistence suite passed 85 real-database tests. Five
focused native continuation/authorization regressions passed. Five
callback ownership/rotation tests passed after the last runtime repair.
- Review repairs cover reconnect ownership, current caller authority,
duplicate delivery, multipart answers, task-page answers, guest question
handling, and saved sandbox recovery.
- A real OpenCode/OpenRouter DeepSeek task ran in Daytona and saved a
correct disk-space answer. This did not establish live-call playback.
- Full local typecheck/build passed before the final repairs; focused
typechecks passed after them. Latest-head CI runs the repository gates.
- The separate integrated browser qualification passed two journeys and
failed browser answer retrieval. The feature remains experimental. The
report in #15729 records this failure and outstanding real-provider
acceptance.
- No lockfiles are included. Speko migrations follow master as
0324–0330.

## Risks

- Voice sessions add migrations and provider-dependent lifecycle
behavior. Migrations preserve existing chat and AI transports.
- Callback origins must be reachable HTTPS. Provider keys and signing
secrets remain vaulted.
- Unverified callers receive task-scoped low-trust authority. Caller ID
does not grant private task access.
- Outbound telephony incurs provider charges. Provider acceptance is not
proof that the caller heard an answer.
- Keep the feature behind the existing experimental chat setting until
the real browser, inbound, outbound, and delayed-result acceptance
matrix passes.

## Model Used

OpenAI Codex, GPT-6, with tool use and code execution. The exact serving
model ID and context window are not exposed in this session.

## 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
- [ ] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-09 21:54:11 -05:00

148 lines
5.4 KiB
TypeScript

import type { WebhookOptions } from "chat";
import { createChatSdkEndpointRuntime, ChatSdkEndpointNotRegisteredError, type CreateChatSdkEndpointRuntimeOptions } from "./chat-sdk-runtime.js";
import { createVoiceRuntime, type ChatEndpointRuntime, type CreateVoiceRuntimeOptions } from "./voice/voice-runtime.js";
/** One lifecycle registry for the Chat SDK and hosted voice transports. */
export class ChatRuntime {
private readonly endpoints = new Map<string, ChatEndpointRuntime>();
private readonly retiringEndpoints = new Map<
string,
ChatEndpointRuntime
>();
private readonly lifecycleTails = new Map<string, Promise<void>>();
private readonly replacementGenerations = new Map<string, number>();
private shuttingDown = false;
get(endpointId: string): ChatEndpointRuntime | null {
if (this.shuttingDown) return null;
return this.endpoints.get(endpointId) ?? null;
}
list(): ChatEndpointRuntime[] {
if (this.shuttingDown) return [];
return [...this.endpoints.values()];
}
private enqueueLifecycle<T>(
endpointId: string,
operation: () => Promise<T>,
): Promise<T> {
const previous = this.lifecycleTails.get(endpointId) ?? Promise.resolve();
const result = previous.then(operation);
// A failed shutdown must not poison the queue or release ownership of a
// possibly still-running predecessor. Only an explicit later operation
// retries retirement; callers still receive the original failure.
const settled = result.then(
() => undefined,
() => undefined,
);
this.lifecycleTails.set(endpointId, settled);
void settled.then(() => {
if (this.lifecycleTails.get(endpointId) === settled) {
this.lifecycleTails.delete(endpointId);
}
});
return result;
}
private async retireEndpoint(endpointId: string): Promise<boolean> {
const previous =
this.endpoints.get(endpointId) ?? this.retiringEndpoints.get(endpointId);
if (!previous) return false;
this.endpoints.delete(endpointId);
this.retiringEndpoints.set(endpointId, previous);
await previous.shutdown();
this.retiringEndpoints.delete(endpointId);
return true;
}
private nextReplacementGeneration(endpointId: string): number {
const next = (this.replacementGenerations.get(endpointId) ?? 0) + 1;
this.replacementGenerations.set(endpointId, next);
return next;
}
private assertReplacementCurrent(
endpointId: string,
generation: number,
): void {
if (this.shuttingDown) throw new Error("Chat SDK runtime is shutting down");
if (this.replacementGenerations.get(endpointId) !== generation) {
throw new Error(
`Chat SDK runtime replacement for endpoint ${endpointId} was superseded`,
);
}
}
async replaceEndpoint(
options: CreateChatSdkEndpointRuntimeOptions,
): Promise<ChatEndpointRuntime> {
if (this.shuttingDown) throw new Error("Chat SDK runtime is shutting down");
const generation = this.nextReplacementGeneration(options.endpointId);
return await this.enqueueLifecycle(options.endpointId, async () => {
this.assertReplacementCurrent(options.endpointId, generation);
await this.retireEndpoint(options.endpointId);
this.assertReplacementCurrent(options.endpointId, generation);
const next = createChatSdkEndpointRuntime(options);
this.endpoints.set(options.endpointId, next);
// The service installs callback context before initialize() starts the
// Discord gateway. Preserve that caller-owned initialization boundary.
return next;
});
}
async replaceVoiceEndpoint(options: CreateVoiceRuntimeOptions): Promise<ChatEndpointRuntime> {
if (this.shuttingDown) throw new Error("Chat runtime is shutting down");
const generation = this.nextReplacementGeneration(options.endpointId);
return this.enqueueLifecycle(options.endpointId, async () => {
this.assertReplacementCurrent(options.endpointId, generation);
await this.retireEndpoint(options.endpointId);
this.assertReplacementCurrent(options.endpointId, generation);
const next = createVoiceRuntime(options);
this.endpoints.set(options.endpointId, next);
return next;
});
}
async removeEndpoint(endpointId: string): Promise<boolean> {
this.nextReplacementGeneration(endpointId);
return await this.enqueueLifecycle(
endpointId,
async () => await this.retireEndpoint(endpointId),
);
}
async handleWebhook(
endpointId: string,
request: Request,
options?: WebhookOptions,
responseDeadlineAt?: number,
): Promise<Response> {
const runtime = this.get(endpointId);
if (!runtime) throw new ChatSdkEndpointNotRegisteredError(endpointId);
return await runtime.handleWebhook(request, options, responseDeadlineAt);
}
async shutdown(): Promise<void> {
this.shuttingDown = true;
const endpointIds = new Set([
...this.endpoints.keys(),
...this.retiringEndpoints.keys(),
...this.lifecycleTails.keys(),
]);
const results = await Promise.allSettled(
[...endpointIds].map(
async (endpointId) =>
await this.enqueueLifecycle(
endpointId,
async () => await this.retireEndpoint(endpointId),
),
),
);
const failure = results.find((result) => result.status === "rejected");
if (failure?.status === "rejected") throw failure.reason;
}
}
export function createChatRuntime() { return new ChatRuntime(); }