mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-31 14:16:39 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - Connections provide governed tools, chat channels, model accounts,
and gateways.
> - Several management routes require a human board actor even when an
agent has the required grant.
> - Default agents must configure these resources within the responsible
user's authority.
> - This pull request adds a shared authorization path to the existing
REST and native API surface.
> - Human authentication, execution approvals, and local host boundaries
remain enforced.
> - The benefit is that a standard agent can complete authorized setup
with a bounded human handoff.
## Linked Issues or Issue Description
**Subsystem affected**
Server authorization, connection services, shared contracts, native API
discovery, database schema.
**Problem or motivation**
Connection administration is available in the web app but often
unavailable to agents. Agent grants, responsible-user authority,
credential ownership, and actor attribution need separate checks.
Opening gateway-token creation also requires preserving the issuing
agent's delegated authority during token use.
**Proposed solution**
Use the existing authorization evaluator for every connection family.
Enforce current responsible-user authority, effective trust, grant
scope, resource visibility, and target-agent access. Keep existing agent
grants unchanged. Expose authorized configuration through default
`search_api` and `call_api`. Save human authentication steps and let
agents continue after completion.
**Roadmap alignment**
This change completes the API access path for the existing Connected
Apps, Personal & Shared AI Accounts, and governed MCP Gateway
capabilities in `ROADMAP.md`. It follows the maintainer's requested
design. Related work: #11899 enforces connection execution access and
creator/manager rules; this PR extends agent management across
connection families. It does not replace that execution-policy work.
## What Changed
- Add shared connection management context and mandatory
responsible-user, trust, scope, and target checks.
- Allow authorized agents to configure tool, chat/email, GitHub/Slack,
AI, profile, and gateway resources through existing routes.
- Preserve human credential ownership and record the actual agent,
responsible user, and run or key in audit data.
- Preserve saved browser authentication handoffs and callback session
checks.
- Bind agent-issued durable gateway tokens to their responsible user and
recheck delegated authority at use.
- Add explicit REST transport and management capability metadata,
built-in guidance, and sensitive-response handling.
- Intersect caller and endpoint-agent Slack test/invitation policies,
including independent and shared rates. Require the addressed human’s
current endpoint identity link before completing identity handoffs.
- Add production-authenticated integration scenarios. Companion #17739
contains the saved setup UI (including the required human
import/rotation step), product and permission documentation,
catalog/Vercel credential and callback ownership, and operation maps to
keep each review below 100 files. Both PRs must ship together; merge
this implementation first, then its companion.
## Verification
- Current implementation head:
`2ecd6451d0d0c8d82121a4e3fa4ce94c5befbbd6`, including master
`ea727dc3c2`, 99 files. The latest follow-up fixes the two valid
findings from the preceding f9 review. Exact-head Greptile has completed
at5/5 with no findings and Superagent passed. Full exact-head Linux CI
workflow40446606056 completed SUCCESS; only the queued external
Paperclip Review remains pending; earlier Linux passes do not qualify
this successor.
- Latest preserved-stack verification passed **2,165 tests** in fresh
PostgreSQL: **70 actual-auth scenarios**, 27 OpenAPI contracts, 2,022
native API tests and 46 saved GitHub wizard cases. **141 existing
gateway/policy acceptance tests** also passed. Workspace
typecheck/build, maps and token gates passed. The first workspace
typecheck was blocked by sandbox tsx IPC permissions; its authorized
rerun passed. This is focused local evidence; the full Linux CI matrix
is still required.
- Issuer/target gateway policy regressions were red before the fix. Both
decisions now intersect, including Block/Ask first/rates, same
credential identity and current token/user/agent authority after
approval. Invocations retain their token and actual requesting agent;
deleted tokens fail closed. Thirteen actual-auth cases cover revocation,
narrowed scope, approvals, shared rates and board compatibility.
Intermediate missing-token attribution, review-context and
implicit-session actor failures remain in the qualification record; all
final cases pass.
- Activity pagination now retains a bounded cursor across private-only
windows. The actual-JWT regression reaches three older readable events
after 27 private ones without exposing private details. A native
device-login regression was red for plaintext receipts; local check and
test-call results now use existing protected-response handling. The
passing actual-auth case proves encrypted persistence, exact replay,
redacted history and no response asset.
- Previous-head `5b55195593` Linux CI initially failed e2e shard 4/8 in
the existing connection-intent continuation test: periodic recovery
queued a repair at 01:21:47, the scripted journey completed the task at
01:21:48, and the extra queued run was cancelled at 01:21:49 because the
task was terminal. The assertion selected that latest cancelled run.
GitHub refused the first attempt while the workflow was nonterminal.
After completion, the single evidence-supported failed-job rerun was
accepted as **attempt 2** on the same head (workflow 40431202466). The
failed shard and final E2E aggregate passed on attempt 2, and the
complete Linux workflow for that head is successful. The original
failure remains part of qualification. No additional unchanged-code
rerun will be used for this failure.
- Companion CI also has an unchanged login-cleanup idleness timeout,
retained in its qualification record. That same 16-case suite passed in
this parent Linux run and a fresh local database. Both preceding
workflows passed after their single failed-job reruns as attempt 2; the
original failures remain recorded. No additional unchanged-code rerun
was used.
- Migration `0380_broken_aqueduct.sql` was regenerated through the
repository workflow after master took 0379 for project Git
authorization. It adds the responsible-user column with `IF NOT EXISTS`,
preserves upstream migrations, and satisfies snapshot retention and
migration safety checks.
- Upstream published Copilot v62 and v63 identities remain byte-for-byte
unchanged. The combined guidance is now v64, digest
`sha256:22e31f95ef972bcead98a4a707c9f33433558fd111e390e027a2bbb4346e112a`.
The normal shared TypeScript/Rust identity check and **61 Copilot
installation tests passed**. The old source-identity assertion first
failed against unchanged published v63; regenerating a new v64 preserves
the published release.
- Workspace `pnpm -r typecheck` and `pnpm build`, map validation, and UI
token gates passed on the final combined stack after the upstream merge.
Node 24.22.1 / pnpm 9.15.4 were used.
- **Earlier 82 API/OpenAPI tests passed** in fresh PostgreSQL 18: 55
assembled-server scenarios and 27 contracts. They use real persistent
agent keys, run JWTs, human sessions, production defaults, and
deterministic provider fixtures. No actor injection establishes access.
- The new email regression was red before per-account scope filtering.
The Arcade regression was red before human ownership and inventory-key
fixes; it also verifies actual-agent audit identity and a human-session
inventory read. The activity regression measured **200 authorization
checks before the fix and one afterward** for the same one-item page.
- **82 GitHub UI tests passed**, including all three new
failed-replacement regressions that were red before their fix. The UI
preserves an earlier copy only after confirming its committed
generation. Changed or unreadable results block copying and reconnecting
until reconciled. Human-only secret responses now include their
nonsecret committed generation.
- Private test status now rechecks the originating principal and linked
task, including mandatory agent/responsible-user privacy. Cross-agent
tests require the full caller tool access decision and the same
credential identity, regardless of auth label; caller and target
policies/approvals and rate limits apply before execution and after
human approval. A profile-only precondition was found to reject valid
allow-policy and scoped-grant access and has been removed. Both
permitted-access cases and a no-auth-label identity regression were red
before the correction; caller-specific Block still prevents provider
execution. The private-status regression was also red before its fix.
- The tool-activity regression measured 100 capability decisions and 102
run captures on a 100-event page before the fix. It now uses two task
decisions and at most two captures while retaining the same 50 visible
events, private-event filtering, and 403 after audit-grant revocation.
The regression was red before request-context reuse and task-decision
sharing; final server typecheck/build also pass.
- Generic chat configure/reconnect now hands agent-supplied verification
credentials to the addressed human before provider work or vault
changes. Actual key/JWT regressions were red for Slack signing-key
replacement and generic channel secret-reference rebinding. They now
prove unchanged refs and vaulted signing value, human setup, permitted
agent bot-token repair, and governed test messages. All 82 API/OpenAPI
cases pass in fresh PostgreSQL. Eight native receipt protections and
final server typecheck/build also pass.
- The preceding review found that old healthy state could retire a
credential-entry card before a human changed anything. The actual-JWT
regression was red. Saved field generations now change only with
protected values and commit with refs plus a verification fence; retries
retain the baseline. Old health, bot-token repair and unchanged entry
stay pending. New signing verification and current authority permit
continuation. A separate red race proved that user revocation during
provider authentication could return 403 after refs changed; authority
is now checked before persistence and inside the credential transaction.
The final 82 API/OpenAPI cases, four neighboring real-database
Slack/GitHub lifecycle cases, and final server typecheck/build pass.
- A preceding full run crossed a rate-window boundary. Database rows
prove one consumed slot at 23:35 and another at 23:36 for the same
policy/bucket. Only Date is frozen in the rate test cases; transport and
asynchronous timers remain real. Production rate behavior is unchanged,
and the final full run passes. An intermediate fixture failure that
overwrote hidden generation metadata with an API projection is retained
in the qualification record.
- Linux CI on an earlier head found two rate-admission assertions that
omitted the newly persisted bucket key. The failures were reproduced
locally; both assertions now verify the exact actor/tool bucket and all
49 policy-service tests pass. The companion qualification record retains
the initial and intermediate failures. Catalog creator attribution is
preserved in the companion to keep this implementation review at 99
files.
- The latest review reproduced three regressions before repair: complete
human replacements failed on unavailable old signing secrets, fresh
GitHub links incorrectly selected reconnect, and different
credential-entry requests shared an idempotency key. Each old protected
ref now has a narrow known-unavailable fallback; unexpected resolver
failures and company/scope violations still abort. Fresh imports keep
their credential form, configured endpoints keep reconnect, and
canonical field sets/completion modes distinguish handoffs while
matching retries retain their baseline. All 55 actual-auth scenarios and
27 separately run OpenAPI contracts pass, as do server typecheck/build.
Companion #17739 also passes all 41 wizard tests including actual
fresh-form submission, UI typecheck, maps and token gates. Earlier red
results and a mistyped OpenAPI filename are retained in qualification.
- The configured GitHub handoff regression was red in the
browser-component tests and actual-auth link/persistence tests. Saved
links now name requested fields and all/any completion mode; the
companion form submits those supplied fields through reconnect and
retains other saved credentials. Webhook/client-secret reconnect remains
human-only; first-setup secret restrictions remain. All 46 wizard tests
pass, including combined modes and legacy links. A duplicate review
referenced the older companion bf760912; the current form is already
fixed, linked in the reply, and its thread is resolved.
- Linux CI on bf760912 failed automatic Slack provisioning because vault
persistence cleared an already verified manifest-update challenge. The
same regression was reproduced locally. The provider-owned helper now
preserves proof only for the current signing fingerprint and callback
URL. Eight existing compatibility cases pass, including this case and
initial GitHub secret rejection. The first uncommitted GitHub-field
variant also failed that initial boundary and was narrowed to reconnect;
both failures remain in qualification.
- The upstream merge conflicted only in generated migration metadata.
Upstream 0379 is preserved, normal generation/pruning produced 0380, and
two repeated applications of the idempotent additive SQL passed. The
final combined stack passed **128 tests** (55 actual-auth, 27 OpenAPI
and 46 wizard cases) in fresh PostgreSQL. Eight Google UI cases also
pass; the two protocol cases could not initialize embedded PostgreSQL in
this fresh local attempt. Their earlier passing evidence remains
historical; fresh Linux CI must execute them. Vercel personal credential
attribution is preserved in companion #17739 with its other
ownership/consent follow-ups, keeping this PR at 99 files.
- The suite covers fresh defaults, restricted users/agents, scopes,
personal isolation, token revocation, human handoffs, callback replay,
execution approvals, authorized self-targeted policy changes,
self-approval denial, and current authority before commit. Reproduce API
checks with `pnpm exec vitest run
server/src/__tests__/connection-management.integration.test.ts
server/src/__tests__/openapi-routes.test.ts`, using a fresh database
through `PAPERCLIP_CONNECTION_MANAGEMENT_TEST_DATABASE_URL` or the
default embedded test database.
- Companion #17739 also records consent separately from token refresh so
saved Google choices survive refresh. Its eight service-picker and two
local-HTTP OAuth tests pass; both new UI cases were red before the fix.
Normal migration generation confirms no SQL change is needed for the
additive JSON metadata.
- The integration module shares one assembled server, authentication
factory, and provider lifecycle to preserve the
HTTP-to-vault-to-task-continuation proof. A reused external database
caused a Slack fixture identity conflict; the fresh final run passed.
Earlier fixture/transport and contract-update failures remain in the
companion qualification record.
- The broad local `pnpm test:run` attempt remains blocked by macOS
embedded PostgreSQL's host semaphore limit. It is not a clean pass. The
fresh Linux CI matrix must complete. Provider fixtures do not prove live
setup or an empirical LLM success rate.
- A current-head completed Paperclip assessment is not yet recorded. Its
earlier external recovery boundary has not been bypassed, and no
incomplete assessment is reported as passing. The user authorized both
merges when checks pass; merge this implementation first, then replay,
retarget, and requalify companion #17739 against the squash-merged
master.
- After the master refresh, local workspace typecheck/build, **97
actual-auth/OpenAPI cases** and **141 gateway/policy cases** pass. The
original fixed database port was occupied; Docker assigned a free
localhost port. The first neighbor setup command could not resolve root
`tsx`, leaving its schema uninitialized; the built database package
migrated the separate fixture and all unchanged cases passed. Both setup
failures are retained in qualification. Fresh Linux CI remains required;
no full local test-sweep pass is claimed.
- The f9 Greptile review scored **2/5** for two reproduced findings:
Slack test sends skipped the caller’s tool policy, and healthy App
credentials completed an unconfirmed identity handoff. Both are fixed in
this head and have resolved evidence threads
([Slack](https://github.com/paperclipai/paperclip/pull/17737#discussion_r4384927765),
[identity](https://github.com/paperclipai/paperclip/pull/17737#discussion_r4384927895)).
Actual key/JWT cases cover twelve Slack caller/target/recipient
combinations; the human-session GitHub OAuth callback alone remains
pending until explicit confirmation. All **99 API/OpenAPI tests** (72
actual-auth + 27 contracts), workspace typecheck and build pass. On the
combined companion, all four focused cases (including the twelve Slack
combinations), typecheck/build and maps also pass. The continuation
suite’s 50 embedded-PG cases were skipped because its database could not
start locally; fresh Linux CI must run them. Initial fixture
credential-collision and audit-projection assertion failures are
retained with the red reproductions in the companion qualification
record. No full local sweep or live consent is claimed.
## Risks
- The maintainer explicitly confirmed authorized policy administration,
including self-targeted changes that loosen controls. These writes
require management grants and the responsible user’s current authority.
Agents cannot approve their own governed action requests or edit their
own principal permission grants. The actual-auth regression exercises
both permitted administration and those denials.
- This is a broad authorization change. Incorrect scope or owner
resolution could deny permitted setup or expose another user's
resources. Integration cases cover both permitted and denied requests
with actual authentication.
- The additive nullable gateway-token column does not infer identities
for legacy clients or backfill agent grants. Legacy agent tokens without
a responsible user fail closed.
- Provider fixtures test supported setup and callback contracts. They do
not prove live provider availability.
## Model Used
- OpenAI Codex, GPT-6 family, with reasoning, repository tools, and code
execution. The runtime does not expose a more specific deployment ID or
context-window size.
## 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 — focused suites above;
full local sweep remains blocked as documented
- [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
- [ ] All Paperclip CI gates are green — exact `2ecd6451d0` Linux CI
completed SUCCESS; external Paperclip Review is still queued
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups —
exact `2ecd6451d0` review completed; both f9 findings have resolved
evidence replies
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
1514 lines
65 KiB
TypeScript
1514 lines
65 KiB
TypeScript
import { promptInjectionPreventionRoutes } from "./routes/prompt-injection-prevention.js";
|
|
import { voiceSessionRoutes, voiceWebhookRoutes } from "./routes/voice-sessions.js";
|
|
import { eq } from "drizzle-orm";
|
|
import { chatEndpoints } from "@paperclipai/db";
|
|
import { fastResponseRoutes } from "./routes/fast-responses.js";
|
|
import { fastResponseService } from "./services/fast-responses.js";
|
|
import { createDeliveryWorkCoordinator } from "./services/delivery-work-coordinator.js";
|
|
import { DELIVERY_QUEUES } from "./services/delivery-work-notifications.js";
|
|
import { createLifecycleDriver } from "./services/agent-lifecycle-driver.js";
|
|
import { startAgentLifecycle } from "./services/agent-lifecycle.js";
|
|
import { idleAdmissionMiddleware, trackIdleRequestHandlers } from "./middleware/idle-admission.js";
|
|
import { staticUiFiles } from "./middleware/static-ui.js";
|
|
import { isIdleTaskDrainActive, trackIdleWork } from "./services/task-admission.js";
|
|
import { customerSuccessRoutes } from "./routes/customer-success.js";
|
|
import { cloudWarmStandbyMiddleware } from "./middleware/cloud-warm-standby.js";
|
|
import type { CloudWarmStandby } from "./services/cloud-warm-standby.js";
|
|
import { browserUseRoutes } from "./routes/browser-use.js";
|
|
import { registerChatActionWork } from "./services/chat-action-work.js";
|
|
import { registerChatDeliveryWork } from "./services/chat-delivery-work.js";
|
|
import { registerBrowserUseCleanup } from "./services/browser-use-work.js";
|
|
import { browserUseService } from "./services/browser-use.js";
|
|
import { slackToolRoutes } from "./routes/slack-tools.js";
|
|
import { createPublicMcpOAuth, publicMcpConfig } from "./services/public-mcp/oauth.js";
|
|
import { createDotRunnerMcpTools, dotRunnerBroker } from "./services/dot-runner-broker.js";
|
|
import { agentProfileAvatarRoutes } from "./routes/agent-profile-avatar.js";
|
|
import { museTransportRoutes, museBoardRoutes } from "./routes/muse.js";
|
|
import { museQualificationRoutes } from "./routes/muse-qualification.js";
|
|
import { startMuseMaintenance } from "./services/muse-maintenance.js";
|
|
import { grokBotRoutes } from "./routes/grok-bot.js";
|
|
import { createGrokRoutineDispatcher } from "./services/grok-bot/dispatcher.js";
|
|
import { dotRunnerRoutes } from "./routes/dot-runner.js";
|
|
import { createPublicMcpTransfers } from "./services/public-mcp/file-transfers.js";
|
|
import { createMcpApiDispatch, createPublicMcpExecutor } from "./services/public-mcp/capabilities.js";
|
|
import { createPublicMcpEvents, type PublicMcpEvents } from "./services/public-mcp/events.js";
|
|
import { publicMcpIngressRoutes, publicMcpManagementRoutes } from "./routes/public-mcp.js";
|
|
import { agentAvatarRoutes } from "./routes/agent-avatars.js";
|
|
import { decisionModelRoutes } from "./routes/decision-models.js";
|
|
import { agentObservabilityRoutes } from "./routes/agent-observability.js";
|
|
import { aiConnectionRoutes } from "./routes/ai-connections.js";
|
|
import { taskWorkspaceRoutes } from "./routes/task-workspaces.js";
|
|
import { projectToolRoutes } from "./routes/project-tools.js";
|
|
import { emailChannelService } from "./services/email-channels.js";
|
|
import { emailRoutes, emailWebhookRoutes } from "./routes/email.js";
|
|
import { toolActionDeliveryService } from "./services/tool-action-delivery.js";
|
|
import { registerAssignedMcpGateway } from "./services/native-runtime/assigned-mcp-tools.js";
|
|
import express, { Router, type Request as ExpressRequest } from "express";
|
|
import {
|
|
createServer as createHttpServer,
|
|
type Server as HttpServer,
|
|
} from "node:http";
|
|
import path from "node:path";
|
|
import fs from "node:fs";
|
|
import { fileURLToPath } from "node:url";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
derivePaperclipViteHmrPort,
|
|
type DeploymentExposure,
|
|
type DeploymentMode,
|
|
} from "@paperclipai/shared";
|
|
import type { InspectDatabaseBackupHealthOptions } from "./services/database-backup-health.js";
|
|
import type { StorageService } from "./storage/types.js";
|
|
import { httpLogger, errorHandler } from "./middleware/index.js";
|
|
import { skillAccessRequestContext } from "./services/skill-access.js";
|
|
import { actorMiddleware } from "./middleware/auth.js";
|
|
import { boardMutationGuard } from "./middleware/board-mutation-guard.js";
|
|
import {
|
|
privateHostnameGuard,
|
|
resolvePrivateHostnameAllowSet,
|
|
} from "./middleware/private-hostname-guard.js";
|
|
import {
|
|
applyTrustProxy,
|
|
parseTrustProxyEnv,
|
|
} from "./middleware/trust-proxy.js";
|
|
import {
|
|
IMPORT_TRANSFER_SPOOL_SWEEP_INTERVAL_MS,
|
|
resolveDefaultImportTransferSpoolRoot,
|
|
sweepAbandonedImportTransferSpools,
|
|
} from "./services/company-import-transfers.js";
|
|
import { companyTransferRunService } from "./services/company-transfer-runs.js";
|
|
import { healthRoutes } from "./routes/health.js";
|
|
import { livenessRoutes } from "./routes/liveness.js";
|
|
import { cloudRuntimeIdentityMiddleware } from "./middleware/cloud-runtime-identity.js";
|
|
import { cloudControlMiddleware } from "./middleware/cloud-control.js";
|
|
import { cloudRoutes } from "./routes/cloud.js";
|
|
import { companyRoutes } from "./routes/companies.js";
|
|
import { companySkillRoutes } from "./routes/company-skills.js";
|
|
import { companySkillPolicyRoutes } from "./routes/company-skill-policy.js";
|
|
import { inboxAgentPolicyRoutes } from "./routes/inbox-agent-policy.js";
|
|
import { builtInAgentRoutes } from "./routes/built-in-agents.js";
|
|
import { folderRoutes } from "./routes/folders.js";
|
|
import { summarySlotRoutes } from "./routes/summary-slots.js";
|
|
import { statusCardRoutes } from "./routes/status-cards.js";
|
|
import { teamsCatalogRoutes } from "./routes/teams-catalog.js";
|
|
import { agentRoutes } from "./routes/agents.js";
|
|
import { resolveAgentRunnerTargetForCompany } from "./services/agent-runner-selection.js";
|
|
import type { SetupTokenSessionService } from "./services/setup-token-session.js";
|
|
import {
|
|
buildSetupTokenLoginTransport,
|
|
createProductionSetupTokenSandboxProvider,
|
|
createProductionSetupTokenCleanupStore,
|
|
createSetupTokenSecretWriter,
|
|
createWorkerBoundLoginPtyOpener,
|
|
} from "./services/setup-token-transport-binding.js";
|
|
import { environmentService } from "./services/environments.js";
|
|
import { environmentRuntimeService } from "./services/environment-runtime.js";
|
|
import { projectRoutes } from "./routes/projects.js";
|
|
import { issueRoutes } from "./routes/issues.js";
|
|
import { issueTreeControlRoutes } from "./routes/issue-tree-control.js";
|
|
import { caseRoutes } from "./routes/cases.js";
|
|
import { caseHandoffRoutes } from "./routes/case-handoffs.js";
|
|
import { workflowRoutes } from "./routes/workflows.js";
|
|
import { fileResourceRoutes } from "./routes/file-resources.js";
|
|
import { routineRoutes } from "./routes/routines.js";
|
|
import { environmentRoutes } from "./routes/environments.js";
|
|
import { executionWorkspaceRoutes } from "./routes/execution-workspaces.js";
|
|
import { goalRoutes } from "./routes/goals.js";
|
|
import { onboardingSeedRoutes } from "./routes/onboarding-seed.js";
|
|
import { boardChatRoutes } from "./routes/board-chat.js";
|
|
import { approvalRoutes } from "./routes/approvals.js";
|
|
import { secretRoutes } from "./routes/secrets.js";
|
|
import { toolAccessRoutes } from "./routes/tool-access.js";
|
|
import {
|
|
chatChannelRoutes,
|
|
chatWebhookRoutes,
|
|
} from "./routes/chat-channels.js";
|
|
import { smokeLabRoutes } from "./routes/smoke-lab.js";
|
|
import { costRoutes } from "./routes/costs.js";
|
|
import { agentCommentaryRoutes } from "./routes/agent-commentary.js";
|
|
import { activityRoutes } from "./routes/activity.js";
|
|
import { dashboardRoutes } from "./routes/dashboard.js";
|
|
import { attentionRoutes } from "./routes/attention.js";
|
|
import { decisionTrainingRoutes } from "./routes/decision-training.js";
|
|
import { decisionRoutes } from "./routes/decisions.js";
|
|
import { decisionQueueRoutes } from "./routes/decision-queues.js";
|
|
import type { DecisionServiceOptions } from "./services/decisions.js";
|
|
import { userProfileRoutes } from "./routes/user-profiles.js";
|
|
import { sidebarBadgeRoutes } from "./routes/sidebar-badges.js";
|
|
import { sidebarPreferenceRoutes } from "./routes/sidebar-preferences.js";
|
|
import { announcementRoutes } from "./routes/announcements.js";
|
|
import { serverVersion } from "./version.js";
|
|
import { primaryAgentRoutes } from "./routes/primary-agent.js";
|
|
import { resourceMembershipRoutes } from "./routes/resource-memberships.js";
|
|
import { inboxDismissalRoutes } from "./routes/inbox-dismissals.js";
|
|
import { instanceSettingsRoutes } from "./routes/instance-settings.js";
|
|
import { instanceSettingsService } from "./services/instance-settings.js";
|
|
import { openApiRoutes } from "./routes/openapi.js";
|
|
import {
|
|
instanceDatabaseBackupRoutes,
|
|
type InstanceDatabaseBackupService,
|
|
} from "./routes/instance-database-backups.js";
|
|
import { llmRoutes } from "./routes/llms.js";
|
|
import { authRoutes } from "./routes/auth.js";
|
|
import { assetRoutes } from "./routes/assets.js";
|
|
import { accessRoutes } from "./routes/access.js";
|
|
import { pluginRoutes } from "./routes/plugins.js";
|
|
import {
|
|
mcpGatewayProtocolRoutes,
|
|
toolGatewayRoutes,
|
|
} from "./routes/tool-gateway.js";
|
|
import {
|
|
connectionIntentBoardRoutes,
|
|
runtimeConnectionIntentRoutes,
|
|
} from "./routes/connection-intents.js";
|
|
import { adapterRoutes } from "./routes/adapters.js";
|
|
import { managedAgentProfileRoutes } from "./routes/managed-agent-profiles.js";
|
|
import { remoteAgentProfileRoutes } from "./routes/remote-agent-profiles.js";
|
|
import { pluginUiStaticRoutes } from "./routes/plugin-ui-static.js";
|
|
import { readBrandedStaticIndexHtml } from "./static-index-html.js";
|
|
import { staticUiCacheControl } from "./static-ui-cache.js";
|
|
import { staticUiCompression } from "./middleware/static-ui-compression.js";
|
|
import { applyUiBranding } from "./ui-branding.js";
|
|
import { logger } from "./middleware/logger.js";
|
|
import {
|
|
DEFAULT_LOCAL_PLUGIN_DIR,
|
|
pluginLoader,
|
|
type PluginLoader,
|
|
} from "./services/plugin-loader.js";
|
|
import {
|
|
SELF_HOSTED_AUTO_INSTALL_KEYS,
|
|
BUNDLED_PLUGIN_CATALOG,
|
|
ensureBundledPlugins,
|
|
resolveBundledCatalogRoot,
|
|
resolveBundledPluginInstalls,
|
|
} from "./services/bundled-plugins.js";
|
|
import { readDistributionPluginCatalog, distributionPluginActivationGuard } from "./services/distribution-plugin-catalog.js";
|
|
import {
|
|
createPluginWorkerManager,
|
|
type PluginWorkerManager,
|
|
} from "./services/plugin-worker-manager.js";
|
|
import { createPluginJobScheduler } from "./services/plugin-job-scheduler.js";
|
|
import { pluginJobStore } from "./services/plugin-job-store.js";
|
|
import { createPluginToolDispatcher } from "./services/plugin-tool-dispatcher.js";
|
|
import { createToolGatewayService } from "./services/tool-gateway.js";
|
|
import { toolAccessService } from "./services/tool-access.js";
|
|
import { chatChannelService } from "./services/chat-channels.js";
|
|
import { deliverNativeQuestionResponse } from "./services/native-runtime/native-question-bridge.js";
|
|
import { enqueueChatRunMilestones } from "./services/chat-run-publications.js";
|
|
import {
|
|
createCoalescedAsyncTrigger,
|
|
isChatPublicationCommitSignal,
|
|
} from "./services/chat-publication-reconciliation.js";
|
|
import { subscribeAllCompanyLiveEvents } from "./services/live-events.js";
|
|
import { heartbeatService } from "./services/heartbeat.js";
|
|
import { pluginLifecycleManager } from "./services/plugin-lifecycle.js";
|
|
import { registerPluginLifecycleDelivery } from "./services/plugin-lifecycle-delivery.js";
|
|
import { createPluginJobCoordinator } from "./services/plugin-job-coordinator.js";
|
|
import {
|
|
buildHostServices,
|
|
flushPluginLogBuffer,
|
|
} from "./services/plugin-host-services.js";
|
|
import { createPluginEventBus } from "./services/plugin-event-bus.js";
|
|
import { setPluginEventBus } from "./services/activity-log.js";
|
|
import { createPluginDevWatcher } from "./services/plugin-dev-watcher.js";
|
|
import { createPluginHostServiceCleanup } from "./services/plugin-host-service-cleanup.js";
|
|
import { pluginRegistryService } from "./services/plugin-registry.js";
|
|
import { createHostClientHandlers } from "@paperclipai/plugin-sdk";
|
|
import type { BetterAuthSessionResult } from "./auth/better-auth.js";
|
|
import { createCachedViteHtmlRenderer } from "./vite-html-renderer.js";
|
|
import {
|
|
DEFAULT_JSON_BODY_LIMIT,
|
|
PORTABLE_JSON_BODY_LIMIT,
|
|
} from "./http/body-limits.js";
|
|
import { COMPANY_IMPORT_API_PATH } from "./routes/company-import-paths.js";
|
|
import { apiCompression } from "./middleware/api-compression.js";
|
|
import { chatWebhookBodyParser } from "./middleware/chat-webhook-body.js";
|
|
import { createChatWebhookDiagnostics } from "./services/chat-webhook-diagnostics.js";
|
|
|
|
type UiMode = "none" | "static" | "vite-dev";
|
|
const FEEDBACK_EXPORT_FLUSH_INTERVAL_MS = 5_000;
|
|
const CHAT_PUBLICATION_FLUSH_INTERVAL_MS = 1_000;
|
|
const VITE_DEV_ASSET_PREFIXES = [
|
|
"/@fs/",
|
|
"/@id/",
|
|
"/@react-refresh",
|
|
"/@vite/",
|
|
"/assets/",
|
|
"/node_modules/",
|
|
"/src/",
|
|
];
|
|
const VITE_DEV_STATIC_PATHS = new Set([
|
|
"/apple-touch-icon.png",
|
|
"/favicon-16x16.png",
|
|
"/favicon-32x32.png",
|
|
"/favicon.ico",
|
|
"/favicon.svg",
|
|
"/site.webmanifest",
|
|
"/sw.js",
|
|
]);
|
|
|
|
export function isDatabaseConnectionUnavailableError(err: unknown): boolean {
|
|
const error = err as { code?: unknown; message?: unknown; cause?: unknown };
|
|
if (error?.code === "ECONNREFUSED") return true;
|
|
return Boolean(
|
|
error?.cause && isDatabaseConnectionUnavailableError(error.cause),
|
|
);
|
|
}
|
|
|
|
export function resolveViteHmrPort(serverPort: number): number {
|
|
return derivePaperclipViteHmrPort(serverPort);
|
|
}
|
|
|
|
export function resolveViteHmrHost(bindHost: string): string | undefined {
|
|
const normalized = bindHost.trim().toLowerCase();
|
|
if (
|
|
normalized === "0.0.0.0" ||
|
|
normalized === "::" ||
|
|
normalized === "127.0.0.1" ||
|
|
normalized === "::1" ||
|
|
normalized === "localhost"
|
|
)
|
|
return undefined;
|
|
return bindHost;
|
|
}
|
|
|
|
export function resolveViteHmrProtocol(
|
|
value: string | undefined,
|
|
): "ws" | "wss" | undefined {
|
|
if (!value) return undefined;
|
|
if (value === "ws" || value === "wss") return value;
|
|
throw new Error("PAPERCLIP_VITE_HMR_PROTOCOL must be ws or wss");
|
|
}
|
|
|
|
export function listenViteHmrServer(
|
|
server: HttpServer,
|
|
port: number,
|
|
bindHost: string,
|
|
): Promise<void> {
|
|
return new Promise((resolve, reject) => {
|
|
const onError = (error: Error) => {
|
|
server.off("listening", onListening);
|
|
reject(error);
|
|
};
|
|
const onListening = () => {
|
|
server.off("error", onError);
|
|
resolve();
|
|
};
|
|
server.once("error", onError);
|
|
server.once("listening", onListening);
|
|
server.listen(port, bindHost);
|
|
});
|
|
}
|
|
|
|
export function shouldServeViteDevHtml(req: ExpressRequest): boolean {
|
|
const pathname = req.path;
|
|
if (VITE_DEV_STATIC_PATHS.has(pathname)) return false;
|
|
if (VITE_DEV_ASSET_PREFIXES.some((prefix) => pathname.startsWith(prefix)))
|
|
return false;
|
|
return req.accepts(["html"]) === "html";
|
|
}
|
|
|
|
export function shouldEnablePrivateHostnameGuard(opts: {
|
|
deploymentMode: DeploymentMode;
|
|
deploymentExposure: DeploymentExposure;
|
|
}): boolean {
|
|
return (
|
|
opts.deploymentExposure === "private" &&
|
|
(opts.deploymentMode === "local_trusted" ||
|
|
opts.deploymentMode === "authenticated")
|
|
);
|
|
}
|
|
|
|
type ChatReconciliationLane =
|
|
| "provider runtimes"
|
|
| "deliveries"
|
|
| "GitHub webhook recovery"
|
|
| "run milestones"
|
|
| "publications"
|
|
| "Slack file receipts"
|
|
| "Slack session status";
|
|
|
|
/**
|
|
* Provider recovery can wait on slow external I/O. Keep each existing durable
|
|
* lane single-flight without making an optional provider effect suppress the
|
|
* next publication sweep for every endpoint.
|
|
*/
|
|
export function createChatReconciliationCoordinator(input: {
|
|
reconcileProviderRuntimes: () => Promise<unknown>;
|
|
processPendingDeliveries: () => Promise<unknown>;
|
|
processFailedGitHubWebhookDeliveries?: () => Promise<unknown>;
|
|
projectRunMilestones: () => Promise<number>;
|
|
flushPublications: () => Promise<unknown>;
|
|
processPendingSlackFileUploadReceipts?: () => Promise<unknown>;
|
|
processPendingSlackSessionSyncs?: () => Promise<unknown>;
|
|
onError: (lane: ChatReconciliationLane, error: unknown) => void;
|
|
}) {
|
|
let stopped = false;
|
|
const inFlight = new Map<ChatReconciliationLane, Promise<void>>();
|
|
const publicationReconciliation = createCoalescedAsyncTrigger({
|
|
run: input.flushPublications,
|
|
onError: (error) => input.onError("publications", error),
|
|
});
|
|
const milestoneReconciliation = createCoalescedAsyncTrigger({
|
|
run: async () => {
|
|
const inserted = await input.projectRunMilestones();
|
|
// Existing final/question publications never wait on this optional
|
|
// projection. Newly committed milestones get a bounded dispatch wake;
|
|
// an empty/contended pass does not create a self-sustaining loop.
|
|
if (inserted > 0) publicationReconciliation.notify();
|
|
},
|
|
onError: (error) => input.onError("run milestones", error),
|
|
});
|
|
const start = (
|
|
lane: ChatReconciliationLane,
|
|
task: () => Promise<unknown>,
|
|
) => {
|
|
if (stopped || inFlight.has(lane)) return;
|
|
const pending = Promise.resolve()
|
|
.then(task)
|
|
.then(() => undefined)
|
|
.catch((error) => input.onError(lane, error))
|
|
.finally(() => {
|
|
if (inFlight.get(lane) === pending) inFlight.delete(lane);
|
|
});
|
|
inFlight.set(lane, pending);
|
|
};
|
|
return {
|
|
reconcile() {
|
|
if (stopped) return;
|
|
start("provider runtimes", input.reconcileProviderRuntimes);
|
|
start("deliveries", input.processPendingDeliveries);
|
|
if (input.processFailedGitHubWebhookDeliveries) {
|
|
start(
|
|
"GitHub webhook recovery",
|
|
input.processFailedGitHubWebhookDeliveries,
|
|
);
|
|
}
|
|
milestoneReconciliation.poll();
|
|
publicationReconciliation.poll();
|
|
if (input.processPendingSlackFileUploadReceipts) start("Slack file receipts", input.processPendingSlackFileUploadReceipts);
|
|
if (input.processPendingSlackSessionSyncs) start("Slack session status", input.processPendingSlackSessionSyncs);
|
|
},
|
|
notifyPublications() {
|
|
milestoneReconciliation.notify();
|
|
publicationReconciliation.notify();
|
|
},
|
|
stop() {
|
|
stopped = true;
|
|
milestoneReconciliation.stop();
|
|
publicationReconciliation.stop();
|
|
},
|
|
async drain() {
|
|
await Promise.allSettled([
|
|
...inFlight.values(),
|
|
milestoneReconciliation.drain(),
|
|
]);
|
|
// Projecting the final batch can notify dispatch after an earlier drain
|
|
// would have returned. Join dispatch only after its producer has drained.
|
|
await publicationReconciliation.drain();
|
|
},
|
|
};
|
|
}
|
|
|
|
export function createManagedBundledPluginWorkerRecovery(input: {
|
|
managedBundledPluginKeys: readonly string[];
|
|
workerManager: Pick<
|
|
PluginWorkerManager,
|
|
"getWorker" | "isRunning" | "stopWorker"
|
|
>;
|
|
getLoader: () => Pick<PluginLoader, "loadSingle"> | null;
|
|
}): (plugin: { id: string; pluginKey: string }) => Promise<boolean> {
|
|
const recoverablePluginKeys = new Set(input.managedBundledPluginKeys);
|
|
const inFlightStarts = new Map<string, Promise<boolean>>();
|
|
|
|
// A failed attempt can leave behind the dead handle it registered (e.g. the
|
|
// worker process died during initialize, which kills the process without
|
|
// scheduling a restart). No pre-existing handle survives to a recovery
|
|
// attempt — recovery only starts when getWorker() was empty — so discarding
|
|
// the dead handle lets a later capability request retry instead of being
|
|
// blocked by the handle-presence gate until the process restarts. Handles
|
|
// in starting/running/backoff states belong to the worker manager's own
|
|
// lifecycle and are left alone.
|
|
const discardDeadRecoveryHandle = async (plugin: {
|
|
id: string;
|
|
pluginKey: string;
|
|
}) => {
|
|
const handle = input.workerManager.getWorker(plugin.id);
|
|
if (!handle || (handle.status !== "crashed" && handle.status !== "stopped"))
|
|
return;
|
|
try {
|
|
await input.workerManager.stopWorker(plugin.id);
|
|
} catch (err) {
|
|
logger.warn(
|
|
{
|
|
pluginId: plugin.id,
|
|
pluginKey: plugin.pluginKey,
|
|
err: err instanceof Error ? err.message : String(err),
|
|
},
|
|
"failed to discard dead plugin worker handle after recovery failure",
|
|
);
|
|
}
|
|
};
|
|
|
|
return async (plugin) => {
|
|
if (!recoverablePluginKeys.has(plugin.pluginKey)) return false;
|
|
|
|
const inFlight = inFlightStarts.get(plugin.id);
|
|
if (inFlight) return inFlight;
|
|
|
|
const startPromise = (async () => {
|
|
if (input.workerManager.getWorker(plugin.id)) {
|
|
return input.workerManager.isRunning(plugin.id);
|
|
}
|
|
|
|
const loader = input.getLoader();
|
|
if (!loader) return false;
|
|
|
|
try {
|
|
const result = await loader.loadSingle(plugin.id, {
|
|
markErrorOnFailure: false,
|
|
});
|
|
if (
|
|
result.success === true ||
|
|
input.workerManager.isRunning(plugin.id)
|
|
) {
|
|
return true;
|
|
}
|
|
await discardDeadRecoveryHandle(plugin);
|
|
return false;
|
|
} catch (err) {
|
|
logger.warn(
|
|
{
|
|
pluginId: plugin.id,
|
|
pluginKey: plugin.pluginKey,
|
|
err: err instanceof Error ? err.message : String(err),
|
|
},
|
|
"managed bundled plugin lazy worker recovery failed",
|
|
);
|
|
await discardDeadRecoveryHandle(plugin);
|
|
throw err;
|
|
}
|
|
})();
|
|
|
|
inFlightStarts.set(plugin.id, startPromise);
|
|
try {
|
|
return await startPromise;
|
|
} finally {
|
|
if (inFlightStarts.get(plugin.id) === startPromise) {
|
|
inFlightStarts.delete(plugin.id);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
export async function createApp(
|
|
db: Db,
|
|
opts: {
|
|
cloudWarmStandby?: CloudWarmStandby;
|
|
uiMode: UiMode;
|
|
serverPort: number;
|
|
storageService: StorageService;
|
|
feedbackExportService?: {
|
|
hasPendingFeedbackTraces(): Promise<boolean>;
|
|
flushPendingFeedbackTraces(input?: {
|
|
companyId?: string;
|
|
traceId?: string;
|
|
limit?: number;
|
|
now?: Date;
|
|
signal?: AbortSignal;
|
|
}): Promise<unknown>;
|
|
};
|
|
databaseBackupService?: InstanceDatabaseBackupService;
|
|
prepareIdleDatabaseBackup?: () => Promise<boolean>;
|
|
databaseBackupHealth?: InspectDatabaseBackupHealthOptions;
|
|
deploymentMode: DeploymentMode;
|
|
deploymentExposure: DeploymentExposure;
|
|
allowedHostnames: string[];
|
|
bindHost: string;
|
|
authPublicBaseUrl?: string;
|
|
chatWebhookPublicBaseUrl?: string;
|
|
authReady: boolean;
|
|
companyDeletionEnabled: boolean;
|
|
announcements?: { enabled: boolean; feedUrl: string };
|
|
instanceId?: string;
|
|
hostVersion?: string;
|
|
localPluginDir?: string;
|
|
pluginMigrationDb?: Db;
|
|
pluginWorkerManager?: PluginWorkerManager;
|
|
decisionServiceOptions: DecisionServiceOptions;
|
|
betterAuthHandler?: express.RequestHandler;
|
|
resolveSession?: (
|
|
req: ExpressRequest,
|
|
) => Promise<BetterAuthSessionResult | null>;
|
|
/**
|
|
* `plugins.autoInstall` from the managed config (PAPERCLIP_MANAGED_CONFIG).
|
|
* `null`/absent ⇒ self-hosted: only the built-in kubernetes bundle is
|
|
* ensured, exactly as before. A managed list is resolved against the
|
|
* bundled catalog fail-to-start (see services/bundled-plugins.ts).
|
|
*/
|
|
managedPluginAutoInstall?: readonly string[] | null;
|
|
/** Test override for the bundled plugin catalog root. */
|
|
bundledPluginCatalogRoot?: string;
|
|
},
|
|
) {
|
|
const app = express();
|
|
app.use(idleAdmissionMiddleware);
|
|
const staticUi = express.Router();
|
|
app.locals.paperclipDb = db;
|
|
const isWarmStandby = opts.cloudWarmStandby ?? (() => false);
|
|
const health = healthRoutes(db, {
|
|
deploymentMode: opts.deploymentMode,
|
|
deploymentExposure: opts.deploymentExposure,
|
|
authReady: opts.authReady,
|
|
companyDeletionEnabled: opts.companyDeletionEnabled,
|
|
databaseBackupHealth: opts.databaseBackupHealth,
|
|
isWarmStandby,
|
|
});
|
|
const captureRawBody = (
|
|
req: express.Request,
|
|
_res: express.Response,
|
|
buf: Buffer,
|
|
) => {
|
|
(req as unknown as { rawBody: Buffer }).rawBody = buf;
|
|
};
|
|
|
|
// Respect the operator's `TRUST_PROXY` env var (see middleware/trust-proxy.ts).
|
|
// Default is unset → Express trusts nothing, which is the only safe choice
|
|
// when the server may be reachable without a known reverse proxy in front.
|
|
applyTrustProxy(app, parseTrustProxyEnv(process.env.TRUST_PROXY));
|
|
|
|
app.use(
|
|
COMPANY_IMPORT_API_PATH,
|
|
express.json({
|
|
limit: PORTABLE_JSON_BODY_LIMIT,
|
|
verify: captureRawBody,
|
|
}),
|
|
);
|
|
// Chat providers sign the exact request bytes. Capture every webhook media
|
|
// type before the global JSON parser so JSON events and form-encoded action
|
|
// callbacks are verified against the provider's original body.
|
|
app.use(
|
|
"/api/chat-webhooks",
|
|
createChatWebhookDiagnostics(),
|
|
chatWebhookBodyParser,
|
|
);
|
|
const jsonBodyParser = express.json({ limit: DEFAULT_JSON_BODY_LIMIT, verify: captureRawBody });
|
|
// File tickets authenticate before parsing bytes; JSON attachments must remain bytes too.
|
|
app.use((req, res, next) => ["/mcp/files/upload", "/mcp/runner/files/upload"].includes(req.path) ? next() : jsonBodyParser(req, res, next));
|
|
app.use("/api", apiCompression());
|
|
app.use(httpLogger);
|
|
const privateHostnameGateEnabled = shouldEnablePrivateHostnameGuard({
|
|
deploymentMode: opts.deploymentMode,
|
|
deploymentExposure: opts.deploymentExposure,
|
|
});
|
|
const privateHostnameAllowSet = resolvePrivateHostnameAllowSet({
|
|
allowedHostnames: opts.allowedHostnames,
|
|
bindHost: opts.bindHost,
|
|
});
|
|
app.use(
|
|
privateHostnameGuard({
|
|
enabled: privateHostnameGateEnabled,
|
|
allowedHostnames: opts.allowedHostnames,
|
|
bindHost: opts.bindHost,
|
|
}),
|
|
);
|
|
let mcpConfig: ReturnType<typeof publicMcpConfig> = null;
|
|
try { mcpConfig = publicMcpConfig(process.env, opts.authPublicBaseUrl); }
|
|
catch { logger.warn("Assistant connections require an HTTPS public URL (HTTP loopback is allowed for development)."); }
|
|
const publicMcpOAuth = mcpConfig ? createPublicMcpOAuth(db, mcpConfig) : null;
|
|
const publicMcpIngress = Router();
|
|
|
|
app.use(cloudRuntimeIdentityMiddleware(db));
|
|
// Routine probes stop before session/actor resolution, even after claim.
|
|
// Keep hostname validation and the signed-bootstrap endpoint guard above.
|
|
app.use("/api/liveness", livenessRoutes());
|
|
// A signed claim above commits identity before any normal request can seed
|
|
// company data. Unclaimed probes bypass session resolution as well as SQL.
|
|
app.use(cloudWarmStandbyMiddleware(isWarmStandby, health, staticUi));
|
|
app.use("/api/customer-success/v1", customerSuccessRoutes(db, opts.storageService));
|
|
app.use(museTransportRoutes(db, opts.authPublicBaseUrl));
|
|
app.use(publicMcpIngress);
|
|
// Connection-intent tools carry their own short-lived, run-bound bearer and
|
|
// must be reachable by remote adapters that intentionally do not receive an
|
|
// agent API key. Every request revalidates the active heartbeat row.
|
|
app.use(runtimeConnectionIntentRoutes(db));
|
|
const hostServicesDisposers = new Map<string, () => void>();
|
|
const workerManager = opts.pluginWorkerManager ?? createPluginWorkerManager();
|
|
let lifecyclePluginsReady = false;
|
|
const agentLifecycle = startAgentLifecycle(db, createLifecycleDriver(db, workerManager), () => lifecyclePluginsReady && !isWarmStandby() && !isIdleTaskDrainActive());
|
|
const connectionIntentHeartbeat = heartbeatService(db, {
|
|
pluginWorkerManager: workerManager,
|
|
});
|
|
const chatChannels = chatChannelService(db, {
|
|
allowLocalVoiceBoard: opts.deploymentMode === "local_trusted",
|
|
deferWebhookProcessing: true,
|
|
heartbeat: connectionIntentHeartbeat,
|
|
publicBaseUrl: opts.authPublicBaseUrl,
|
|
githubWizardOrigin: opts.deploymentMode === "local_trusted"
|
|
&& ["127.0.0.1", "localhost", "::1"].includes(opts.bindHost ?? "")
|
|
&& Number.isInteger(opts.serverPort) && opts.serverPort! > 0
|
|
? `http://${opts.bindHost === "::1" ? "[::1]" : opts.bindHost}:${opts.serverPort}` : null,
|
|
webhookPublicBaseUrl: opts.chatWebhookPublicBaseUrl,
|
|
resolveNativeQuestion: (interaction) =>
|
|
deliverNativeQuestionResponse(db, interaction),
|
|
storage: opts.storageService,
|
|
});
|
|
// Voice capabilities are verified by the signed callback route, not by
|
|
// board/agent bearer authentication. Mount before actorMiddleware so its
|
|
// per-session Bearer cannot be mistaken for an agent API key.
|
|
app.use(voiceWebhookRoutes(db, chatChannels.voice));
|
|
app.use(
|
|
actorMiddleware(db, {
|
|
deploymentMode: opts.deploymentMode,
|
|
resolveSession: opts.resolveSession,
|
|
}),
|
|
);
|
|
// After the actor middleware on purpose: a valid Cloud control assertion
|
|
// REPLACES whatever actor the request otherwise resolved to, and only on
|
|
// the one endpoint it authorizes (see the middleware for the contract).
|
|
app.use(cloudControlMiddleware());
|
|
app.use(skillAccessRequestContext);
|
|
app.use("/api/auth", authRoutes(db));
|
|
if (opts.betterAuthHandler) {
|
|
app.all("/api/auth/{*authPath}", opts.betterAuthHandler);
|
|
}
|
|
app.use(llmRoutes(db));
|
|
|
|
// Provider-authenticated ingress is intentionally outside the board
|
|
// mutation guard. The Chat SDK adapter verifies the provider signature
|
|
// before Paperclip persists or acts on any event.
|
|
const emailChannels = emailChannelService(db, {
|
|
isReconciliationEnabled: () => !isWarmStandby(),
|
|
isBackgroundWorkEnabled: () => !isWarmStandby() && !isIdleTaskDrainActive(),
|
|
heartbeat: connectionIntentHeartbeat,
|
|
storage: opts.storageService,
|
|
publicBaseUrl: opts.chatWebhookPublicBaseUrl ?? opts.authPublicBaseUrl,
|
|
});
|
|
app.use(emailWebhookRoutes(emailChannels));
|
|
app.locals.fastResponses = fastResponseService(db, {
|
|
authorizeExternal: async (tx, request) => {
|
|
const [endpoint] = await tx.select({ provider: chatEndpoints.provider }).from(chatEndpoints).where(eq(chatEndpoints.id, request.endpointId!));
|
|
return endpoint?.provider === "agentmail" ? emailChannels.authorizeFastResponse(tx, request) : chatChannels.authorizeFastResponse(tx, request);
|
|
},
|
|
publishExternal: async (tx, request, commentId, text) => {
|
|
const [endpoint] = await tx.select({ provider: chatEndpoints.provider }).from(chatEndpoints).where(eq(chatEndpoints.id, request.endpointId!));
|
|
if (endpoint?.provider !== "agentmail") return false;
|
|
await emailChannels.publishFastResponse(tx, request, commentId, text);
|
|
return true;
|
|
},
|
|
budgetHooks: { cancelWorkForScope: connectionIntentHeartbeat.cancelBudgetScopeWork },
|
|
});
|
|
app.use(chatWebhookRoutes(chatChannels));
|
|
// The instance validates single-use registration state and its trusted
|
|
// current origin. These exact callback routes are the public setup returns.
|
|
app.get("/api/chat-github/manifest/callback", async (req, res) => {
|
|
res.set("Cache-Control", "no-store");
|
|
res.set("Referrer-Policy", "no-referrer");
|
|
const redirect = await chatChannels.githubWizard.directCallback(String(req.query.state ?? ""), String(req.query.code ?? ""), req.actor);
|
|
res.redirect(303, redirect);
|
|
});
|
|
app.get("/api/chat-github/cloud/callback", async (req, res) => {
|
|
res.set("Cache-Control", "no-store"); res.set("Referrer-Policy", "no-referrer");
|
|
res.redirect(303, await chatChannels.githubWizard.cloudCallback(String(req.query.state ?? ""), String(req.query.registration ?? ""), typeof req.query.claim === "string" ? req.query.claim : undefined, req.actor));
|
|
});
|
|
app.get("/api/chat-github/identity/callback", async (req, res) => {
|
|
res.set("Cache-Control", "no-store"); res.set("Referrer-Policy", "no-referrer");
|
|
res.redirect(303, await chatChannels.githubWizard.identityCallback(String(req.query.state ?? ""), String(req.query.code ?? ""), req.actor));
|
|
});
|
|
const managedAutoInstallKeys = opts.managedPluginAutoInstall ?? null;
|
|
const bundledCatalogRoot =
|
|
opts.bundledPluginCatalogRoot ?? resolveBundledCatalogRoot(process.env);
|
|
const distributionPlugins = readDistributionPluginCatalog(bundledCatalogRoot, BUNDLED_PLUGIN_CATALOG);
|
|
const bundledPluginInstalls = resolveBundledPluginInstalls(
|
|
managedAutoInstallKeys ?? SELF_HOSTED_AUTO_INSTALL_KEYS,
|
|
{
|
|
catalogRoot: bundledCatalogRoot,
|
|
env: process.env,
|
|
enforceCatalogRoot: managedAutoInstallKeys !== null,
|
|
distributionPlugins,
|
|
},
|
|
);
|
|
const managedBundledPluginKeys =
|
|
managedAutoInstallKeys !== null
|
|
? bundledPluginInstalls.map((install) => install.pluginKey)
|
|
: [];
|
|
let runtimePluginLoader: Pick<PluginLoader, "loadSingle"> | null = null;
|
|
// A sibling process can install a managed bundled plugin while this process
|
|
// skips the mid-install row, then finish the row after this process's
|
|
// loadAll() pass. The capabilities route may recover only those managed
|
|
// bundles by starting their ready-but-unstarted worker lazily.
|
|
const recoverManagedBundledPluginWorker =
|
|
managedAutoInstallKeys !== null
|
|
? createManagedBundledPluginWorkerRecovery({
|
|
managedBundledPluginKeys,
|
|
workerManager,
|
|
getLoader: () => runtimePluginLoader,
|
|
})
|
|
: undefined;
|
|
|
|
// Mount API routes
|
|
const api = Router();
|
|
const agentAvatars = agentAvatarRoutes();
|
|
api.use(agentAvatars.router);
|
|
api.use(boardMutationGuard());
|
|
api.use("/health", health);
|
|
api.use(openApiRoutes());
|
|
api.use("/cloud", cloudRoutes());
|
|
api.use("/companies", companyRoutes(db, opts.storageService));
|
|
api.use(llmRoutes(db));
|
|
api.use(folderRoutes(db));
|
|
api.use(companySkillRoutes(db));
|
|
api.use(companySkillPolicyRoutes(db));
|
|
api.use(inboxAgentPolicyRoutes(db));
|
|
api.use(agentCommentaryRoutes(db));
|
|
api.use(builtInAgentRoutes(db));
|
|
api.use(summarySlotRoutes(db));
|
|
api.use(statusCardRoutes(db));
|
|
api.use(teamsCatalogRoutes(db));
|
|
// The setup-token login session service. The router builds it and hands it
|
|
// back through the callback below, so the shutdown hook can cancel every live
|
|
// session (SR-4).
|
|
let setupTokenLoginService: SetupTokenSessionService | null = null;
|
|
// The dedicated proxy IP or CIDR allowlist for the confidential setup-token
|
|
// login responses (SR-7). The global `TRUST_PROXY` setting does not satisfy
|
|
// the guard; an operator sets this allowlist to the real TLS-terminating
|
|
// proxy addresses. An empty value keeps the confidential responses on direct
|
|
// TLS (or a `local_trusted` loopback peer) only.
|
|
const setupTokenLoginProxyAllowlist = (
|
|
process.env.CLAUDE_LOGIN_TRUSTED_PROXIES ?? ""
|
|
)
|
|
.split(",")
|
|
.map((entry) => entry.trim())
|
|
.filter((entry) => entry.length > 0);
|
|
// The explicit operator declaration that a platform edge terminates TLS for
|
|
// every client request (SR-7). This complements the allowlist for managed
|
|
// platforms (Railway, Render, Fly, and the like) where the app socket is
|
|
// always plain HTTP and the edge-proxy peer addresses are not stable or
|
|
// documented, so `CLAUDE_LOGIN_TRUSTED_PROXIES` cannot express them. It is a
|
|
// dedicated, single-purpose setting; the guard still never reads the global
|
|
// `TRUST_PROXY` value.
|
|
const setupTokenLoginEdgeTlsTerminated = /^(1|true|yes|on)$/i.test(
|
|
(process.env.CLAUDE_LOGIN_EDGE_TLS_TERMINATED ?? "").trim(),
|
|
);
|
|
// Bind the production setup-token login transport. It carries the live lease
|
|
// manager, the login-process factory over the sandbox pseudo-terminal, and the
|
|
// durable cleanup store. The factory passes only the fixed command
|
|
// `CLAUDE_SETUP_TOKEN_COMMAND`; it never reads a command from a
|
|
// route, a request body, or an adapter configuration. The durable store and the
|
|
// startup reaper are live now, so a restart reaps a leftover lease.
|
|
//
|
|
// The live sandbox pseudo-terminal opener binds inside the sandbox provider
|
|
// worker, so the server process does not hold the raw sandbox process. The
|
|
// opener drives the worker through the plugin worker manager route gate.
|
|
// The manager mints a host-owned route identifier, permits one
|
|
// active credential pseudo-terminal per worker, binds the worker session
|
|
// identifier one time for output only, and terminalizes the route on every open
|
|
// failure path. With the opener supplied, the provider acquires a lease and the
|
|
// start route drives a live login instead of the fixed 503.
|
|
const setupTokenLoginTransport = buildSetupTokenLoginTransport({
|
|
sandbox: createProductionSetupTokenSandboxProvider({
|
|
environments: environmentService(db),
|
|
environmentRuntime: environmentRuntimeService(db, {
|
|
pluginWorkerManager: workerManager,
|
|
}),
|
|
openLivePtySession: createWorkerBoundLoginPtyOpener({
|
|
workerManager,
|
|
environments: environmentService(db),
|
|
log: (line) => logger.info(line),
|
|
}),
|
|
log: (line) => logger.info(line),
|
|
}),
|
|
store: createProductionSetupTokenCleanupStore(db),
|
|
// Bind the atomic credential-claim writer, so a completed login transitions
|
|
// the durable row to `stored` and stores the minted token in one control-plane
|
|
// transaction. The writer reads the company and the owner only from the
|
|
// immutable session scope. The confirm-replacement flow owns rotation. Without
|
|
// this writer the router falls back to the deferred, fail-closed 503 and never
|
|
// stores the token.
|
|
completeCredential: createSetupTokenSecretWriter({ db }),
|
|
// Forward the login runner diagnostic lines to the server logger. The
|
|
// runner is the sole producer, and every line is a fixed, non-secret
|
|
// literal. Without this sink the diagnostics fall back to a no-op in
|
|
// production, so a failed login leaves no log trail.
|
|
log: (line) => logger.info(line),
|
|
});
|
|
api.use(
|
|
agentRoutes(db, {
|
|
chatRunRetries: chatChannels,
|
|
pluginWorkerManager: workerManager,
|
|
deploymentMode: opts.deploymentMode,
|
|
confidentialProxyAllowlist: setupTokenLoginProxyAllowlist,
|
|
confidentialEdgeTlsTerminated: setupTokenLoginEdgeTlsTerminated,
|
|
setupTokenLogin: setupTokenLoginTransport,
|
|
onSetupTokenLoginService: (service) => {
|
|
// Capture the service, so the graceful-shutdown hook cancels every live
|
|
// session and releases each lease. The standalone scheduled reaper owns
|
|
// the startup and interval lease cleanup now (SR-4).
|
|
setupTokenLoginService = service;
|
|
},
|
|
}),
|
|
);
|
|
api.use(assetRoutes(db, opts.storageService));
|
|
api.use(agentProfileAvatarRoutes(db, opts.storageService));
|
|
api.use(projectToolRoutes(db));
|
|
api.use(taskWorkspaceRoutes(db));
|
|
api.use(projectRoutes(db));
|
|
api.use(caseRoutes(db, opts.storageService));
|
|
api.use(caseHandoffRoutes(db));
|
|
api.use(workflowRoutes(db));
|
|
api.use(issueTreeControlRoutes(db, { pluginWorkerManager: workerManager }));
|
|
api.use(fileResourceRoutes(db));
|
|
api.use(routineRoutes(db, { pluginWorkerManager: workerManager }));
|
|
api.use(
|
|
environmentRoutes(db, {
|
|
pluginWorkerManager: workerManager,
|
|
recoverMissingPluginWorker: recoverManagedBundledPluginWorker
|
|
? {
|
|
pluginKeys: managedBundledPluginKeys,
|
|
startWorker: recoverManagedBundledPluginWorker,
|
|
}
|
|
: undefined,
|
|
}),
|
|
);
|
|
api.use(executionWorkspaceRoutes(db, { pluginWorkerManager: workerManager }));
|
|
api.use(emailRoutes(db, emailChannels));
|
|
api.use(goalRoutes(db));
|
|
api.use(onboardingSeedRoutes(db));
|
|
api.use(boardChatRoutes(db, { deploymentMode: opts.deploymentMode }));
|
|
api.use(voiceSessionRoutes(db, chatChannels.voice));
|
|
api.use(approvalRoutes(db, { pluginWorkerManager: workerManager }));
|
|
api.use(secretRoutes(db));
|
|
api.use(managedAgentProfileRoutes(db));
|
|
api.use(remoteAgentProfileRoutes(db));
|
|
api.use(
|
|
chatChannelRoutes(db, {
|
|
heartbeat: connectionIntentHeartbeat,
|
|
publicBaseUrl: opts.authPublicBaseUrl,
|
|
storage: opts.storageService,
|
|
service: chatChannels,
|
|
}),
|
|
);
|
|
const trustedLocalStdioRuntimeHost =
|
|
process.env.PAPERCLIP_TRUSTED_MCP_RUNTIME_HOST ??
|
|
process.env.PAPERCLIP_TOOL_RUNTIME_TRUSTED_HOST ??
|
|
null;
|
|
api.use(costRoutes(db, { pluginWorkerManager: workerManager }));
|
|
api.use(activityRoutes(db));
|
|
api.use(dashboardRoutes(db));
|
|
api.use(attentionRoutes(db));
|
|
api.use(decisionTrainingRoutes(db));
|
|
api.use(decisionRoutes(db, opts.decisionServiceOptions));
|
|
api.use(decisionQueueRoutes(db));
|
|
api.use(userProfileRoutes(db));
|
|
api.use(sidebarBadgeRoutes(db));
|
|
api.use(sidebarPreferenceRoutes(db));
|
|
api.use(announcementRoutes(db, { ...opts.announcements, version: opts.hostVersion ?? serverVersion }));
|
|
api.use(resourceMembershipRoutes(db));
|
|
api.use(primaryAgentRoutes(db));
|
|
api.use(inboxDismissalRoutes(db));
|
|
api.use(instanceSettingsRoutes(db, workerManager, opts.prepareIdleDatabaseBackup));
|
|
if (opts.databaseBackupService) {
|
|
api.use(instanceDatabaseBackupRoutes(opts.databaseBackupService));
|
|
}
|
|
const pluginRegistry = pluginRegistryService(db);
|
|
const eventBus = createPluginEventBus();
|
|
setPluginEventBus(eventBus);
|
|
const jobStore = pluginJobStore(db);
|
|
const lifecycle = pluginLifecycleManager(db, { workerManager });
|
|
const scheduler = createPluginJobScheduler({
|
|
isBackgroundWorkEnabled: () => !isWarmStandby() && !isIdleTaskDrainActive(),
|
|
db,
|
|
jobStore,
|
|
workerManager,
|
|
});
|
|
const toolDispatcher = createPluginToolDispatcher({
|
|
workerManager,
|
|
lifecycleManager: lifecycle,
|
|
db,
|
|
});
|
|
const gatewayOAuthAccess = toolAccessService(db, {
|
|
deploymentMode: opts.deploymentMode,
|
|
deploymentExposure: opts.deploymentExposure,
|
|
trustedLocalStdioRuntimeHost,
|
|
});
|
|
const toolActionDeliveries = toolActionDeliveryService(db, heartbeatService(db, { pluginWorkerManager: workerManager }));
|
|
const toolGateway = createToolGatewayService(db, {
|
|
budgetHooks: { cancelWorkForScope: heartbeatService(db, { pluginWorkerManager: workerManager }).cancelBudgetScopeWork },
|
|
onToolActionSettled: (id) => toolActionDeliveries.deliver(id),
|
|
pluginToolDispatcher: toolDispatcher,
|
|
deploymentMode: opts.deploymentMode,
|
|
deploymentExposure: opts.deploymentExposure,
|
|
trustedLocalStdioRuntimeHost,
|
|
oauthGrantRefresher: (input) =>
|
|
gatewayOAuthAccess.refreshOAuthGrantCredentials(input),
|
|
});
|
|
// Issue routes are intentionally mounted after the gateway is constructed because
|
|
// issue approval endpoints delegate to it. The intervening routers use distinct
|
|
// route prefixes, so this dependency does not change issue-route precedence.
|
|
api.use(issueRoutes(db, opts.storageService, {
|
|
chatRunRetries: chatChannels,
|
|
pluginWorkerManager: workerManager,
|
|
approveToolActionRequest: (input) => toolGateway.approveActionRequest(input),
|
|
declineToolActionRequest: (input) => toolGateway.declineActionRequest(input),
|
|
}));
|
|
api.use(slackToolRoutes(db, opts.authPublicBaseUrl));
|
|
app.locals.toolGateway = toolGateway;
|
|
registerAssignedMcpGateway(db, toolGateway);
|
|
app.locals.toolActionDeliveries = toolActionDeliveries;
|
|
app.use(mcpGatewayProtocolRoutes(toolGateway));
|
|
api.use(decisionModelRoutes(db));
|
|
api.use(agentObservabilityRoutes(db, { deploymentMode: opts.deploymentMode, deploymentExposure: opts.deploymentExposure }));
|
|
api.use(fastResponseRoutes(db));
|
|
api.use(promptInjectionPreventionRoutes(db));
|
|
api.use(aiConnectionRoutes(db, { deploymentMode: opts.deploymentMode, deploymentExposure: opts.deploymentExposure, trustedLocalStdioRuntimeHost, pluginWorkerManager: workerManager }));
|
|
api.use(
|
|
toolAccessRoutes(db, {
|
|
deploymentMode: opts.deploymentMode,
|
|
deploymentExposure: opts.deploymentExposure,
|
|
authPublicBaseUrl: opts.authPublicBaseUrl,
|
|
trustedLocalStdioRuntimeHost,
|
|
toolGateway,
|
|
connectionIntentHeartbeat,
|
|
}),
|
|
);
|
|
api.use(connectionIntentBoardRoutes(db, connectionIntentHeartbeat));
|
|
api.use(
|
|
smokeLabRoutes(db, {
|
|
deploymentMode: opts.deploymentMode,
|
|
deploymentExposure: opts.deploymentExposure,
|
|
}),
|
|
);
|
|
const jobCoordinator = createPluginJobCoordinator({
|
|
db,
|
|
lifecycle,
|
|
scheduler,
|
|
jobStore,
|
|
});
|
|
const hostServiceCleanup = createPluginHostServiceCleanup(
|
|
lifecycle,
|
|
hostServicesDisposers,
|
|
);
|
|
let viteHtmlRenderer: ReturnType<typeof createCachedViteHtmlRenderer> | null =
|
|
null;
|
|
let viteDevServer: { close(): Promise<void> } | null = null;
|
|
let viteHmrServer: HttpServer | null = null;
|
|
const loader = pluginLoader(
|
|
db,
|
|
{
|
|
localPluginDir: opts.localPluginDir ?? DEFAULT_LOCAL_PLUGIN_DIR,
|
|
migrationDb: opts.pluginMigrationDb,
|
|
assertPackageActivation: distributionPluginActivationGuard(bundledCatalogRoot, distributionPlugins, managedAutoInstallKeys),
|
|
},
|
|
{
|
|
workerManager,
|
|
eventBus,
|
|
jobScheduler: scheduler,
|
|
jobStore,
|
|
toolDispatcher,
|
|
lifecycleManager: lifecycle,
|
|
instanceInfo: {
|
|
instanceId: opts.instanceId ?? "default",
|
|
hostVersion: opts.hostVersion ?? serverVersion,
|
|
deploymentMode: opts.deploymentMode,
|
|
deploymentExposure: opts.deploymentExposure,
|
|
},
|
|
buildHostHandlers: (pluginId, manifest) => {
|
|
const notifyWorker = (method: string, params: unknown) => {
|
|
const handle = workerManager.getWorker(pluginId);
|
|
if (handle) handle.notify(method, params);
|
|
};
|
|
const services = buildHostServices(
|
|
db,
|
|
pluginId,
|
|
manifest.id,
|
|
eventBus,
|
|
notifyWorker,
|
|
{
|
|
pluginWorkerManager: workerManager,
|
|
manifest,
|
|
},
|
|
);
|
|
hostServicesDisposers.set(pluginId, () => services.dispose());
|
|
return createHostClientHandlers({
|
|
pluginId,
|
|
capabilities: manifest.capabilities,
|
|
services,
|
|
});
|
|
},
|
|
},
|
|
);
|
|
runtimePluginLoader = loader;
|
|
const browserUse = browserUseService(db, undefined,
|
|
{ cancelWorkForScope: heartbeatService(db, { pluginWorkerManager: workerManager }).cancelBudgetScopeWork },
|
|
(session, run) => toolGateway.browserUseSessionAuthorized({ ...session, runId: run.heartbeatRunId, invocationId: run.invocationId }));
|
|
api.use(browserUseRoutes(db, browserUse));
|
|
api.use(toolGatewayRoutes(db, toolGateway));
|
|
api.use(
|
|
pluginRoutes(
|
|
db,
|
|
loader,
|
|
{ scheduler, jobStore },
|
|
{ workerManager },
|
|
{ toolDispatcher },
|
|
{ workerManager },
|
|
{ toolGateway },
|
|
),
|
|
);
|
|
api.use(
|
|
adapterRoutes({
|
|
resolveRunnerTarget: (companyId, environmentId) => resolveAgentRunnerTargetForCompany(db, companyId, environmentId),
|
|
getNativeRunnerEnabled: async () =>
|
|
(await instanceSettingsService(db).getExperimental())
|
|
.enableNativeRunner === true,
|
|
getOpenAiDotEnabled: async () =>
|
|
(await instanceSettingsService(db).getExperimental())
|
|
.enableOpenAiDot === true,
|
|
}),
|
|
);
|
|
api.use(
|
|
accessRoutes(db, {
|
|
deploymentMode: opts.deploymentMode,
|
|
deploymentExposure: opts.deploymentExposure,
|
|
bindHost: opts.bindHost,
|
|
allowedHostnames: opts.allowedHostnames,
|
|
authPublicBaseUrl: opts.authPublicBaseUrl,
|
|
}),
|
|
);
|
|
let publicMcpEvents: PublicMcpEvents | null = null;
|
|
const grokDispatcher = createGrokRoutineDispatcher(db, () => !isWarmStandby() && !isIdleTaskDrainActive());
|
|
let dotMcpEvents: PublicMcpEvents | null = null;
|
|
if (publicMcpOAuth) {
|
|
const dispatch = createMcpApiDispatch(api, app.locals);
|
|
publicMcpEvents = createPublicMcpEvents(db, publicMcpOAuth, dispatch, {
|
|
isBackgroundWorkEnabled: () => !isWarmStandby() && !isIdleTaskDrainActive(),
|
|
});
|
|
const transfers = createPublicMcpTransfers(db, publicMcpOAuth, dispatch, opts.storageService);
|
|
publicMcpIngress.use(transfers.router);
|
|
publicMcpIngress.use(publicMcpIngressRoutes(publicMcpOAuth, createPublicMcpExecutor(db, publicMcpOAuth, dispatch, transfers), publicMcpEvents));
|
|
const dotOAuth = createPublicMcpOAuth(db, { ...publicMcpOAuth.config, resource: publicMcpOAuth.config.origin + "/mcp/runner" });
|
|
dotMcpEvents = createPublicMcpEvents(db, dotOAuth, dispatch, { enableDotRunner: true, isBackgroundWorkEnabled: () => !isWarmStandby() && !isIdleTaskDrainActive() });
|
|
const grokTransfers = createPublicMcpTransfers(db, dotOAuth, dispatch, opts.storageService, { pathPrefix: "/mcp/runner/files",
|
|
agentSession: { authorize: (principal, sessionId, taskId, write, database) => dotRunnerBroker(database ?? db).authorizeFileSession(principal, sessionId, taskId, write) } });
|
|
publicMcpIngress.use(grokTransfers.router);
|
|
publicMcpIngress.use(publicMcpIngressRoutes(dotOAuth, createPublicMcpExecutor(db, dotOAuth, dispatch), dotMcpEvents, createDotRunnerMcpTools(db, connectionIntentHeartbeat, grokTransfers)));
|
|
api.use(publicMcpManagementRoutes(publicMcpOAuth, dotOAuth));
|
|
api.use(dotRunnerRoutes(db, publicMcpOAuth.config.origin + "/mcp/runner"));
|
|
api.use(grokBotRoutes(db, publicMcpOAuth.config.origin + "/mcp/runner"));
|
|
grokDispatcher.start();
|
|
}
|
|
|
|
api.use(museBoardRoutes(db, opts.authPublicBaseUrl));
|
|
api.use(museQualificationRoutes(db));
|
|
app.use("/api", api);
|
|
app.use("/api", (_req, res) => {
|
|
res.status(404).json({ error: "API route not found" });
|
|
});
|
|
app.use(
|
|
pluginUiStaticRoutes(db, {
|
|
localPluginDir: opts.localPluginDir ?? DEFAULT_LOCAL_PLUGIN_DIR,
|
|
}),
|
|
);
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
if (opts.uiMode === "static") {
|
|
// Try published location first (server/ui-dist/), then monorepo dev location (../../ui/dist)
|
|
const candidates = [
|
|
path.resolve(__dirname, "../ui-dist"),
|
|
path.resolve(__dirname, "../../ui/dist"),
|
|
];
|
|
const uiDist = candidates.find((p) =>
|
|
fs.existsSync(path.join(p, "index.html")),
|
|
);
|
|
if (uiDist) {
|
|
staticUi.use(staticUiCompression());
|
|
// Hashed asset files (Vite emits them under /assets/<name>.<hash>.<ext>)
|
|
// never change once built, so they can be cached aggressively.
|
|
staticUi.use(
|
|
"/assets",
|
|
staticUiFiles(path.join(uiDist, "assets"), {
|
|
maxAge: "1y",
|
|
immutable: true,
|
|
}),
|
|
);
|
|
// Serve root/index through the same runtime HTML transform as SPA routes.
|
|
staticUi.get(["/", "/index.html"], (_req, res) => {
|
|
res.type("html").set("Cache-Control", "no-cache").send(readBrandedStaticIndexHtml(uiDist));
|
|
});
|
|
// Non-hashed static files (favicon.ico, manifest, robots.txt, etc.):
|
|
// short cache so operators who swap them out see the new version
|
|
// reasonably fast, with must-revalidate overrides for index.html and
|
|
// sw.js (see staticUiCacheControl for why those two).
|
|
staticUi.use(
|
|
staticUiFiles(uiDist, {
|
|
maxAge: "1h",
|
|
setHeaders(res, filePath) {
|
|
const override = staticUiCacheControl(filePath);
|
|
if (override) {
|
|
res.set("Cache-Control", override);
|
|
}
|
|
},
|
|
}),
|
|
);
|
|
// SPA fallback. Only for non-asset routes — if the browser asks for
|
|
// /assets/something.js that doesn't exist, we must NOT serve the HTML
|
|
// shell: the browser would try to load it as a JavaScript module, fail
|
|
// with a MIME-type error, and cache that broken response. Return 404
|
|
// instead. The index.html response itself is no-cache so a subsequent
|
|
// deploy's updated asset hashes are picked up on next load.
|
|
staticUi.get(/.*/, (req, res) => {
|
|
if (req.path.startsWith("/assets/")) {
|
|
res.status(404).end();
|
|
return;
|
|
}
|
|
res
|
|
.status(200)
|
|
.set("Content-Type", "text/html")
|
|
.set("Cache-Control", "no-cache")
|
|
.end(readBrandedStaticIndexHtml(uiDist));
|
|
});
|
|
} else {
|
|
console.warn("[paperclip] UI dist not found; running in API-only mode");
|
|
}
|
|
if (process.env.PAPERCLIP_MANAGED_RUNTIME_EXPOSURE === "tailscale_https") {
|
|
// The managed-runtime supervisor waits for the app port AND its derived
|
|
// Vite HMR companion port to bind before publishing the service. Static
|
|
// mode has no Vite, so bind the same placeholder listener dev mode uses
|
|
// or the supervisor kills a healthy server at the readiness deadline
|
|
// (PAP-18043).
|
|
const hmrServer = createHttpServer((_req, res) => {
|
|
res.writeHead(426, { "Content-Type": "text/plain" });
|
|
res.end("Upgrade Required");
|
|
});
|
|
await listenViteHmrServer(
|
|
hmrServer,
|
|
resolveViteHmrPort(opts.serverPort),
|
|
opts.bindHost,
|
|
);
|
|
viteHmrServer = hmrServer;
|
|
}
|
|
}
|
|
|
|
if (opts.uiMode === "vite-dev") {
|
|
const uiRoot = path.resolve(__dirname, "../../ui");
|
|
const publicUiRoot = path.resolve(uiRoot, "public");
|
|
const hmrPort = resolveViteHmrPort(opts.serverPort);
|
|
const hmrHost = resolveViteHmrHost(opts.bindHost);
|
|
const hmrProtocol = resolveViteHmrProtocol(
|
|
process.env.PAPERCLIP_VITE_HMR_PROTOCOL,
|
|
);
|
|
const hmrServer = createHttpServer((_req, res) => {
|
|
res.writeHead(426, { "Content-Type": "text/plain" });
|
|
res.end("Upgrade Required");
|
|
});
|
|
const { createServer: createViteServer } = await import("vite");
|
|
const configuredViteCacheDir = process.env.PAPERCLIP_VITE_CACHE_DIR?.trim();
|
|
const vite = await createViteServer({
|
|
root: uiRoot,
|
|
...(configuredViteCacheDir
|
|
? { cacheDir: path.resolve(configuredViteCacheDir) }
|
|
: {}),
|
|
appType: "custom",
|
|
// Vite otherwise discovers every HTML entry below the UI root. Generated
|
|
// Storybook output can reference dependencies that are intentionally not
|
|
// part of the application install, poisoning a clean embedded dev-server
|
|
// cache before the browser opens. The embedded UI has one real entry.
|
|
optimizeDeps: { entries: [path.resolve(uiRoot, "index.html")] },
|
|
server: {
|
|
// Listener binding and browser HMR hostname are deliberately separate:
|
|
// exposed branch runtimes stay loopback-only while the browser uses the
|
|
// current MagicDNS hostname through the broker's HTTPS listener.
|
|
host: opts.bindHost,
|
|
middlewareMode: true,
|
|
hmr: {
|
|
server: hmrServer,
|
|
...(hmrHost ? { host: hmrHost } : {}),
|
|
...(hmrProtocol ? { protocol: hmrProtocol } : {}),
|
|
port: hmrPort,
|
|
clientPort: hmrPort,
|
|
},
|
|
allowedHosts: privateHostnameGateEnabled
|
|
? Array.from(privateHostnameAllowSet)
|
|
: undefined,
|
|
},
|
|
});
|
|
try {
|
|
await listenViteHmrServer(hmrServer, hmrPort, opts.bindHost);
|
|
} catch (error) {
|
|
await vite.close();
|
|
throw error;
|
|
}
|
|
viteDevServer = vite;
|
|
viteHmrServer = hmrServer;
|
|
viteHtmlRenderer = createCachedViteHtmlRenderer({
|
|
vite,
|
|
uiRoot,
|
|
brandHtml: applyUiBranding,
|
|
});
|
|
const renderViteHtml = viteHtmlRenderer;
|
|
|
|
if (fs.existsSync(publicUiRoot)) {
|
|
staticUi.use(staticUiFiles(publicUiRoot, { index: false }));
|
|
}
|
|
staticUi.get(/.*/, async (req, res, next) => {
|
|
if (!shouldServeViteDevHtml(req)) {
|
|
next();
|
|
return;
|
|
}
|
|
try {
|
|
const html = await renderViteHtml.render(req.originalUrl);
|
|
res.status(200).set({ "Content-Type": "text/html" }).end(html);
|
|
} catch (err) {
|
|
next(err);
|
|
}
|
|
});
|
|
staticUi.use(vite.middlewares);
|
|
}
|
|
|
|
app.use(staticUi);
|
|
app.use(errorHandler);
|
|
|
|
jobCoordinator.start();
|
|
scheduler.start();
|
|
const deliveryWork = createDeliveryWorkCoordinator({
|
|
owner: db,
|
|
canRun: () => !isWarmStandby() && !isIdleTaskDrainActive(),
|
|
canReconcile: () => !isWarmStandby(),
|
|
onError: (err, queue) => logger.error({ err, queue }, "Delivery reconciliation failed"),
|
|
});
|
|
app.locals.deliveryWork = deliveryWork;
|
|
const agentLifecycleDelivery = deliveryWork.register(DELIVERY_QUEUES.agentLifecycle, {
|
|
retryMs: 1_000,
|
|
run: () => agentLifecycle.sweep(),
|
|
hasPending: () => agentLifecycle.hasPending(),
|
|
nextRunAt: () => agentLifecycle.nextRunAt(),
|
|
});
|
|
agentLifecycle.setWake(agentLifecycleDelivery.wake);
|
|
publicMcpEvents?.start(deliveryWork);
|
|
dotMcpEvents?.start(deliveryWork);
|
|
const stopMuseMaintenance = startMuseMaintenance(db, deliveryWork);
|
|
const resourceLifecycleDelivery = registerPluginLifecycleDelivery(deliveryWork, db, workerManager, lifecycle);
|
|
await resourceLifecycleDelivery.ready;
|
|
if (opts.feedbackExportService) {
|
|
deliveryWork.register(DELIVERY_QUEUES.feedback, {
|
|
retryMs: FEEDBACK_EXPORT_FLUSH_INTERVAL_MS,
|
|
run: (signal) => opts.feedbackExportService!.flushPendingFeedbackTraces({ signal }),
|
|
hasPending: () => opts.feedbackExportService!.hasPendingFeedbackTraces(),
|
|
});
|
|
}
|
|
registerChatDeliveryWork(deliveryWork, chatChannels, () => !isIdleTaskDrainActive());
|
|
registerChatActionWork(deliveryWork, chatChannels, () => !isIdleTaskDrainActive());
|
|
emailChannels.start();
|
|
const reconcileChatPublicationMaintenance = async () => {
|
|
await chatChannels.processPublicationMaintenance();
|
|
};
|
|
const chatReconciliation = createChatReconciliationCoordinator({
|
|
reconcileProviderRuntimes: async () => {
|
|
await chatChannels.reconcileProviderRuntimes();
|
|
await chatChannels.voice.reconcile();
|
|
},
|
|
// Chat delivery, action, and Telegram discovery workers now own these
|
|
// duties. Keep the coordinator's other maintenance lanes independent.
|
|
processPendingDeliveries: async () => undefined,
|
|
processFailedGitHubWebhookDeliveries: () =>
|
|
chatChannels.processFailedGitHubWebhookDeliveries(),
|
|
projectRunMilestones: () =>
|
|
enqueueChatRunMilestones(db, {
|
|
publicBaseUrl: opts.authPublicBaseUrl,
|
|
}),
|
|
flushPublications: () => reconcileChatPublicationMaintenance(),
|
|
onError: (lane, err) => {
|
|
logger.error({ err, lane }, `Failed to reconcile chat ${lane}`);
|
|
},
|
|
});
|
|
const unsubscribeChatPublicationSignals = subscribeAllCompanyLiveEvents(
|
|
(event) => {
|
|
if (!isWarmStandby() && !isIdleTaskDrainActive() && isChatPublicationCommitSignal(event))
|
|
chatReconciliation.notifyPublications();
|
|
},
|
|
);
|
|
// Provider/action maintenance and milestone projection still use this cadence.
|
|
// Inbox, outbox, and file receipt queues have independent commit/deadline wakes.
|
|
let chatPublicationTimer: ReturnType<typeof setInterval> | null = setInterval(
|
|
() => {
|
|
if (!isWarmStandby() && !isIdleTaskDrainActive()) chatReconciliation.reconcile();
|
|
},
|
|
CHAT_PUBLICATION_FLUSH_INTERVAL_MS,
|
|
);
|
|
chatPublicationTimer.unref?.();
|
|
if (!isWarmStandby() && !isIdleTaskDrainActive()) chatReconciliation.reconcile();
|
|
// Abandoned chunked-import spool sweep: hourly (plus once at startup),
|
|
// deleting spool dirs whose transfer saw no activity for 24h and cancelling
|
|
// their still-open ledger runs. Same setInterval + unref + shutdown-clear
|
|
// shape as the feedback export flush above.
|
|
const importTransferSpoolRoot = resolveDefaultImportTransferSpoolRoot();
|
|
const sweepImportTransferSpools = () => {
|
|
if (isWarmStandby() || isIdleTaskDrainActive()) return;
|
|
sweepAbandonedImportTransferSpools(db, importTransferSpoolRoot)
|
|
.then((result) => {
|
|
if (result.swept > 0) {
|
|
logger.info(result, "swept abandoned company import transfer spools");
|
|
}
|
|
})
|
|
.catch((err) => {
|
|
logger.error(
|
|
{ err },
|
|
"abandoned company import transfer spool sweep failed",
|
|
);
|
|
});
|
|
};
|
|
registerBrowserUseCleanup(deliveryWork, browserUse, () => !isIdleTaskDrainActive());
|
|
let importTransferSweepTimer: ReturnType<typeof setInterval> | null =
|
|
setInterval(
|
|
sweepImportTransferSpools,
|
|
IMPORT_TRANSFER_SPOOL_SWEEP_INTERVAL_MS,
|
|
);
|
|
importTransferSweepTimer.unref?.();
|
|
// Startup only (never on the hourly interval — that would kill live
|
|
// applies): apply jobs are in-memory in this single process, so any run
|
|
// still "applying" now was interrupted by the previous shutdown and would
|
|
// otherwise 409 every retry forever. Fail those stranded runs — their
|
|
// spooled parts stay reusable — then run the normal sweep once.
|
|
void companyTransferRunService
|
|
.recoverStrandedApplyingRuns(db)
|
|
.then((recovered) => {
|
|
if (recovered.length > 0) {
|
|
logger.warn(
|
|
{ count: recovered.length, runIds: recovered },
|
|
"failed company transfer runs stranded in applying by a restart",
|
|
);
|
|
}
|
|
})
|
|
.catch((err) => {
|
|
logger.error({ err }, "stranded company transfer apply recovery failed");
|
|
})
|
|
.finally(() => {
|
|
sweepImportTransferSpools();
|
|
});
|
|
void toolDispatcher.initialize().catch((err) => {
|
|
logger.error({ err }, "Failed to initialize plugin tool dispatcher");
|
|
});
|
|
const devWatcher = createPluginDevWatcher(
|
|
lifecycle,
|
|
async (pluginId) =>
|
|
(await pluginRegistry.getById(pluginId))?.packagePath ?? null,
|
|
undefined,
|
|
{ unwatchedRoots: [bundledCatalogRoot] },
|
|
);
|
|
// Auto-provision bundled plugins so their providers are registered for
|
|
// agent runs. Bundles are excluded from the pnpm
|
|
// workspace and built standalone into the image (see Dockerfile), then
|
|
// installed here from their local paths. This runs BEFORE loadAll() so
|
|
// loadAll() can activate them in the same startup pass.
|
|
//
|
|
// Workers are started exactly once, by loadAll(): the `lifecycle` manager
|
|
// above is constructed without a runtime-capable loader
|
|
// (pluginLifecycleManager(db, { workerManager }) — no `loader` option), so
|
|
// the lifecycle.load() that ensureBundledPlugins performs per newly
|
|
// installed bundle only records the `ready` status and does not spawn a
|
|
// worker (see activateReadyPlugin in services/plugin-lifecycle.ts).
|
|
//
|
|
// Managed instances (`plugins.autoInstall` from PAPERCLIP_MANAGED_CONFIG)
|
|
// drive the key list from the control plane; self-hosted instances keep
|
|
// the pre-existing behavior of ensuring only the kubernetes bundle.
|
|
//
|
|
// Resolution is deliberately synchronous and NOT fail-safe: an
|
|
// unknown key or a path escaping the bundled catalog root throws out of
|
|
// createApp so a managed instance refuses to start (positive allowlist,
|
|
// fail closed).
|
|
// SAFETY: installation is fully fail-safe. Any failure
|
|
// (missing bundle, install error, load error) is caught, logged, and
|
|
// swallowed per plugin so the server ALWAYS finishes booting. A degraded
|
|
// boot (a provider unavailable, some agents cannot run) is strictly
|
|
// preferable to a crash loop.
|
|
//
|
|
// The chain is not awaited here (createApp stays fast), but the settled
|
|
// promise is exposed via `app.locals.bundledPluginsStartup` so boot steps
|
|
// that must not outrun plugin availability — managed sandbox environments
|
|
// (`applyManagedEnvironments`) run before the heartbeat resumes queued
|
|
// runs — can sequence on it. It never rejects.
|
|
const bundledPluginsStartup = ensureBundledPlugins(
|
|
bundledPluginInstalls,
|
|
{ registry: pluginRegistry, loader, lifecycle, logger },
|
|
// Managed mode reinstalls soft-uninstalled bundles (the control plane
|
|
// owns provisioning); self-hosted leaves an operator's uninstall alone.
|
|
// Disabled plugins never start automatically. Added distribution permissions
|
|
// still enter upgrade_pending so enabling them requires an operator decision.
|
|
{ reinstallUninstalled: managedAutoInstallKeys !== null },
|
|
)
|
|
.then(() => loader.loadAll())
|
|
.then((result) => {
|
|
if (!result) return;
|
|
for (const loaded of result.results) {
|
|
if (devWatcher && loaded.success && loaded.plugin.packagePath) {
|
|
devWatcher.watch(loaded.plugin.id, loaded.plugin.packagePath);
|
|
}
|
|
}
|
|
})
|
|
.catch((err) => {
|
|
logger.error({ err }, "Failed to load ready plugins on startup");
|
|
});
|
|
app.locals.bundledPluginsStartup = trackIdleWork(bundledPluginsStartup);
|
|
void bundledPluginsStartup.then(() => { lifecyclePluginsReady = true; resourceLifecycleDelivery.wake(); agentLifecycleDelivery.wake(); }).catch(() => logger.warn("Agent lifecycle recovery failed; retrying."));
|
|
// The shutdown hook runs at most once. It caches the in-flight promise, so a
|
|
// second caller (for example the `exit` handler) awaits the same completion
|
|
// instead of starting a second teardown.
|
|
let appServicesShutdown: Promise<void> | null = null;
|
|
const shutdownAppServices = (): Promise<void> => {
|
|
if (appServicesShutdown) return appServicesShutdown;
|
|
appServicesShutdown = (async () => {
|
|
// The scheduler tick queries the database. Stop it here, inside the
|
|
// awaited teardown, so no tick runs after the caller ends the pool.
|
|
scheduler.stop();
|
|
await agentLifecycle.stop();
|
|
await publicMcpEvents?.stop();
|
|
await dotMcpEvents?.stop(); grokDispatcher.stop();
|
|
jobCoordinator.stop();
|
|
resourceLifecycleDelivery.dispose();
|
|
await deliveryWork.stop();
|
|
unsubscribeChatPublicationSignals();
|
|
chatReconciliation.stop();
|
|
if (chatPublicationTimer) {
|
|
clearInterval(chatPublicationTimer);
|
|
chatPublicationTimer = null;
|
|
}
|
|
await chatReconciliation.drain();
|
|
if (importTransferSweepTimer) {
|
|
clearInterval(importTransferSweepTimer);
|
|
importTransferSweepTimer = null;
|
|
}
|
|
devWatcher?.close();
|
|
viteHtmlRenderer?.dispose();
|
|
void viteDevServer?.close().catch(() => undefined);
|
|
viteHmrServer?.close();
|
|
hostServiceCleanup.disposeAll();
|
|
hostServiceCleanup.teardown();
|
|
await stopMuseMaintenance();
|
|
await emailChannels.shutdown();
|
|
await chatChannels.shutdown();
|
|
// End the avatar worker pool, if a request ever started one, so no
|
|
// render outlives the HTTP teardown.
|
|
await agentAvatars.close();
|
|
// Cancel every live setup-token login session and AWAIT the cancellation,
|
|
// so each direct child stops and the server releases each lease before the
|
|
// caller stops the database and the provider. A lease release that
|
|
// fails stays a durable record for the startup reaper.
|
|
await setupTokenLoginService?.shutdown();
|
|
})();
|
|
return appServicesShutdown;
|
|
};
|
|
app.locals.paperclipShutdown = shutdownAppServices;
|
|
|
|
// The `exit` event is synchronous. It cannot await the teardown, so it runs
|
|
// the best-effort cleanup and drops the returned promise. The orderly signal
|
|
// path awaits `shutdownAppServices` in full before the process exits.
|
|
process.once("exit", () => {
|
|
void shutdownAppServices();
|
|
});
|
|
process.once("beforeExit", () => {
|
|
void flushPluginLogBuffer();
|
|
});
|
|
|
|
trackIdleRequestHandlers(app);
|
|
return app;
|
|
}
|