mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agent runs need credentials for a specific provider and sign-in method. > - Connections already owns accounts, grants, and access permissions. > - AI authentication should use those same boundaries. > - This pull request adds the storage, API, adoption, and runtime foundation. > - Legacy agents keep their authentication until they explicitly adopt a managed connection. ## Linked Issues or Issue Description **Problem or motivation** AI credentials are configured separately from Connections. Agents cannot consistently reuse a responsible user's account or a permitted shared account. **Proposed solution** Manage AI accounts with the existing Connections grants and permissions. Keep model and harness selection independent from credential selection. Preserve legacy authentication until validated adoption. **Alternatives considered** A separate credential registry would duplicate ownership and access policy. Automatic fallback would risk using the wrong account. **Roadmap alignment** This extends the shipped Apps, multi-user, secrets, and agent-runtime capabilities. The maintainer requested the feature and reviewed the UI. Related groundwork: #11899 (connection permissions), #10910 (connection wizard), #11692 (Claude subscription profiles), and #11854 (Codex account rotation). ## What Changed - Add AI-purpose/runtime-auth contracts and an additive, idempotent migration. - Add Claude, OpenAI, OpenRouter, and Grok provider capabilities and catalog entries. - Store credentials on grants. Resolve responsible-user defaults or explicit permitted grants. - Isolate managed credentials and provider sessions across accounts. Block missing credentials without ambient fallback. - Keep imported legacy secrets unchanged during reconnect. Use independent local Codex/Grok sign-in attempts for rotating credentials. - Add authorization, migration, concurrent refresh, retry, cancellation, and legacy-compatibility tests. This is part 1 of a two-PR stack. The app UI follows in #13248. Merge the foundation first. ## Verification - Updated against master `04e364236`, preserving upstream provider login and connector workflows. - Full workspace typecheck, production build, Storybook build, and token gates passed on the integrated branch. Final local-login changes passed 59 focused tests; new-agent and inbox regression suites passed 63 tests. - Browser checks verified automatic local Claude account detection, resumable Codex login commands, retry, focus restoration, and desktop/phone layouts. Commands create their isolated directory before invoking the CLI. - All current-head CI checks passed on `2a996560a`, including all server/workspace tests, browser shards, runner verification, typecheck, build, and canary dry run. Greptile reviewed that commit at 5/5 with no unresolved threads. Earlier local full-suite attempts hit the Mac PostgreSQL shared-memory limit; the complete suites passed in CI. - Renumbered the additive AI migration to `0276` after upstream migrations and regenerated its snapshot. Existing legacy agents retain their configuration. - Added local login status checks, owner-scoped retry, managed OpenCode remote homes, credential-aware model discovery, and task connection-repair delivery. ## Risks - Managed credential failures intentionally block execution. They do not restore legacy fallback. - Preview-era copied Codex/Grok subscriptions require independent reconnect. - The integrated branch has live provider acceptance coverage. This update verifies local Claude detection and Codex API-key task repair; it does not add a new subscription authorization/refresh or Daytona stress pass. - Runtime-auth connections must stay excluded from tool and channel handling. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools, code execution, and browser testing. The exact runtime model identifier and context-window size 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 - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
124 lines
7.0 KiB
TypeScript
124 lines
7.0 KiB
TypeScript
import { sql } from "drizzle-orm";
|
|
import { index, jsonb, pgTable, text, timestamp, uniqueIndex, uuid, varchar } from "drizzle-orm/pg-core";
|
|
import type { AdapterAuthSessionInternalStatus, AgentAdapterType } from "@paperclipai/shared";
|
|
import { companies } from "./companies.js";
|
|
import { environments } from "./environments.js";
|
|
|
|
// The merged state set for the unified login table. One column holds the state
|
|
// of both login flows: the device-login flow and the setup-token flow. The set
|
|
// joins the two prior state unions into one union. The set drops the dead
|
|
// `persisting` state.
|
|
//
|
|
// The active states hold the company credential slot for one company, owner, and
|
|
// adapter. The partial unique index applies to the active states only.
|
|
// - `starting`, `waiting_for_user`, `promoting`: the device-login active states.
|
|
// - `awaiting_code`, `submitting`: the setup-token active states.
|
|
// The non-active states do not hold the slot:
|
|
// - `stored`: the one-time setup-token claim. The create path consumes it and
|
|
// writes `bound_at`.
|
|
// - `authenticated`, `completed`: the terminal success states.
|
|
// - `cleanup_pending`: the terminal state whose sandbox delete failed.
|
|
// - `failed`, `timed_out`, `cancelled`: the shared terminal failure states.
|
|
export type AdapterAuthSessionState =
|
|
| AdapterAuthSessionInternalStatus
|
|
| "awaiting_code"
|
|
| "submitting"
|
|
| "stored"
|
|
| "completed";
|
|
|
|
// The active states of the merged set. The partial unique index and the store
|
|
// use this list. The list excludes `stored`, every terminal state, and the
|
|
// removed `persisting` state.
|
|
export const ADAPTER_AUTH_SESSION_ACTIVE_STATES = [
|
|
"starting",
|
|
"waiting_for_user",
|
|
"promoting",
|
|
"awaiting_code",
|
|
"submitting",
|
|
] as const satisfies readonly AdapterAuthSessionState[];
|
|
|
|
// The durable store for an adapter login session. One row tracks one login
|
|
// attempt for one adapter in one environment. The row keeps the owner principal,
|
|
// the public session id, the provider lease reference, the status, and the
|
|
// finish times. The row never stores the prompt, a credential byte, or the raw
|
|
// provider secret.
|
|
export const adapterAuthSessions = pgTable(
|
|
"adapter_auth_sessions",
|
|
{
|
|
id: uuid("id").primaryKey().defaultRandom(),
|
|
companyId: uuid("company_id").notNull().references(() => companies.id, { onDelete: "cascade" }),
|
|
environmentId: uuid("environment_id").notNull().references(() => environments.id, { onDelete: "cascade" }),
|
|
aiConnection: jsonb("ai_connection").$type<import("@paperclipai/shared").AiConnectionLoginIntent>(),
|
|
connectionId: uuid("connection_id"),
|
|
connectionGrantId: uuid("connection_grant_id"),
|
|
connectionMethod: text("connection_method"),
|
|
adapterType: text("adapter_type").$type<AgentAdapterType>().notNull(),
|
|
// The immutable owner principal. The service sets this column one time at
|
|
// create and never updates it. The service returns the prompt only to this
|
|
// owner. The active-slot index includes this column, so the column stays
|
|
// non-null; a null owner escapes a partial unique index.
|
|
startedByUserId: text("started_by_user_id").notNull(),
|
|
// The opaque public session id. The public API returns this id, and the
|
|
// store keys its lookups by it. The column is non-null, length-bounded, and
|
|
// unique. The store fills it at create with a CSPRNG value.
|
|
publicSessionId: varchar("public_session_id", { length: 128 }).notNull(),
|
|
// The provider lease reference for the sandbox. The reaper reads it to retry
|
|
// a failed sandbox delete. It is not a public field.
|
|
providerLeaseId: text("provider_lease_id"),
|
|
// The merged login state. The column is `text`, so it stores every value of
|
|
// the merged `AdapterAuthSessionState` set. The compile-time `$type` is the
|
|
// merged union, so both login stores share one status type.
|
|
status: text("status").$type<AdapterAuthSessionState>().notNull().default("starting"),
|
|
expiresAt: timestamp("expires_at", { withTimezone: true }),
|
|
// The promotion claim deadline. The service sets this column when it moves the
|
|
// row to `promoting`. While the deadline is in the future, the claim is live,
|
|
// so the reaper does not terminate the session or release the company slot.
|
|
// A null or past deadline means no live claim, so the reaper can reclaim a
|
|
// stalled `promoting` row. The service clears the column on every terminal
|
|
// transition.
|
|
promotionExpiresAt: timestamp("promotion_expires_at", { withTimezone: true }),
|
|
// The claim-consumption marker for a `stored` row. The column is null while
|
|
// the stored claim is live. The create path sets it one time when it consumes
|
|
// the claim. A non-null value marks a consumed claim, so the reaper removes
|
|
// the row. A device-login row never sets this column.
|
|
boundAt: timestamp("bound_at", { withTimezone: true }),
|
|
finishedAt: timestamp("finished_at", { withTimezone: true }),
|
|
// The fixed, non-secret failure code. The public response reads it.
|
|
failureReason: text("failure_reason"),
|
|
// The non-secret result claim of a terminal success, written in the SAME
|
|
// conditional write that records the terminal status, so a claim can never
|
|
// exist for a session that did not authenticate and a restart never loses
|
|
// it. For a Codex device login this holds the account-binding claim: the
|
|
// opaque company secret id that names the login's account home, and
|
|
// whether the company default home stayed on a different account. Never a
|
|
// credential byte, never an account identifier. Null for every failure
|
|
// and for flows that produce no claim.
|
|
resultClaim: jsonb("result_claim").$type<Record<string, unknown>>(),
|
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
|
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
|
},
|
|
(table) => ({
|
|
companyStatusIdx: index("adapter_auth_sessions_company_status_idx").on(
|
|
table.companyId,
|
|
table.status,
|
|
),
|
|
// Serialize on the company credential slot. Only one active session can hold
|
|
// the slot per company, owner, and adapter. The index applies to the active
|
|
// states of the merged set. It does not include the environment; the board
|
|
// rule scopes the slot to the owner, not the environment.
|
|
companyOwnerAdapterActiveUq: uniqueIndex("adapter_auth_sessions_company_owner_adapter_active_uq")
|
|
.on(table.companyId, table.startedByUserId, table.adapterType)
|
|
.where(
|
|
sql`${table.status} IN ('starting', 'waiting_for_user', 'promoting', 'awaiting_code', 'submitting')`,
|
|
),
|
|
// The public session id is unique across the table. The store keys its
|
|
// lookups by this id.
|
|
publicSessionIdUq: uniqueIndex("adapter_auth_sessions_public_session_id_uq").on(
|
|
table.publicSessionId,
|
|
),
|
|
environmentIdx: index("adapter_auth_sessions_environment_idx").on(table.environmentId),
|
|
expiresIdx: index("adapter_auth_sessions_expires_idx").on(table.expiresAt),
|
|
providerLeaseIdx: index("adapter_auth_sessions_provider_lease_idx").on(table.providerLeaseId),
|
|
}),
|
|
);
|