mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-17 13:01:05 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - A heartbeat run resumes the agent's saved task session, which holds the provider thread and its history. > - Before resume, Paperclip compares a fingerprint of the effective run configuration with the fingerprint that the session saved. A difference discards the thread. > - The fingerprint hashed the agent config revision row (id, changed keys, time). Every saved agent edit therefore discarded the thread, also an edit that set a value back to what it was. > - The fingerprint also hashed settings that never reach the thread or the native execution input, for example turn timeouts, wake scheduling, and the environment row's update time. > - This pull request removes those inputs from the fingerprint, classifies every input with its reason, and adds backstop tests so that a new input cannot join or leave the fingerprint without a decision. > - The benefit is that agents keep their thread history across edits that cannot change what the thread saw or may do, while real changes still start a new thread. ## Linked Issues or Issue Description Related: #9977 (semantic task-session fingerprints, open) and #8797 (added the effective run config fingerprint). **What happened?** An operator changed an agent's warm idle window from 60000 to unset, and then back to 60000, between two turns on the same issue. The next run logged `Skipping saved session resume for task "<issue>" because effective run configuration changed: adapter.` Only the `adapter` category changed, because the new config revision row was in it. The adapter config itself was identical. The run started a new provider thread. The environment lease was reused, so the run stopped the retained remote task before it started a new one. That stop raced the task's exit, and the run failed with `Plugin Runner termination is unconfirmed; reconcile the saved task`. An automatic retry then succeeded on a fresh environment. **Expected behavior** An edit that cannot change what the provider thread saw or may do, and cannot change the native execution input, keeps the saved session. An edit to the model, provider, active permission mode, lifecycle mode or warm idle window, instructions, skills, environment, secrets, or another thread input still starts a new session. **Steps to reproduce** 1. Run an agent turn on an issue so that the task session saves its fingerprint. 2. Save an agent config edit that does not change a thread input, for example set `adapterConfig.idleTimeoutMs` to another value and back, or rename the agent. 3. Wake the agent on the same issue. On master the run log shows "effective run configuration changed: adapter" and the run starts a new thread. ## What Changed - New `server/src/services/heartbeat/session-fingerprint-inputs.ts`. It classifies each fingerprint input as kept or excluded, with the reason: - agent config revision fields (`CONFIG_REVISION_FIELDS`); - `paperclip_runner` adapter config keys; - top-level environment driver config keys; - agent runtime config keys; - selected-environment and environment-selection fields. - The session fingerprint no longer hashes these inputs: - the config revision row (id, changed keys, time); - for `paperclip_runner`: `timeoutSec`, `graceSec`, the permission keys of providers that are not selected, and `search` when the provider is not Codex; - `runtimeConfig.heartbeat` (wake scheduling, concurrency, daily caps, max-turn continuation); - the selected environment's `configRevisionAt` (row update time) and the `selectionSource`; - environment config `archiveOnRelease`, `streamRunLogs`, and `timeoutMs` (sandbox RPC timeout). - Unknown adapter and runtime config keys are still hashed. A missing classification can only keep the old reset behavior; it cannot skip a reset. - Lifecycle inputs stay in the fingerprint: `lifecycleMode`, `idleTimeoutMs`, and the environment's `runnerLifecycleMode`, `runnerIdleTimeoutMs`, and `reuseLease`. They become `session.lifecyclePolicy`, which the native session digest compares before a follow-up turn attaches to its warm Runner. A kept session with a different policy would be refused (`warm_recovery_refused=execution_mismatch`). - Session preparation accepts a saved fingerprint built with the previous composition (`legacyComposition`) for the same inputs. The upgrade therefore does not discard every saved session once. The run then saves the new fingerprint. - Backstop tests in `session-fingerprint-inputs.test.ts`: - every agent revision field, runner config schema field, provider permission key, and environment driver config key has a classification; - the shape of each hashed category is pinned, so a new field cannot reach the fingerprint without a decision; - every runner key classified as excluded leaves the native provider input and the lifecycle policy unchanged (this test fails if `idleTimeoutMs` is reclassified as excluded); - behavior tests for each exclusion and for the thread and lifecycle inputs that must still reset; - a pinned fingerprint proves that the legacy composition reproduces the master fingerprint exactly. - `ai-connection-session.test.ts`: two tests used a rename or a `heartbeat` edit as the "unrelated change". They now use a model change or an unclassified runtime setting, and two new tests pin that a rename and a scheduling change keep the session. - `doc/heartbeat-internals.md` (Config Freshness) describes the rule and the backstop. The PR adds no code comments, as `CONTRIBUTING.md` requires; the reasons live in the classification tables and the doc. ## Verification - Red/green: on master, the exclusion cases, the category-shape pin, and the legacy acceptance case fail. With the change, all pass. - Backstop check: with `idleTimeoutMs` temporarily reclassified as excluded, the native-input test and the idle-window reset test fail. - Legacy bridge: I computed the fingerprint for one runner fixture and one `codex_local` fixture with master's `workspaces.ts` and with `legacyComposition: true` on this branch. The output files were byte-identical, category fingerprints included. The pinned test uses those values. - `cd server && npx vitest run src/services/heartbeat/session-fingerprint-inputs.test.ts src/__tests__/ai-connection-session.test.ts src/__tests__/heartbeat-workspace-session.test.ts src/__tests__/heartbeat-execution-configuration.test.ts src/__tests__/ai-connection-router.test.ts src/__tests__/native-session-resumption.test.ts src/__tests__/environment-service.test.ts`: 7 files, 397 tests, all pass. - `npx tsc --noEmit -p server`: no errors. - `pnpm verify` exited 2 (broader coverage needed), so the focused checks above and required CI give the coverage. ## Risks - Behavior change: an agent rename, role, title, icon, appearance, reports-to, capabilities, budget, or metadata edit no longer starts a new thread. Agent tools read these fields live at call time (`runner-semantic-authority.ts`, `paperclip-runner-tool-authority.ts`), so the thread never holds a frozen copy. - Behavior change: wake-scheduling and turn-timeout edits no longer start a new thread. Neither value is part of the native execution input, so warm Runner attachment is unaffected. - A warm idle window edit still starts a new thread. Setting it and setting it back between turns no longer does, because the revision row is not hashed. - The legacy bridge computes extra candidate fingerprints only when the saved fingerprint differs. It accepts a legacy fingerprint only for the same current inputs; it never widens what a reset protects. - During the transition, a real change on a session that still holds a legacy fingerprint can list extra categories in the reset reason. The reset decision is correct. - No schema or API change. The fingerprint version stays 1. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used in Claude Code with tool use (shell, file edit) and extended thinking. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
492 lines
19 KiB
TypeScript
492 lines
19 KiB
TypeScript
import { createHash, randomBytes } from "node:crypto";
|
|
import { and, eq, gte, inArray, lt, sql } from "drizzle-orm";
|
|
import { agents, costEvents, type Db } from "@paperclipai/db";
|
|
import {
|
|
agentAppearanceSchema, resolveAgentAppearance, agentAvatarUrl,
|
|
AGENT_DEFAULT_MAX_CONCURRENT_RUNS, agentRuntimeConfigSchema, getAgentWorkEligibility,
|
|
normalizeAgentUrlKey, type AgentEligibilityAgent, type AgentRunnerChoice,
|
|
} from "@paperclipai/shared";
|
|
import { conflict, notFound, unprocessable } from "../errors.js";
|
|
import { REDACTED_EVENT_VALUE, sanitizeRecord } from "../redaction.js";
|
|
import { normalizeAgentPermissions } from "./agent-permissions.js";
|
|
import { readAgentReportingChain } from "./agent-reporting-chain.js";
|
|
import { builtInAgentMarkersEqual, readBuiltInAgentMarker } from "./built-in-agent-metadata.js";
|
|
|
|
export function hashToken(token: string) {
|
|
return createHash("sha256").update(token).digest("hex");
|
|
}
|
|
|
|
export function createToken() {
|
|
return `pcp_${randomBytes(24).toString("hex")}`;
|
|
}
|
|
|
|
export const CONFIG_REVISION_FIELDS = [
|
|
"name",
|
|
"role",
|
|
"title",
|
|
"icon",
|
|
"appearance",
|
|
"reportsTo",
|
|
"capabilities",
|
|
"adapterType",
|
|
"adapterConfig",
|
|
"runtimeConfig",
|
|
"defaultEnvironmentId",
|
|
"budgetMonthlyCents",
|
|
"metadata",
|
|
] as const;
|
|
|
|
type ConfigRevisionField = (typeof CONFIG_REVISION_FIELDS)[number];
|
|
type AgentConfigSnapshot = Pick<typeof agents.$inferSelect, ConfigRevisionField>;
|
|
|
|
export interface RevisionMetadata {
|
|
createdByAgentId?: string | null;
|
|
createdByUserId?: string | null;
|
|
source?: string;
|
|
rolledBackFromRevisionId?: string | null;
|
|
}
|
|
|
|
/**
|
|
* The Claude login context for an agent write. The route derives the owner user
|
|
* from the authenticated actor, not from the request body, and forwards the
|
|
* non-secret `storedSessionId` claim from a completed Claude login session. A
|
|
* controlled internal override permits a migration or an administrator repair to
|
|
* bind or unbind the fixed OAuth token without a claim.
|
|
*
|
|
* The `applyExistingWithoutClaim` field is the user-actor apply-existing path.
|
|
* The route sets it only for an authenticated user actor and derives the owner
|
|
* from that actor. The path binds the fixed reference to the owner stored value
|
|
* with no login round trip. It is distinct from `allowInternalBindingOverride`,
|
|
* which does no ownership check.
|
|
*
|
|
* The `inheritedFromAgentId` field is the hire-inheritance path. The route
|
|
* sets it only for an authenticated agent actor whose hire request inherited
|
|
* the fixed reference from that named parent. The service re-reads the parent
|
|
* agent inside the write transaction and binds the fixed reference only when
|
|
* the parent exists, is in the same company, is a `claude_local` agent, and
|
|
* already holds the exact fixed binding.
|
|
*/
|
|
export interface ClaudeLoginContext {
|
|
storedSessionId?: string | null;
|
|
ownerUserId?: string | null;
|
|
allowInternalBindingOverride?: boolean;
|
|
applyExistingWithoutClaim?: boolean;
|
|
inheritedFromAgentId?: string | null;
|
|
}
|
|
|
|
export interface UpdateAgentOptions {
|
|
expectedConfigurationRevision?: string;
|
|
expectedConfiguration?: Pick<AgentConfigurationRecord, "adapterType" | "adapterConfig" | "runtimeConfig" | "defaultEnvironmentId">;
|
|
recordRevision?: RevisionMetadata;
|
|
allowBuiltInAgentMetadata?: boolean;
|
|
allowPendingApprovalConfigUpdate?: boolean;
|
|
claudeLogin?: ClaudeLoginContext;
|
|
}
|
|
|
|
export type CreateAgentData = Omit<typeof agents.$inferInsert, "companyId" | "lifecycleState" | "lifecycleRequiredPluginIds" | "lifecycleHolds" | "lifecycleVersion" | "lifecycleError" | "lifecycleOperation"> & { runner?: AgentRunnerChoice };
|
|
export type AgentConfigurationRecord = typeof agents.$inferSelect;
|
|
export const AGENT_CONFIGURATION_FIELDS = [...CONFIG_REVISION_FIELDS, "permissions"] as const;
|
|
export type AgentConfigurationPatch = Partial<Pick<typeof agents.$inferInsert, typeof AGENT_CONFIGURATION_FIELDS[number]>>;
|
|
export type AgentHireRecord = Pick<typeof agents.$inferSelect, "id" | "companyId" | "adapterType" | "adapterConfig" | "permissions" | "metadata" | "status">;
|
|
|
|
export interface CreateAgentOptions {
|
|
createdByAgentId?: string | null;
|
|
createdByAgentCompanyId?: string;
|
|
interactionTexts?: readonly string[];
|
|
initialBudgetPolicyUserId?: string;
|
|
setupOnly?: boolean;
|
|
setupAgentId?: string;
|
|
runnerResolved?: boolean;
|
|
responsibleUserId?: string | null;
|
|
createdByUserId?: string | null;
|
|
aiConnectionInstall?: { connectionId: string; memberConnectionIds?: string[]; createdByUserId: string | null };
|
|
allowBuiltInAgentMetadata?: boolean;
|
|
claudeLogin?: ClaudeLoginContext;
|
|
}
|
|
|
|
type AgentEligibilityRow = Pick<typeof agents.$inferSelect, "id" | "companyId" | "name" | "status" | "reportsTo">;
|
|
|
|
interface AgentShortnameRow {
|
|
id: string;
|
|
name: string;
|
|
status: string;
|
|
}
|
|
|
|
interface AgentShortnameCollisionOptions {
|
|
excludeAgentId?: string | null;
|
|
}
|
|
|
|
export function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
}
|
|
|
|
export function jsonEqual(left: unknown, right: unknown): boolean {
|
|
return JSON.stringify(left) === JSON.stringify(right);
|
|
}
|
|
|
|
export function buildConfigSnapshot(
|
|
row: Pick<typeof agents.$inferSelect, ConfigRevisionField>,
|
|
): AgentConfigSnapshot {
|
|
const adapterConfig =
|
|
typeof row.adapterConfig === "object" && row.adapterConfig !== null && !Array.isArray(row.adapterConfig)
|
|
? sanitizeRecord(row.adapterConfig as Record<string, unknown>)
|
|
: {};
|
|
const runtimeConfig =
|
|
typeof row.runtimeConfig === "object" && row.runtimeConfig !== null && !Array.isArray(row.runtimeConfig)
|
|
? sanitizeRecord(row.runtimeConfig as Record<string, unknown>)
|
|
: {};
|
|
const metadata =
|
|
typeof row.metadata === "object" && row.metadata !== null && !Array.isArray(row.metadata)
|
|
? sanitizeRecord(row.metadata as Record<string, unknown>)
|
|
: row.metadata ?? null;
|
|
return {
|
|
name: row.name,
|
|
role: row.role,
|
|
title: row.title,
|
|
icon: row.icon,
|
|
appearance: row.appearance,
|
|
reportsTo: row.reportsTo,
|
|
capabilities: row.capabilities,
|
|
adapterType: row.adapterType,
|
|
adapterConfig,
|
|
runtimeConfig,
|
|
defaultEnvironmentId: row.defaultEnvironmentId,
|
|
budgetMonthlyCents: row.budgetMonthlyCents,
|
|
metadata,
|
|
};
|
|
}
|
|
|
|
export function containsRedactedMarker(value: unknown): boolean {
|
|
if (value === REDACTED_EVENT_VALUE) return true;
|
|
if (Array.isArray(value)) return value.some((item) => containsRedactedMarker(item));
|
|
if (typeof value !== "object" || value === null) return false;
|
|
return Object.values(value as Record<string, unknown>).some((entry) => containsRedactedMarker(entry));
|
|
}
|
|
|
|
export function hasConfigPatchFields(data: Partial<typeof agents.$inferInsert>) {
|
|
return CONFIG_REVISION_FIELDS.some((field) => Object.prototype.hasOwnProperty.call(data, field));
|
|
}
|
|
|
|
export function changedPendingApprovalConfigFields(
|
|
existing: Omit<typeof agents.$inferSelect, "lifecycleOperation" | "lifecycleRequiredPluginIds" | "harnessVerifiedDigest" | "harnessVerifiedAt">,
|
|
data: Partial<typeof agents.$inferInsert>,
|
|
) {
|
|
return CONFIG_REVISION_FIELDS.filter((field) =>
|
|
Object.prototype.hasOwnProperty.call(data, field) && !jsonEqual(data[field], existing[field]),
|
|
);
|
|
}
|
|
|
|
export function configPatchFromApprovalPayload(payload: Record<string, unknown>) {
|
|
const patch: Partial<typeof agents.$inferInsert> = {};
|
|
if (typeof payload.name === "string") patch.name = payload.name;
|
|
if (typeof payload.role === "string") patch.role = payload.role;
|
|
if (payload.appearance != null) patch.appearance = agentAppearanceSchema.parse(payload.appearance);
|
|
if (Object.prototype.hasOwnProperty.call(payload, "title")) {
|
|
patch.title = typeof payload.title === "string" ? payload.title : null;
|
|
}
|
|
if (Object.prototype.hasOwnProperty.call(payload, "icon")) {
|
|
patch.icon = typeof payload.icon === "string" ? payload.icon : null;
|
|
}
|
|
if (Object.prototype.hasOwnProperty.call(payload, "reportsTo")) {
|
|
patch.reportsTo = typeof payload.reportsTo === "string" ? payload.reportsTo : null;
|
|
}
|
|
if (Object.prototype.hasOwnProperty.call(payload, "capabilities")) {
|
|
patch.capabilities = typeof payload.capabilities === "string" ? payload.capabilities : null;
|
|
}
|
|
if (typeof payload.adapterType === "string") patch.adapterType = payload.adapterType;
|
|
if (isPlainRecord(payload.adapterConfig)) patch.adapterConfig = payload.adapterConfig;
|
|
if (isPlainRecord(payload.runtimeConfig)) patch.runtimeConfig = payload.runtimeConfig;
|
|
if (Object.prototype.hasOwnProperty.call(payload, "defaultEnvironmentId")) {
|
|
patch.defaultEnvironmentId =
|
|
typeof payload.defaultEnvironmentId === "string" ? payload.defaultEnvironmentId : null;
|
|
}
|
|
if (typeof payload.budgetMonthlyCents === "number") {
|
|
patch.budgetMonthlyCents = payload.budgetMonthlyCents;
|
|
}
|
|
if (Object.prototype.hasOwnProperty.call(payload, "metadata")) {
|
|
patch.metadata = isPlainRecord(payload.metadata) ? payload.metadata : null;
|
|
}
|
|
if (isPlainRecord(payload.permissions)) {
|
|
patch.permissions = payload.permissions;
|
|
}
|
|
return patch;
|
|
}
|
|
|
|
function parseFiniteNumberLike(value: unknown): number | null {
|
|
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
if (typeof value !== "string") return null;
|
|
const parsed = Number(value.trim());
|
|
return Number.isFinite(parsed) ? parsed : null;
|
|
}
|
|
|
|
export function normalizeRuntimeConfigForNewAgent(runtimeConfig: unknown): Record<string, unknown> {
|
|
const normalizedRuntimeConfig = isPlainRecord(runtimeConfig) ? { ...runtimeConfig } : {};
|
|
const heartbeat = isPlainRecord(normalizedRuntimeConfig.heartbeat)
|
|
? { ...normalizedRuntimeConfig.heartbeat }
|
|
: {};
|
|
if (parseFiniteNumberLike(heartbeat.maxConcurrentRuns) == null) {
|
|
heartbeat.maxConcurrentRuns = AGENT_DEFAULT_MAX_CONCURRENT_RUNS;
|
|
}
|
|
normalizedRuntimeConfig.heartbeat = heartbeat;
|
|
return normalizedRuntimeConfig;
|
|
}
|
|
|
|
export function diffConfigSnapshot(
|
|
before: AgentConfigSnapshot,
|
|
after: AgentConfigSnapshot,
|
|
): string[] {
|
|
return CONFIG_REVISION_FIELDS.filter((field) => !jsonEqual(before[field], after[field]));
|
|
}
|
|
|
|
export function configPatchFromSnapshot(snapshot: unknown): Partial<typeof agents.$inferInsert> {
|
|
if (!isPlainRecord(snapshot)) throw unprocessable("Invalid revision snapshot");
|
|
|
|
if (typeof snapshot.name !== "string" || snapshot.name.length === 0) {
|
|
throw unprocessable("Invalid revision snapshot: name");
|
|
}
|
|
if (typeof snapshot.role !== "string" || snapshot.role.length === 0) {
|
|
throw unprocessable("Invalid revision snapshot: role");
|
|
}
|
|
if (typeof snapshot.adapterType !== "string" || snapshot.adapterType.length === 0) {
|
|
throw unprocessable("Invalid revision snapshot: adapterType");
|
|
}
|
|
if (typeof snapshot.budgetMonthlyCents !== "number" || !Number.isFinite(snapshot.budgetMonthlyCents)) {
|
|
throw unprocessable("Invalid revision snapshot: budgetMonthlyCents");
|
|
}
|
|
const runtimeConfig = agentRuntimeConfigSchema.safeParse(
|
|
isPlainRecord(snapshot.runtimeConfig) ? snapshot.runtimeConfig : {},
|
|
);
|
|
if (!runtimeConfig.success) {
|
|
throw unprocessable("Invalid revision snapshot: runtimeConfig");
|
|
}
|
|
|
|
return {
|
|
name: snapshot.name,
|
|
role: snapshot.role,
|
|
title: typeof snapshot.title === "string" || snapshot.title === null ? snapshot.title : null,
|
|
reportsTo:
|
|
typeof snapshot.reportsTo === "string" || snapshot.reportsTo === null ? snapshot.reportsTo : null,
|
|
capabilities:
|
|
typeof snapshot.capabilities === "string" || snapshot.capabilities === null
|
|
? snapshot.capabilities
|
|
: null,
|
|
adapterType: snapshot.adapterType,
|
|
adapterConfig: isPlainRecord(snapshot.adapterConfig) ? snapshot.adapterConfig : {},
|
|
runtimeConfig: runtimeConfig.data,
|
|
defaultEnvironmentId:
|
|
typeof snapshot.defaultEnvironmentId === "string" || snapshot.defaultEnvironmentId === null
|
|
? snapshot.defaultEnvironmentId
|
|
: null,
|
|
budgetMonthlyCents: Math.max(0, Math.floor(snapshot.budgetMonthlyCents)),
|
|
metadata: isPlainRecord(snapshot.metadata) || snapshot.metadata === null ? snapshot.metadata : null,
|
|
};
|
|
}
|
|
|
|
export function hasAgentShortnameCollision(
|
|
candidateName: string,
|
|
existingAgents: AgentShortnameRow[],
|
|
options?: AgentShortnameCollisionOptions,
|
|
): boolean {
|
|
const candidateShortname = normalizeAgentUrlKey(candidateName);
|
|
if (!candidateShortname) return false;
|
|
|
|
return existingAgents.some((agent) => {
|
|
if (agent.status === "terminated") return false;
|
|
if (options?.excludeAgentId && agent.id === options.excludeAgentId) return false;
|
|
return normalizeAgentUrlKey(agent.name) === candidateShortname;
|
|
});
|
|
}
|
|
|
|
export function deduplicateAgentName(
|
|
candidateName: string,
|
|
existingAgents: AgentShortnameRow[],
|
|
): string {
|
|
if (!hasAgentShortnameCollision(candidateName, existingAgents)) {
|
|
return candidateName;
|
|
}
|
|
for (let i = 2; i <= 100; i++) {
|
|
const suffixed = `${candidateName} ${i}`;
|
|
if (!hasAgentShortnameCollision(suffixed, existingAgents)) {
|
|
return suffixed;
|
|
}
|
|
}
|
|
return `${candidateName} ${Date.now()}`;
|
|
}
|
|
|
|
export function agentRecordQueries(db: Db) {
|
|
function currentUtcMonthWindow(now = new Date()) {
|
|
const year = now.getUTCFullYear();
|
|
const month = now.getUTCMonth();
|
|
return {
|
|
start: new Date(Date.UTC(year, month, 1, 0, 0, 0, 0)),
|
|
end: new Date(Date.UTC(year, month + 1, 1, 0, 0, 0, 0)),
|
|
};
|
|
}
|
|
|
|
function withUrlKey<T extends { id: string; name: string }>(row: T) {
|
|
return {
|
|
...row,
|
|
urlKey: normalizeAgentUrlKey(row.name) ?? row.id,
|
|
};
|
|
}
|
|
|
|
function normalizeAgentBaseRow(row: typeof agents.$inferSelect) {
|
|
// The harness verification digest is server-only reuse state, never an API field.
|
|
const { lifecycleOperation, lifecycleRequiredPluginIds, harnessVerifiedDigest, harnessVerifiedAt, ...publicRow } = row;
|
|
return withUrlKey({
|
|
...publicRow,
|
|
permissions: normalizeAgentPermissions(row.permissions, { role: row.role }),
|
|
});
|
|
}
|
|
|
|
function toEligibilityAgent(row: Pick<typeof agents.$inferSelect, "id" | "companyId" | "name" | "status" | "reportsTo">): AgentEligibilityAgent {
|
|
return {
|
|
id: row.id,
|
|
companyId: row.companyId,
|
|
name: row.name,
|
|
status: row.status,
|
|
reportsTo: row.reportsTo,
|
|
};
|
|
}
|
|
|
|
function normalizeAgentRows(rows: (typeof agents.$inferSelect)[], allCompanyRows: AgentEligibilityRow[] = rows) {
|
|
const eligibilityAgents = allCompanyRows.map(toEligibilityAgent);
|
|
return rows.map((row) => {
|
|
const base = normalizeAgentBaseRow(row);
|
|
const appearance = resolveAgentAppearance(row.appearance, row.id);
|
|
return {
|
|
...base,
|
|
appearance,
|
|
avatarUrl: agentAvatarUrl(appearance),
|
|
orgChainHealth: getAgentWorkEligibility({
|
|
agent: toEligibilityAgent(row),
|
|
agents: eligibilityAgents,
|
|
}).orgChainHealth,
|
|
};
|
|
});
|
|
}
|
|
|
|
function normalizeAgentRow(row: typeof agents.$inferSelect, allCompanyRows?: AgentEligibilityRow[]) {
|
|
return normalizeAgentRows([row], allCompanyRows)[0]!;
|
|
}
|
|
|
|
async function listCompanyAgentRows(companyId: string) {
|
|
return db.select().from(agents).where(eq(agents.companyId, companyId));
|
|
}
|
|
|
|
async function listCompanyAgentEligibilityRows(companyId: string): Promise<AgentEligibilityRow[]> {
|
|
return db.select({ id: agents.id, companyId: agents.companyId, name: agents.name,
|
|
status: agents.status, reportsTo: agents.reportsTo }).from(agents).where(eq(agents.companyId, companyId));
|
|
}
|
|
|
|
async function getMonthlySpendByAgentIds(companyId: string, agentIds: string[]) {
|
|
if (agentIds.length === 0) return new Map<string, number>();
|
|
const { start, end } = currentUtcMonthWindow();
|
|
const rows = await db
|
|
.select({
|
|
agentId: costEvents.agentId,
|
|
spentMonthlyCents: sql<number>`coalesce(sum(${costEvents.costCents}), 0)::double precision`,
|
|
})
|
|
.from(costEvents)
|
|
.where(
|
|
and(
|
|
eq(costEvents.companyId, companyId),
|
|
inArray(costEvents.agentId, agentIds),
|
|
gte(costEvents.occurredAt, start),
|
|
lt(costEvents.occurredAt, end),
|
|
),
|
|
)
|
|
.groupBy(costEvents.agentId);
|
|
return new Map(rows.map((row) => [row.agentId, Number(row.spentMonthlyCents ?? 0)]));
|
|
}
|
|
|
|
async function hydrateAgentSpend<T extends { id: string; companyId: string; spentMonthlyCents: number }>(rows: T[]) {
|
|
const agentIds = rows.map((row) => row.id);
|
|
const companyId = rows[0]?.companyId;
|
|
if (!companyId || agentIds.length === 0) return rows;
|
|
const spendByAgentId = await getMonthlySpendByAgentIds(companyId, agentIds);
|
|
return rows.map((row) => ({
|
|
...row,
|
|
spentMonthlyCents: spendByAgentId.get(row.id) ?? 0,
|
|
}));
|
|
}
|
|
|
|
async function getById(id: string) {
|
|
const row = await db
|
|
.select()
|
|
.from(agents)
|
|
.where(eq(agents.id, id))
|
|
.then((rows) => rows[0] ?? null);
|
|
if (!row) return null;
|
|
const [chainRows, hydrated] = await Promise.all([
|
|
readAgentReportingChain(db, row),
|
|
hydrateAgentSpend([row]).then((rows) => rows[0]!),
|
|
]);
|
|
return normalizeAgentRow(hydrated, chainRows);
|
|
}
|
|
|
|
async function ensureManager(companyId: string, managerId: string) {
|
|
const manager = await getById(managerId);
|
|
if (!manager) throw notFound("Manager not found");
|
|
if (manager.companyId !== companyId) {
|
|
throw unprocessable("Manager must belong to same company");
|
|
}
|
|
return manager;
|
|
}
|
|
|
|
async function assertNoCycle(agentId: string, reportsTo: string | null | undefined) {
|
|
if (!reportsTo) return;
|
|
if (reportsTo === agentId) throw unprocessable("Agent cannot report to itself");
|
|
|
|
let cursor: string | null = reportsTo;
|
|
while (cursor) {
|
|
if (cursor === agentId) throw unprocessable("Reporting relationship would create cycle");
|
|
const next = await getById(cursor);
|
|
cursor = next?.reportsTo ?? null;
|
|
}
|
|
}
|
|
|
|
async function assertCompanyShortnameAvailable(
|
|
companyId: string,
|
|
candidateName: string,
|
|
options?: AgentShortnameCollisionOptions,
|
|
) {
|
|
const candidateShortname = normalizeAgentUrlKey(candidateName);
|
|
if (!candidateShortname) return;
|
|
|
|
const existingAgents = await db
|
|
.select({
|
|
id: agents.id,
|
|
name: agents.name,
|
|
status: agents.status,
|
|
})
|
|
.from(agents)
|
|
.where(eq(agents.companyId, companyId));
|
|
|
|
const hasCollision = hasAgentShortnameCollision(candidateName, existingAgents, options);
|
|
if (hasCollision) {
|
|
throw conflict(
|
|
`Agent shortname '${candidateShortname}' is already in use in this company`,
|
|
);
|
|
}
|
|
}
|
|
|
|
function assertBuiltInAgentMetadataMutationAllowed(
|
|
beforeMetadata: unknown,
|
|
afterMetadata: unknown,
|
|
options?: { allowBuiltInAgentMetadata?: boolean },
|
|
) {
|
|
if (options?.allowBuiltInAgentMetadata) return;
|
|
const beforeMarker = readBuiltInAgentMarker(beforeMetadata);
|
|
const afterMarker = readBuiltInAgentMarker(afterMetadata);
|
|
if (builtInAgentMarkersEqual(beforeMarker, afterMarker)) return;
|
|
throw conflict("Built-in agent marker is managed by Paperclip and cannot be edited directly", {
|
|
code: "built_in_agent_marker_readonly",
|
|
key: beforeMarker?.key ?? afterMarker?.key ?? null,
|
|
});
|
|
}
|
|
|
|
return { normalizeAgentRows, normalizeAgentRow, listCompanyAgentRows, listCompanyAgentEligibilityRows, hydrateAgentSpend,
|
|
getById, ensureManager, assertNoCycle, assertCompanyShortnameAvailable, assertBuiltInAgentMetadataMutationAllowed };
|
|
}
|