mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
[codex] Add built-in agents and Reflection Coach bundle (#9206)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Operators need first-party agent capabilities for repeatable company work, not just manually created one-off agents. > - Built-in agents need to behave like normal company-scoped agents while preserving approval gates, permissions, budgets, and audit trails. > - Reflection and coaching work also needs bundled instructions, skill content, and a routine so the feature can be installed and reset predictably. > - The API, database, UI, portability, and tests all need to agree on the built-in lifecycle from not provisioned through setup, approval, ready, paused, and reset. > - This pull request adds built-in agent provisioning and the Reflection Coach bundle end-to-end. > - The benefit is a safer first-party path for Paperclip-managed agents without bypassing the same governance model used for operator-created agents. ## Linked Issues or Issue Description No public GitHub issue was found for this exact built-in agent and Reflection Coach bundle work. Problem/motivation: - Paperclip did not have a first-party built-in agent lifecycle for product-owned agents. - Bundled agent resources such as default instructions, skills, and routines needed managed ownership and reset semantics. - Approval-gated companies needed built-in setup to preserve requested adapter, budget, manager, and permission state through board approval. - The board UI needed clear built-in badges, setup affordances, readiness state, and bundle status without exposing secrets. Proposed solution: - Add a company-scoped built-in agent registry, provisioning/reset/reconcile/status APIs, and Reflection Coach bundled resources. - Track bundled managed resources in the database with idempotent migration behavior. - Reuse existing agent approval, authorization, budget, and activity-log paths instead of creating a bypass. - Add UI setup, badges, gates, bundle panels, and route coverage for built-in agents. Duplicate search: - Searched GitHub PRs for `built-in agents Reflection Coach repo:paperclipai/paperclip`; only this PR was returned. - Searched GitHub issues for the same query; no public issues were returned. ## What Changed - Added built-in agent definitions, lifecycle state derivation, provisioning, reset, reconcile, status, and routine-control routes. - Added the `built_in_managed_resources` migration and schema exports for bundled instructions, skill, and routine ownership. - Added the Reflection Coach built-in bundle with default instructions, skill catalog content, routine template, default permissions, and managed-resource drift handling. - Added approval-aware provisioning behavior that preserves requested adapter config, budgets, manager assignment, and built-in permissions through hire approval. - Added authorization and mutation gates for built-in agent and skill changes, including consented Reflection Coach change paths. - Added UI surfaces for built-in agent setup, roster/detail badges, readiness gates, bundle status, routine controls, and route filtering. - Added company import/export and validator coverage for built-in managed resources and low-trust/red-team presets. - Addressed Greptile follow-ups for pending approval reconciliation, consent-gate error propagation, config-read authorization fallback, approval-path manager preservation, and non-model adapter provisioning. ## Verification Local verification: - `git diff --check public/master..HEAD` passed. - `pnpm check:token-gates` passed with all gates clean. - `pnpm exec vitest run ui/src/components/ConfigureBuiltInAgentModal.test.tsx` passed: 1 file, 4 tests. - `pnpm exec vitest run ui/src/components/EntityRow.test.tsx ui/src/pages/Agents.test.tsx ui/src/components/BuiltInAgentGate.test.tsx ui/src/components/ConfigureBuiltInAgentModal.test.tsx ui/src/components/BuiltInBundlePanel.test.tsx ui/src/pages/InstanceExperimentalSettings.test.tsx ui/src/pages/Routines.test.tsx` passed: 7 files, 64 tests. - `pnpm --filter @paperclipai/server exec vitest run src/__tests__/built-in-agents.test.ts src/__tests__/authorization-service.test.ts src/__tests__/company-skills-routes.test.ts` passed: 3 files, 91 tests. - `pnpm --filter @paperclipai/db check:migrations` passed. - `pnpm -r typecheck` passed after the rebase; `pnpm --filter ui typecheck` passed after the final UI review fix. Remote verification on latest head `1c61f693a4ec881d739022b0e75a8ca8bf8c2cd8`: - Merge state: `CLEAN`. - Greptile: `5/5`, zero unresolved Greptile threads. - PR check rollup: all checks successful, neutral, or skipped as expected. - Passing gates include Build, Typecheck + Release Registry, all server shards, all workspace shards, all serialized server suites, e2e, Canary Dry Run, policy, review, verify, Socket, Superagent, and Snyk. ## Risks - This adds a new managed-resource table and migration; the migration uses idempotent create/add/index guards and passed migration safety checks. - Built-in agent provisioning touches approval and authorization paths; tests cover pending approval preservation, stale retry rejection, consent gates, and config-read fallback behavior. - Reflection Coach creates managed instructions, skill, and routine resources; drift/reset behavior is covered by service tests and redacted API responses. - Non-model adapter setup now provisions a `needs_setup` built-in row before command/endpoint fields are complete; this matches the server lifecycle and is covered by the setup modal regression test. ## Model Used OpenAI Codex coding agent based on GPT-5. Exact hosted model ID, context-window size, and reasoning-mode labels are not exposed in this runtime; tool use, shell execution, GitHub CLI/API access, and local code editing were enabled. ## 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>
This commit is contained in:
1 parent
53d09d4c34
commit
8b6a06ee25
99 files changed
+10109
-310
No files matched your search
@@ -30,6 +30,10 @@ import { syncAgentAdapterEnvBindings } from "./agent-secret-bindings.js";
|
||||
import { normalizeAgentPermissions } from "./agent-permissions.js";
|
||||
import { REDACTED_EVENT_VALUE, sanitizeRecord } from "../redaction.js";
|
||||
import { secretService } from "./secrets.js";
|
||||
import {
|
||||
builtInAgentMarkersEqual,
|
||||
readBuiltInAgentMarker,
|
||||
} from "./built-in-agent-metadata.js";
|
||||
|
||||
function hashToken(token: string) {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
@@ -43,6 +47,7 @@ const CONFIG_REVISION_FIELDS = [
|
||||
"name",
|
||||
"role",
|
||||
"title",
|
||||
"icon",
|
||||
"reportsTo",
|
||||
"capabilities",
|
||||
"adapterType",
|
||||
@@ -65,6 +70,12 @@ interface RevisionMetadata {
|
||||
|
||||
interface UpdateAgentOptions {
|
||||
recordRevision?: RevisionMetadata;
|
||||
allowBuiltInAgentMetadata?: boolean;
|
||||
allowPendingApprovalConfigUpdate?: boolean;
|
||||
}
|
||||
|
||||
interface CreateAgentOptions {
|
||||
allowBuiltInAgentMetadata?: boolean;
|
||||
}
|
||||
|
||||
interface AgentShortnameRow {
|
||||
@@ -104,6 +115,7 @@ function buildConfigSnapshot(
|
||||
name: row.name,
|
||||
role: row.role,
|
||||
title: row.title,
|
||||
icon: row.icon,
|
||||
reportsTo: row.reportsTo,
|
||||
capabilities: row.capabilities,
|
||||
adapterType: row.adapterType,
|
||||
@@ -126,6 +138,50 @@ function hasConfigPatchFields(data: Partial<typeof agents.$inferInsert>) {
|
||||
return CONFIG_REVISION_FIELDS.some((field) => Object.prototype.hasOwnProperty.call(data, field));
|
||||
}
|
||||
|
||||
function changedPendingApprovalConfigFields(
|
||||
existing: typeof agents.$inferSelect,
|
||||
data: Partial<typeof agents.$inferInsert>,
|
||||
) {
|
||||
return CONFIG_REVISION_FIELDS.filter((field) =>
|
||||
Object.prototype.hasOwnProperty.call(data, field) && !jsonEqual(data[field], existing[field]),
|
||||
);
|
||||
}
|
||||
|
||||
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 (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;
|
||||
@@ -390,6 +446,21 @@ export function agentService(db: Db) {
|
||||
});
|
||||
}
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
async function updateAgent(
|
||||
id: string,
|
||||
data: Partial<typeof agents.$inferInsert>,
|
||||
@@ -409,6 +480,16 @@ export function agentService(db: Db) {
|
||||
) {
|
||||
throw conflict("Pending approval agents cannot be activated directly");
|
||||
}
|
||||
if (existing.status === "pending_approval" && !options?.allowPendingApprovalConfigUpdate) {
|
||||
const changedFields = changedPendingApprovalConfigFields(existing as typeof agents.$inferSelect, data);
|
||||
if (changedFields.length > 0) {
|
||||
throw conflict("Pending approval agent configuration cannot be changed before board approval", {
|
||||
code: "pending_approval_agent_config_frozen",
|
||||
agentId: id,
|
||||
fields: changedFields,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (data.reportsTo !== undefined) {
|
||||
if (data.reportsTo) {
|
||||
@@ -425,6 +506,10 @@ export function agentService(db: Db) {
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(data, "metadata")) {
|
||||
assertBuiltInAgentMetadataMutationAllowed(existing.metadata, data.metadata, options);
|
||||
}
|
||||
|
||||
const normalizedPatch = { ...data } as Partial<typeof agents.$inferInsert>;
|
||||
if (data.permissions !== undefined) {
|
||||
const role = (data.role ?? existing.role) as string;
|
||||
@@ -501,7 +586,8 @@ export function agentService(db: Db) {
|
||||
|
||||
getById,
|
||||
|
||||
create: async (companyId: string, data: Omit<typeof agents.$inferInsert, "companyId">) => {
|
||||
create: async (companyId: string, data: Omit<typeof agents.$inferInsert, "companyId">, options?: CreateAgentOptions) => {
|
||||
assertBuiltInAgentMetadataMutationAllowed(null, data.metadata, options);
|
||||
if (data.reportsTo) {
|
||||
await ensureManager(companyId, data.reportsTo);
|
||||
}
|
||||
@@ -645,6 +731,14 @@ export function agentService(db: Db) {
|
||||
remove: async (id: string) => {
|
||||
const existing = await getById(id);
|
||||
if (!existing) return null;
|
||||
const builtInMarker = readBuiltInAgentMarker(existing.metadata);
|
||||
if (builtInMarker) {
|
||||
throw conflict("Built-in agents cannot be deleted; pause them instead", {
|
||||
code: "built_in_agent_undeletable",
|
||||
key: builtInMarker.key,
|
||||
featureKeys: builtInMarker.featureKeys,
|
||||
});
|
||||
}
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
await tx.update(agents).set({ reportsTo: null }).where(eq(agents.reportsTo, id));
|
||||
@@ -675,12 +769,32 @@ export function agentService(db: Db) {
|
||||
});
|
||||
},
|
||||
|
||||
activatePendingApproval: async (id: string) => {
|
||||
activatePendingApproval: async (id: string, approvedPayload?: Record<string, unknown> | null) => {
|
||||
const activatedAgent = await db.transaction(async (tx) => {
|
||||
const txDb = tx as unknown as Db;
|
||||
const existing = await agentService(txDb).getById(id);
|
||||
if (!existing || existing.status !== "pending_approval") return null;
|
||||
const approvedPatch = approvedPayload ? configPatchFromApprovalPayload(approvedPayload) : {};
|
||||
let patch = { ...approvedPatch } as Partial<typeof agents.$inferInsert>;
|
||||
if (
|
||||
Object.prototype.hasOwnProperty.call(patch, "adapterConfig") &&
|
||||
isPlainRecord(patch.adapterConfig)
|
||||
) {
|
||||
patch.adapterConfig = await secretService(txDb).normalizeAdapterConfigForPersistence(
|
||||
existing.companyId,
|
||||
patch.adapterConfig,
|
||||
{ adapterType: (patch.adapterType ?? existing.adapterType) as string },
|
||||
);
|
||||
}
|
||||
if (patch.permissions !== undefined) {
|
||||
patch.permissions = normalizeAgentPermissions(
|
||||
patch.permissions,
|
||||
(patch.role ?? existing.role) as string,
|
||||
);
|
||||
}
|
||||
const updated = await tx
|
||||
.update(agents)
|
||||
.set({ status: "idle", updatedAt: new Date() })
|
||||
.set({ ...patch, status: "idle", updatedAt: new Date() })
|
||||
.where(and(eq(agents.id, id), eq(agents.status, "pending_approval")))
|
||||
.returning()
|
||||
.then((rows) => rows[0] ?? null);
|
||||
@@ -704,6 +818,13 @@ export function agentService(db: Db) {
|
||||
updatePermissions: async (id: string, permissions: Record<string, unknown> & { canCreateAgents: boolean }) => {
|
||||
const existing = await getById(id);
|
||||
if (!existing) return null;
|
||||
if (existing.status === "pending_approval") {
|
||||
throw conflict("Pending approval agent permissions cannot be changed before board approval", {
|
||||
code: "pending_approval_agent_config_frozen",
|
||||
agentId: id,
|
||||
fields: ["permissions"],
|
||||
});
|
||||
}
|
||||
|
||||
const updated = await db
|
||||
.update(agents)
|
||||
|
||||
@@ -24,6 +24,13 @@ export function approvalService(db: Db) {
|
||||
};
|
||||
}
|
||||
|
||||
async function reconcileApprovedBuiltInAgent(companyId: string, payload: Record<string, unknown>) {
|
||||
const sourceBuiltInAgentKey = typeof payload.sourceBuiltInAgentKey === "string" ? payload.sourceBuiltInAgentKey : null;
|
||||
if (!sourceBuiltInAgentKey) return;
|
||||
const { builtInAgentService } = await import("./built-in-agents.js");
|
||||
await builtInAgentService(db).ensure(companyId, sourceBuiltInAgentKey);
|
||||
}
|
||||
|
||||
async function getExistingApproval(id: string) {
|
||||
const existing = await db
|
||||
.select()
|
||||
@@ -128,7 +135,8 @@ export function approvalService(db: Db) {
|
||||
const payload = updated.payload as Record<string, unknown>;
|
||||
const payloadAgentId = typeof payload.agentId === "string" ? payload.agentId : null;
|
||||
if (payloadAgentId) {
|
||||
await agentsSvc.activatePendingApproval(payloadAgentId);
|
||||
await agentsSvc.activatePendingApproval(payloadAgentId, payload);
|
||||
await reconcileApprovedBuiltInAgent(updated.companyId, payload);
|
||||
hireApprovedAgentId = payloadAgentId;
|
||||
} else {
|
||||
const created = await agentsSvc.create(updated.companyId, {
|
||||
|
||||
@@ -56,6 +56,7 @@ export type AuthorizationAction =
|
||||
| PermissionKey
|
||||
| "agent_config:read"
|
||||
| "agent_config:update"
|
||||
| "skill_config:update"
|
||||
| "agent:read"
|
||||
| "agent:wake"
|
||||
| "company_scope:read"
|
||||
@@ -93,6 +94,8 @@ export type AuthorizationDecision = {
|
||||
| "allow_local_board"
|
||||
| "allow_instance_admin"
|
||||
| "allow_explicit_grant"
|
||||
| "allow_direct_change"
|
||||
| "allow_consented_change"
|
||||
| "allow_legacy_agent_creator"
|
||||
| "allow_issue_mention_grant"
|
||||
| "allow_self"
|
||||
@@ -104,6 +107,8 @@ export type AuthorizationDecision = {
|
||||
| "deny_company_boundary"
|
||||
| "deny_missing_membership"
|
||||
| "deny_missing_grant"
|
||||
| "deny_missing_consent"
|
||||
| "deny_no_grant"
|
||||
| "deny_policy_restricted"
|
||||
| "deny_low_trust_boundary"
|
||||
| "deny_scope"
|
||||
@@ -125,7 +130,9 @@ function companyIdForResource(resource: AuthorizationResource) {
|
||||
}
|
||||
|
||||
function permissionForAction(action: AuthorizationAction): PermissionKey | null {
|
||||
if (action === "agent_config:read" || action === "agent_config:update") return "agents:create";
|
||||
if (action === "agent_config:read" || action === "agent_config:update" || action === "skill_config:update") {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
action === "agent:read" ||
|
||||
action === "agent:wake" ||
|
||||
@@ -466,6 +473,10 @@ function activeResponsibleUserCanAuthorizeIssueAction(
|
||||
);
|
||||
}
|
||||
|
||||
function scopeBoolean(scope: Record<string, unknown> | null | undefined, key: string) {
|
||||
return scope?.[key] === true;
|
||||
}
|
||||
|
||||
export function authorizationDeniedDetails(decision: AuthorizationDecision) {
|
||||
return {
|
||||
...(decision.code ? { code: decision.code } : {}),
|
||||
@@ -878,6 +889,9 @@ export function authorizationService(db: Db) {
|
||||
|
||||
if (
|
||||
input.action === "company_scope:read" ||
|
||||
input.action === "agent_config:read" ||
|
||||
input.action === "agent_config:update" ||
|
||||
input.action === "skill_config:update" ||
|
||||
input.action === "runtime:manage" ||
|
||||
input.action === "secrets:read"
|
||||
) {
|
||||
@@ -1305,6 +1319,94 @@ export function authorizationService(db: Db) {
|
||||
return broadDecision;
|
||||
}
|
||||
|
||||
async function decideWithAgentConfigReadGrant(
|
||||
principalType: PrincipalType,
|
||||
principalId: string,
|
||||
): Promise<AuthorizationDecision> {
|
||||
const configureDecision = await decidePrincipalGrant({
|
||||
companyId,
|
||||
principalType,
|
||||
principalId,
|
||||
action: input.action,
|
||||
permissionKey: "agents:configure",
|
||||
scope: input.scope,
|
||||
});
|
||||
if (configureDecision.allowed || configureDecision.reason === "deny_missing_membership") {
|
||||
return configureDecision;
|
||||
}
|
||||
|
||||
const suggestDecision = await decidePrincipalGrant({
|
||||
companyId,
|
||||
principalType,
|
||||
principalId,
|
||||
action: input.action,
|
||||
permissionKey: "agents:suggest-changes",
|
||||
scope: input.scope,
|
||||
});
|
||||
if (suggestDecision.allowed || suggestDecision.reason === "deny_missing_grant") {
|
||||
return suggestDecision;
|
||||
}
|
||||
return configureDecision;
|
||||
}
|
||||
|
||||
async function decideWithProtectedChangeGrants(
|
||||
principalType: PrincipalType,
|
||||
principalId: string,
|
||||
keys: { direct: PermissionKey; suggest: PermissionKey },
|
||||
): Promise<AuthorizationDecision> {
|
||||
const directDecision = await decidePrincipalGrant({
|
||||
companyId,
|
||||
principalType,
|
||||
principalId,
|
||||
action: input.action,
|
||||
permissionKey: keys.direct,
|
||||
scope: input.scope,
|
||||
});
|
||||
if (directDecision.allowed) {
|
||||
return allow({
|
||||
action: input.action,
|
||||
reason: "allow_direct_change",
|
||||
explanation: `Allowed by direct change permission ${keys.direct}.`,
|
||||
grant: directDecision.grant,
|
||||
});
|
||||
}
|
||||
if (directDecision.reason === "deny_missing_membership") return directDecision;
|
||||
|
||||
const suggestDecision = await decidePrincipalGrant({
|
||||
companyId,
|
||||
principalType,
|
||||
principalId,
|
||||
action: input.action,
|
||||
permissionKey: keys.suggest,
|
||||
scope: input.scope,
|
||||
});
|
||||
if (suggestDecision.allowed) {
|
||||
if (scopeBoolean(input.scope, "consentedChange")) {
|
||||
return allow({
|
||||
action: input.action,
|
||||
reason: "allow_consented_change",
|
||||
explanation: `Allowed by suggest permission ${keys.suggest} after accepted change consent.`,
|
||||
grant: suggestDecision.grant,
|
||||
});
|
||||
}
|
||||
return deny({
|
||||
action: input.action,
|
||||
reason: "deny_missing_consent",
|
||||
explanation: `Permission ${keys.suggest} requires accepted change consent before applying this mutation.`,
|
||||
grant: suggestDecision.grant,
|
||||
});
|
||||
}
|
||||
if (suggestDecision.reason === "deny_missing_membership") return suggestDecision;
|
||||
if (directDecision.reason === "deny_scope") return directDecision;
|
||||
if (suggestDecision.reason === "deny_scope") return suggestDecision;
|
||||
|
||||
return deny({
|
||||
action: input.action,
|
||||
reason: "deny_no_grant",
|
||||
explanation: `Missing permission: ${keys.direct} or ${keys.suggest}.`,
|
||||
});
|
||||
}
|
||||
|
||||
async function denyForAssignmentPolicyIfNeeded(
|
||||
policyEffect: AssignmentPolicyEffect,
|
||||
): Promise<AuthorizationDecision | null> {
|
||||
@@ -1465,6 +1567,21 @@ export function authorizationService(db: Db) {
|
||||
if (policyEffect.kind === "restricted") return denyRestrictedAssignmentPolicy(policyEffect);
|
||||
return grantDecision;
|
||||
}
|
||||
if (input.action === "agent_config:read") {
|
||||
return decideWithAgentConfigReadGrant("user", input.actor.userId);
|
||||
}
|
||||
if (input.action === "agent_config:update") {
|
||||
return decideWithProtectedChangeGrants("user", input.actor.userId, {
|
||||
direct: "agents:configure",
|
||||
suggest: "agents:suggest-changes",
|
||||
});
|
||||
}
|
||||
if (input.action === "skill_config:update") {
|
||||
return decideWithProtectedChangeGrants("user", input.actor.userId, {
|
||||
direct: "skills:create",
|
||||
suggest: "skills:suggest-changes",
|
||||
});
|
||||
}
|
||||
return decidePrincipalGrant({
|
||||
companyId,
|
||||
principalType: "user",
|
||||
@@ -1641,7 +1758,8 @@ export function authorizationService(db: Db) {
|
||||
if (
|
||||
input.action === "agent_config:update" &&
|
||||
input.resource.type === "agent" &&
|
||||
input.resource.agentId === actorAgentId
|
||||
input.resource.agentId === actorAgentId &&
|
||||
!scopeBoolean(input.scope, "requiresChangeGrant")
|
||||
) {
|
||||
return allow({
|
||||
action: input.action,
|
||||
@@ -1650,6 +1768,31 @@ export function authorizationService(db: Db) {
|
||||
});
|
||||
}
|
||||
|
||||
if (input.action === "agent_config:read") {
|
||||
if (input.resource.type === "agent" && input.resource.agentId === actorAgentId) {
|
||||
return allow({
|
||||
action: input.action,
|
||||
reason: "allow_self",
|
||||
explanation: "Allowed because the actor is reading its own agent configuration.",
|
||||
});
|
||||
}
|
||||
return decideWithAgentConfigReadGrant("agent", actorAgentId);
|
||||
}
|
||||
|
||||
if (input.action === "agent_config:update") {
|
||||
return decideWithProtectedChangeGrants("agent", actorAgentId, {
|
||||
direct: "agents:configure",
|
||||
suggest: "agents:suggest-changes",
|
||||
});
|
||||
}
|
||||
|
||||
if (input.action === "skill_config:update") {
|
||||
return decideWithProtectedChangeGrants("agent", actorAgentId, {
|
||||
direct: "skills:create",
|
||||
suggest: "skills:suggest-changes",
|
||||
});
|
||||
}
|
||||
|
||||
if (permissionKey) {
|
||||
const grantDecision = await decidePrincipalGrant({
|
||||
companyId,
|
||||
@@ -1664,8 +1807,6 @@ export function authorizationService(db: Db) {
|
||||
|
||||
if (
|
||||
(input.action === "agents:create" ||
|
||||
input.action === "agent_config:read" ||
|
||||
input.action === "agent_config:update" ||
|
||||
input.action === "tasks:manage_active_checkouts") &&
|
||||
canCreateAgentsLegacy(actorAgent)
|
||||
) {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
export const BUILT_IN_AGENT_METADATA_KEY = "paperclipBuiltInAgent";
|
||||
|
||||
export interface BuiltInAgentMarker {
|
||||
key: string;
|
||||
featureKeys: string[];
|
||||
}
|
||||
|
||||
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function normalizeFeatureKeys(value: unknown): string[] | null {
|
||||
if (!Array.isArray(value)) return null;
|
||||
const featureKeys = value.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0);
|
||||
return featureKeys.length === value.length ? featureKeys : null;
|
||||
}
|
||||
|
||||
export function readBuiltInAgentMarker(metadata: unknown): BuiltInAgentMarker | null {
|
||||
if (!isPlainRecord(metadata)) return null;
|
||||
const marker = metadata[BUILT_IN_AGENT_METADATA_KEY];
|
||||
if (!isPlainRecord(marker)) return null;
|
||||
const key = marker.key;
|
||||
const featureKeys = normalizeFeatureKeys(marker.featureKeys);
|
||||
if (typeof key !== "string" || key.trim().length === 0 || !featureKeys) return null;
|
||||
return { key, featureKeys };
|
||||
}
|
||||
|
||||
export function withBuiltInAgentMarker(
|
||||
metadata: Record<string, unknown> | null | undefined,
|
||||
marker: BuiltInAgentMarker,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
...(metadata ?? {}),
|
||||
[BUILT_IN_AGENT_METADATA_KEY]: {
|
||||
key: marker.key,
|
||||
featureKeys: [...marker.featureKeys],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function builtInAgentMarkersEqual(left: BuiltInAgentMarker | null, right: BuiltInAgentMarker | null) {
|
||||
if (!left && !right) return true;
|
||||
if (!left || !right) return false;
|
||||
return left.key === right.key && JSON.stringify(left.featureKeys) === JSON.stringify(right.featureKeys);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,232 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { issueThreadInteractions } from "@paperclipai/db";
|
||||
import { and, desc, eq, or, sql } from "drizzle-orm";
|
||||
import type { RequestConfirmationPayload, RequestConfirmationResult } from "@paperclipai/shared";
|
||||
import { forbidden } from "../errors.js";
|
||||
|
||||
export const AGENT_PROFILE_CHANGE_CONSENT_FIELDS = ["name", "role", "title", "capabilities"] as const;
|
||||
|
||||
type ConsumedRequestConfirmationResult = RequestConfirmationResult & {
|
||||
consumedAt?: string | null;
|
||||
consumedByRunId?: string | null;
|
||||
};
|
||||
|
||||
export function agentInstructionsChangeTargetKey(agentId: string) {
|
||||
return `agent:${agentId}:instructions`;
|
||||
}
|
||||
|
||||
export function agentProfileChangeTargetKey(agentId: string) {
|
||||
return `agent:${agentId}:profile`;
|
||||
}
|
||||
|
||||
export function skillChangeTargetKey(skillId: string) {
|
||||
return `skill:${skillId}`;
|
||||
}
|
||||
|
||||
export function skillSlugChangeTargetKey(slug: string) {
|
||||
return `skill-slug:${slug}`;
|
||||
}
|
||||
|
||||
export function skillImportChangeTargetKey(source: string) {
|
||||
return `skill-import:${source}`;
|
||||
}
|
||||
|
||||
export function skillsScanProjectsChangeTargetKey() {
|
||||
return "skills:scan-projects";
|
||||
}
|
||||
|
||||
export function touchesAgentProfileChangeConsentFields(patchData: Record<string, unknown>) {
|
||||
return AGENT_PROFILE_CHANGE_CONSENT_FIELDS.some((key) =>
|
||||
Object.prototype.hasOwnProperty.call(patchData, key),
|
||||
);
|
||||
}
|
||||
|
||||
function readNonEmptyString(value: unknown) {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
||||
}
|
||||
|
||||
function payloadHasDisplayedDiff(payload: RequestConfirmationPayload) {
|
||||
const details = readNonEmptyString(payload.detailsMarkdown);
|
||||
if (!details) return false;
|
||||
if (/```diff\b/i.test(details)) return true;
|
||||
return /(^|\n)[+-][^\n]+/.test(details);
|
||||
}
|
||||
|
||||
function requestConfirmationResultConsumed(result: RequestConfirmationResult | null) {
|
||||
const consumed = result as ConsumedRequestConfirmationResult | null;
|
||||
return Boolean(readNonEmptyString(consumed?.consumedByRunId) || readNonEmptyString(consumed?.consumedAt));
|
||||
}
|
||||
|
||||
function markRequestConfirmationResultConsumed(
|
||||
result: RequestConfirmationResult,
|
||||
actorRunId: string,
|
||||
consumedAt: Date,
|
||||
): ConsumedRequestConfirmationResult {
|
||||
return {
|
||||
...result,
|
||||
consumedAt: consumedAt.toISOString(),
|
||||
consumedByRunId: actorRunId,
|
||||
};
|
||||
}
|
||||
|
||||
function legacyTargetKeysFor(targetKey: string) {
|
||||
if (targetKey.startsWith("agent:") && targetKey.endsWith(":instructions")) {
|
||||
const agentId = targetKey.slice("agent:".length, -":instructions".length);
|
||||
if (agentId) return [`reflection-coach:agent-instructions:${agentId}`];
|
||||
}
|
||||
if (targetKey.startsWith("agent:") && targetKey.endsWith(":profile")) {
|
||||
const agentId = targetKey.slice("agent:".length, -":profile".length);
|
||||
if (agentId) return [`reflection-coach:agent-description:${agentId}`];
|
||||
}
|
||||
if (targetKey.startsWith("skill:")) {
|
||||
const skillId = targetKey.slice("skill:".length);
|
||||
if (skillId) return [`reflection-coach:company-skill:${skillId}`];
|
||||
}
|
||||
if (targetKey.startsWith("skill-slug:")) {
|
||||
const slug = targetKey.slice("skill-slug:".length);
|
||||
if (slug) return [`reflection-coach:company-skill-slug:${slug}`];
|
||||
}
|
||||
if (targetKey.startsWith("skill-import:")) {
|
||||
const source = targetKey.slice("skill-import:".length);
|
||||
if (source) {
|
||||
return [
|
||||
`reflection-coach:company-skill-import:${source}`,
|
||||
`reflection-coach:company-skill-catalog:${source}`,
|
||||
];
|
||||
}
|
||||
}
|
||||
if (targetKey === "skills:scan-projects") {
|
||||
return ["reflection-coach:company-skills:scan-projects"];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function expandTargetKeysForLegacyCompatibility(targetKeys: string[]) {
|
||||
const expanded = new Set<string>();
|
||||
for (const targetKey of targetKeys) {
|
||||
expanded.add(targetKey);
|
||||
for (const legacyTargetKey of legacyTargetKeysFor(targetKey)) {
|
||||
expanded.add(legacyTargetKey);
|
||||
}
|
||||
}
|
||||
return [...expanded];
|
||||
}
|
||||
|
||||
export function changeConsentGateService(db: Db) {
|
||||
return {
|
||||
assertConsented: async (input: {
|
||||
companyId: string;
|
||||
actorAgentId: string | null | undefined;
|
||||
actorRunId: string | null | undefined;
|
||||
targetKeys: string[];
|
||||
}): Promise<boolean> => {
|
||||
const actorAgentId = readNonEmptyString(input.actorAgentId);
|
||||
if (!actorAgentId) return false;
|
||||
|
||||
const actorRunId = readNonEmptyString(input.actorRunId);
|
||||
if (!actorRunId) {
|
||||
throw forbidden("Reflection Coach mutations require a run id", {
|
||||
code: "reflection_coach_mutation_run_id_required",
|
||||
});
|
||||
}
|
||||
|
||||
const targetKeys = [...new Set(input.targetKeys.map(readNonEmptyString).filter((key): key is string => Boolean(key)))];
|
||||
if (targetKeys.length === 0) {
|
||||
throw forbidden("Reflection Coach mutation target is not gateable", {
|
||||
code: "reflection_coach_mutation_target_required",
|
||||
});
|
||||
}
|
||||
const queryTargetKeys = expandTargetKeysForLegacyCompatibility(targetKeys);
|
||||
|
||||
const targetKeyPredicate = or(
|
||||
...queryTargetKeys.map((targetKey) =>
|
||||
sql`${issueThreadInteractions.payload}->'target'->>'key' = ${targetKey}`,
|
||||
),
|
||||
);
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: issueThreadInteractions.id,
|
||||
sourceRunId: issueThreadInteractions.sourceRunId,
|
||||
payload: issueThreadInteractions.payload,
|
||||
result: issueThreadInteractions.result,
|
||||
})
|
||||
.from(issueThreadInteractions)
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.companyId, input.companyId),
|
||||
eq(issueThreadInteractions.createdByAgentId, actorAgentId),
|
||||
eq(issueThreadInteractions.kind, "request_confirmation"),
|
||||
eq(issueThreadInteractions.status, "accepted"),
|
||||
targetKeyPredicate,
|
||||
))
|
||||
.orderBy(desc(issueThreadInteractions.resolvedAt), desc(issueThreadInteractions.createdAt))
|
||||
.limit(10);
|
||||
|
||||
const accepted = rows.find((row) => {
|
||||
const payload = row.payload as RequestConfirmationPayload;
|
||||
const result = row.result as RequestConfirmationResult | null;
|
||||
return payload.target?.type === "custom"
|
||||
&& queryTargetKeys.includes(payload.target.key)
|
||||
&& result?.outcome === "accepted"
|
||||
&& !requestConfirmationResultConsumed(result)
|
||||
&& payloadHasDisplayedDiff(payload)
|
||||
&& Boolean(row.sourceRunId)
|
||||
&& row.sourceRunId !== actorRunId;
|
||||
});
|
||||
|
||||
if (!accepted) {
|
||||
throw forbidden(
|
||||
"Reflection Coach mutations require an accepted request_confirmation with a displayed diff for this target, "
|
||||
+ "created in a previous run and not already consumed.",
|
||||
{
|
||||
code: "reflection_coach_mutation_gate_required",
|
||||
targetKeys,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const acceptedResult = accepted.result as RequestConfirmationResult | null;
|
||||
if (!acceptedResult) {
|
||||
throw forbidden(
|
||||
"Reflection Coach mutations require an accepted request_confirmation with a displayed diff for this target, "
|
||||
+ "created in a previous run and not already consumed.",
|
||||
{
|
||||
code: "reflection_coach_mutation_gate_required",
|
||||
targetKeys,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const [consumed] = await db
|
||||
.update(issueThreadInteractions)
|
||||
.set({
|
||||
result: markRequestConfirmationResultConsumed(acceptedResult, actorRunId, now),
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(and(
|
||||
eq(issueThreadInteractions.id, accepted.id),
|
||||
eq(issueThreadInteractions.companyId, input.companyId),
|
||||
eq(issueThreadInteractions.createdByAgentId, actorAgentId),
|
||||
eq(issueThreadInteractions.kind, "request_confirmation"),
|
||||
eq(issueThreadInteractions.status, "accepted"),
|
||||
sql`${issueThreadInteractions.result}->>'outcome' = 'accepted'`,
|
||||
sql`coalesce(${issueThreadInteractions.result}->>'consumedByRunId', ${issueThreadInteractions.result}->>'consumedAt') is null`,
|
||||
))
|
||||
.returning({ id: issueThreadInteractions.id });
|
||||
|
||||
if (!consumed) {
|
||||
throw forbidden(
|
||||
"Reflection Coach mutations require an accepted request_confirmation with a displayed diff for this target, "
|
||||
+ "created in a previous run and not already consumed.",
|
||||
{
|
||||
code: "reflection_coach_mutation_gate_required",
|
||||
targetKeys,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import { notFound, unprocessable } from "../errors.js";
|
||||
import { environmentService } from "./environments.js";
|
||||
import { heartbeatService } from "./heartbeat.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import { builtInAgentService } from "./built-in-agents.js";
|
||||
|
||||
export interface CompanyActivityActor {
|
||||
actorType: "user" | "agent" | "system" | "plugin";
|
||||
@@ -52,6 +53,7 @@ export function companyService(db: Db) {
|
||||
const ISSUE_PREFIX_FALLBACK = "CMP";
|
||||
const environmentsSvc = environmentService(db);
|
||||
const heartbeat = heartbeatService(db);
|
||||
const builtInAgents = builtInAgentService(db);
|
||||
|
||||
type CompanyTx = Parameters<Parameters<typeof db.transaction>[0]>[0];
|
||||
|
||||
@@ -263,6 +265,7 @@ export function companyService(db: Db) {
|
||||
create: async (data: typeof companies.$inferInsert) => {
|
||||
const created = await createCompanyWithUniquePrefix(data);
|
||||
await environmentsSvc.ensureLocalEnvironment(created.id);
|
||||
await builtInAgents.autoProvisionBundledAgents(created.id);
|
||||
const row = await getCompanyQuery(db)
|
||||
.where(eq(companies.id, created.id))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
@@ -28,6 +28,7 @@ export function grantsForHumanRole(
|
||||
case "owner":
|
||||
return [
|
||||
{ permissionKey: "agents:create", scope: null },
|
||||
{ permissionKey: "agents:configure", scope: null },
|
||||
{ permissionKey: "skills:create", scope: null },
|
||||
{ permissionKey: "environments:manage", scope: null },
|
||||
{ permissionKey: "users:invite", scope: null },
|
||||
@@ -38,6 +39,7 @@ export function grantsForHumanRole(
|
||||
case "admin":
|
||||
return [
|
||||
{ permissionKey: "agents:create", scope: null },
|
||||
{ permissionKey: "agents:configure", scope: null },
|
||||
{ permissionKey: "skills:create", scope: null },
|
||||
{ permissionKey: "environments:manage", scope: null },
|
||||
{ permissionKey: "users:invite", scope: null },
|
||||
|
||||
@@ -3,7 +3,8 @@ import { promises as fs } from "node:fs";
|
||||
import { execFile } from "node:child_process";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { builtInManagedResources, principalPermissionGrants, type Db } from "@paperclipai/db";
|
||||
import type {
|
||||
CompanyPortabilityAgentManifestEntry,
|
||||
CompanyPortabilityCollisionStrategy,
|
||||
@@ -29,6 +30,7 @@ import type {
|
||||
CompanyPortabilitySkillManifestEntry,
|
||||
CompanySkill,
|
||||
AgentEnvConfig,
|
||||
PermissionKey,
|
||||
RoutineVariable,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
@@ -48,6 +50,7 @@ import {
|
||||
issueCommentMetadataSchema,
|
||||
issueCommentPresentationSchema,
|
||||
normalizeAgentUrlKey,
|
||||
PERMISSION_KEYS,
|
||||
} from "@paperclipai/shared";
|
||||
import {
|
||||
readPaperclipSkillSyncPreference,
|
||||
@@ -77,6 +80,7 @@ import {
|
||||
readCatalogStringList,
|
||||
readPortableCatalogProvenance,
|
||||
} from "./catalog-provenance.js";
|
||||
import { readBuiltInAgentMarker } from "./built-in-agent-metadata.js";
|
||||
import { normalizePortablePath } from "./portable-path.js";
|
||||
|
||||
/** Build OrgNode tree from manifest agent list (slug + reportsToSlug). */
|
||||
@@ -718,6 +722,23 @@ function asBoolean(value: unknown): boolean | null {
|
||||
return typeof value === "boolean" ? value : null;
|
||||
}
|
||||
|
||||
type PortableAgentPermissionGrant = CompanyPortabilityAgentManifestEntry["permissionGrants"][number];
|
||||
|
||||
const VALID_PERMISSION_KEYS = new Set<PermissionKey>(PERMISSION_KEYS);
|
||||
|
||||
function normalizePortablePermissionGrants(value: unknown): PortableAgentPermissionGrant[] {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.flatMap((entry): PortableAgentPermissionGrant[] => {
|
||||
if (!isPlainRecord(entry)) return [];
|
||||
const permissionKey = asString(entry.permissionKey);
|
||||
if (!permissionKey || !VALID_PERMISSION_KEYS.has(permissionKey as PermissionKey)) return [];
|
||||
return [{
|
||||
permissionKey: permissionKey as PermissionKey,
|
||||
scope: isPlainRecord(entry.scope) ? entry.scope : null,
|
||||
}];
|
||||
});
|
||||
}
|
||||
|
||||
function asInteger(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isInteger(value) ? value : null;
|
||||
}
|
||||
@@ -1924,6 +1945,7 @@ const YAML_KEY_PRIORITY = [
|
||||
"adapter",
|
||||
"runtime",
|
||||
"permissions",
|
||||
"permissionGrants",
|
||||
"budgetMonthlyCents",
|
||||
"metadata",
|
||||
] as const;
|
||||
@@ -2690,6 +2712,7 @@ function buildManifestFromPackageFiles(
|
||||
const extensionAdapter = isPlainRecord(extension.adapter) ? extension.adapter : null;
|
||||
const extensionRuntime = isPlainRecord(extension.runtime) ? extension.runtime : null;
|
||||
const extensionPermissions = isPlainRecord(extension.permissions) ? extension.permissions : null;
|
||||
const extensionPermissionGrants = normalizePortablePermissionGrants(extension.permissionGrants);
|
||||
const extensionMetadata = isPlainRecord(extension.metadata) ? extension.metadata : null;
|
||||
const adapterConfig = isPlainRecord(extensionAdapter?.config)
|
||||
? extensionAdapter.config
|
||||
@@ -2713,6 +2736,7 @@ function buildManifestFromPackageFiles(
|
||||
adapterConfig,
|
||||
runtimeConfig,
|
||||
permissions: extensionPermissions ?? {},
|
||||
permissionGrants: extensionPermissionGrants,
|
||||
budgetMonthlyCents:
|
||||
typeof extension.budgetMonthlyCents === "number" && Number.isFinite(extension.budgetMonthlyCents)
|
||||
? Math.max(0, Math.floor(extension.budgetMonthlyCents))
|
||||
@@ -3002,6 +3026,27 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
const strictSecretsMode = process.env.PAPERCLIP_SECRETS_STRICT_MODE === "true";
|
||||
const defaultSecretProvider = getConfiguredSecretProvider();
|
||||
|
||||
async function applyImportedAgentPermissionGrants(
|
||||
companyId: string,
|
||||
agentId: string,
|
||||
permissionGrants: PortableAgentPermissionGrant[],
|
||||
grantedByUserId: string | null,
|
||||
) {
|
||||
if (permissionGrants.length === 0) return;
|
||||
await access.ensureMembership(companyId, "agent", agentId, "member", "active");
|
||||
for (const grant of permissionGrants) {
|
||||
await access.setPrincipalPermission(
|
||||
companyId,
|
||||
"agent",
|
||||
agentId,
|
||||
grant.permissionKey,
|
||||
true,
|
||||
grantedByUserId,
|
||||
grant.scope ?? null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function assertKnownImportAdapterType(type: string | null | undefined): string {
|
||||
const adapterType = typeof type === "string" ? type.trim() : "";
|
||||
if (!adapterType) {
|
||||
@@ -3253,24 +3298,61 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
const rootPath = normalizeAgentUrlKey(company.name) ?? "company-package";
|
||||
let companyLogoPath: string | null = null;
|
||||
|
||||
const managedResourceRows = typeof (db as { select?: unknown }).select === "function"
|
||||
? await db
|
||||
.select({
|
||||
resourceKind: builtInManagedResources.resourceKind,
|
||||
resourceId: builtInManagedResources.resourceId,
|
||||
})
|
||||
.from(builtInManagedResources)
|
||||
.where(eq(builtInManagedResources.companyId, companyId))
|
||||
: [];
|
||||
const managedSkillIds = new Set(
|
||||
managedResourceRows
|
||||
.filter((row) => row.resourceKind === "skill")
|
||||
.map((row) => row.resourceId),
|
||||
);
|
||||
const managedRoutineIds = new Set(
|
||||
managedResourceRows
|
||||
.filter((row) => row.resourceKind === "routine")
|
||||
.map((row) => row.resourceId),
|
||||
);
|
||||
|
||||
const allAgentRows = include.agents ? await agents.list(companyId, { includeTerminated: true }) : [];
|
||||
const liveAgentRows = allAgentRows.filter((agent) => agent.status !== "terminated");
|
||||
const companySkillRows = include.skills || include.agents ? await companySkills.listFull(companyId) : [];
|
||||
const builtInAgentRows = liveAgentRows.filter((agent) => readBuiltInAgentMarker(agent.metadata));
|
||||
const portableAgentRows = liveAgentRows.filter((agent) => !readBuiltInAgentMarker(agent.metadata));
|
||||
const companySkillRowsRaw = include.skills || include.agents ? await companySkills.listFull(companyId) : [];
|
||||
const managedSkillRows = companySkillRowsRaw.filter((skill) => managedSkillIds.has(skill.id));
|
||||
const companySkillRows = companySkillRowsRaw.filter((skill) => !managedSkillIds.has(skill.id));
|
||||
if (include.agents) {
|
||||
const skipped = allAgentRows.length - liveAgentRows.length;
|
||||
if (skipped > 0) {
|
||||
warnings.push(`Skipped ${skipped} terminated agent${skipped === 1 ? "" : "s"} from export.`);
|
||||
}
|
||||
if (builtInAgentRows.length > 0) {
|
||||
warnings.push(`Skipped ${builtInAgentRows.length} built-in managed agent${builtInAgentRows.length === 1 ? "" : "s"} from export.`);
|
||||
}
|
||||
}
|
||||
if (include.skills && managedSkillRows.length > 0) {
|
||||
warnings.push(`Skipped ${managedSkillRows.length} built-in managed skill${managedSkillRows.length === 1 ? "" : "s"} from export.`);
|
||||
}
|
||||
|
||||
const agentByReference = new Map<string, typeof liveAgentRows[number]>();
|
||||
for (const agent of liveAgentRows) {
|
||||
agentByReference.set(agent.id, agent);
|
||||
agentByReference.set(agent.name, agent);
|
||||
const builtInAgentByReference = new Map<string, typeof liveAgentRows[number]>();
|
||||
const addAgentReferences = (map: Map<string, typeof liveAgentRows[number]>, agent: typeof liveAgentRows[number]) => {
|
||||
map.set(agent.id, agent);
|
||||
map.set(agent.name, agent);
|
||||
const normalizedName = normalizeAgentUrlKey(agent.name);
|
||||
if (normalizedName) {
|
||||
agentByReference.set(normalizedName, agent);
|
||||
map.set(normalizedName, agent);
|
||||
}
|
||||
};
|
||||
for (const agent of portableAgentRows) {
|
||||
addAgentReferences(agentByReference, agent);
|
||||
}
|
||||
for (const agent of builtInAgentRows) {
|
||||
addAgentReferences(builtInAgentByReference, agent);
|
||||
}
|
||||
|
||||
const selectedAgents = new Map<string, typeof liveAgentRows[number]>();
|
||||
@@ -3280,6 +3362,11 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
const normalized = normalizeAgentUrlKey(trimmed) ?? trimmed;
|
||||
const match = agentByReference.get(trimmed) ?? agentByReference.get(normalized);
|
||||
if (!match) {
|
||||
const builtInMatch = builtInAgentByReference.get(trimmed) ?? builtInAgentByReference.get(normalized);
|
||||
if (builtInMatch) {
|
||||
warnings.push(`Agent selector "${selector}" is a built-in managed agent and was skipped.`);
|
||||
continue;
|
||||
}
|
||||
warnings.push(`Agent selector "${selector}" was not found and was skipped.`);
|
||||
continue;
|
||||
}
|
||||
@@ -3287,7 +3374,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
}
|
||||
|
||||
if (include.agents && selectedAgents.size === 0) {
|
||||
for (const agent of liveAgentRows) {
|
||||
for (const agent of portableAgentRows) {
|
||||
selectedAgents.set(agent.id, agent);
|
||||
}
|
||||
}
|
||||
@@ -3302,13 +3389,49 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
const slug = uniqueSlug(baseSlug, usedSlugs);
|
||||
idToSlug.set(agent.id, slug);
|
||||
}
|
||||
const agentPermissionGrantRows = agentRows.length > 0 && typeof (db as { select?: unknown }).select === "function"
|
||||
? await db
|
||||
.select({
|
||||
principalId: principalPermissionGrants.principalId,
|
||||
permissionKey: principalPermissionGrants.permissionKey,
|
||||
scope: principalPermissionGrants.scope,
|
||||
})
|
||||
.from(principalPermissionGrants)
|
||||
.where(and(
|
||||
eq(principalPermissionGrants.companyId, companyId),
|
||||
eq(principalPermissionGrants.principalType, "agent"),
|
||||
inArray(principalPermissionGrants.principalId, agentRows.map((agent) => agent.id)),
|
||||
))
|
||||
: [];
|
||||
const permissionGrantsByAgentId = new Map<string, PortableAgentPermissionGrant[]>();
|
||||
for (const row of agentPermissionGrantRows) {
|
||||
if (!VALID_PERMISSION_KEYS.has(row.permissionKey as PermissionKey)) continue;
|
||||
const grants = permissionGrantsByAgentId.get(row.principalId) ?? [];
|
||||
grants.push({
|
||||
permissionKey: row.permissionKey as PermissionKey,
|
||||
scope: isPlainRecord(row.scope) ? row.scope : null,
|
||||
});
|
||||
permissionGrantsByAgentId.set(row.principalId, grants);
|
||||
}
|
||||
for (const grants of permissionGrantsByAgentId.values()) {
|
||||
grants.sort((left, right) => left.permissionKey.localeCompare(right.permissionKey));
|
||||
}
|
||||
|
||||
const projectsSvc = projectService(db);
|
||||
const issuesSvc = issueService(db);
|
||||
const routinesSvc = routineService(db);
|
||||
const allProjectsRaw = include.projects || include.issues ? await projectsSvc.list(companyId) : [];
|
||||
const allProjects = allProjectsRaw.filter((project) => !project.archivedAt);
|
||||
const allRoutines = include.issues ? await routinesSvc.list(companyId) : [];
|
||||
const allRoutinesRaw = include.issues ? await routinesSvc.list(companyId) : [];
|
||||
const builtInRoutineRows = allRoutinesRaw.filter((routine) =>
|
||||
managedRoutineIds.has(routine.id) || routine.originKind === "built_in_agent_bundle"
|
||||
);
|
||||
const allRoutines = allRoutinesRaw.filter((routine) =>
|
||||
!managedRoutineIds.has(routine.id) && routine.originKind !== "built_in_agent_bundle"
|
||||
);
|
||||
if (include.issues && builtInRoutineRows.length > 0) {
|
||||
warnings.push(`Skipped ${builtInRoutineRows.length} built-in managed routine${builtInRoutineRows.length === 1 ? "" : "s"} from export.`);
|
||||
}
|
||||
const projectById = new Map(allProjects.map((project) => [project.id, project]));
|
||||
const projectByReference = new Map<string, typeof allProjects[number]>();
|
||||
for (const project of allProjects) {
|
||||
@@ -3330,6 +3453,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
const selectedIssues = new Map<string, Awaited<ReturnType<typeof issuesSvc.getById>>>();
|
||||
const selectedRoutines = new Map<string, typeof allRoutines[number]>();
|
||||
const routineById = new Map(allRoutines.map((routine) => [routine.id, routine]));
|
||||
const builtInRoutineById = new Map(builtInRoutineRows.map((routine) => [routine.id, routine]));
|
||||
const resolveIssueBySelector = async (selector: string) => {
|
||||
const trimmed = selector.trim();
|
||||
if (!trimmed) return null;
|
||||
@@ -3340,6 +3464,10 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
for (const selector of input.issues ?? []) {
|
||||
const issue = await resolveIssueBySelector(selector);
|
||||
if (!issue || issue.companyId !== companyId) {
|
||||
if (builtInRoutineById.has(selector.trim())) {
|
||||
warnings.push(`Routine selector "${selector}" is a built-in managed routine and was skipped.`);
|
||||
continue;
|
||||
}
|
||||
const routine = routineById.get(selector.trim());
|
||||
if (routine) {
|
||||
selectedRoutines.set(routine.id, routine);
|
||||
@@ -3551,6 +3679,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
},
|
||||
) as Record<string, unknown>;
|
||||
const portablePermissions = pruneDefaultLikeValue(agent.permissions ?? {}, { dropFalseBooleans: true }) as Record<string, unknown>;
|
||||
const portablePermissionGrants = permissionGrantsByAgentId.get(agent.id) ?? [];
|
||||
const agentEnvInputs = dedupeEnvInputs(
|
||||
envInputs
|
||||
.slice(envInputsStart)
|
||||
@@ -3593,6 +3722,7 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
},
|
||||
runtime: portableRuntimeConfig,
|
||||
permissions: portablePermissions,
|
||||
permissionGrants: portablePermissionGrants.length > 0 ? portablePermissionGrants : undefined,
|
||||
budgetMonthlyCents: (agent.budgetMonthlyCents ?? 0) > 0 ? agent.budgetMonthlyCents : undefined,
|
||||
metadata: (agent.metadata as Record<string, unknown> | null) ?? null,
|
||||
});
|
||||
@@ -4593,6 +4723,12 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
} catch (err) {
|
||||
warnings.push(`Failed to materialize instructions bundle for ${manifestAgent.slug}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
await applyImportedAgentPermissionGrants(
|
||||
targetCompany.id,
|
||||
updated.id,
|
||||
manifestAgent.permissionGrants ?? [],
|
||||
actorUserId ?? null,
|
||||
);
|
||||
agentStatusById.set(updated.id, updated.status ?? agentStatusById.get(updated.id) ?? null);
|
||||
await secrets.syncEnvBindingsForTarget?.(
|
||||
targetCompany.id,
|
||||
@@ -4634,6 +4770,12 @@ export function companyPortabilityService(db: Db, storage?: StorageService) {
|
||||
} catch (err) {
|
||||
warnings.push(`Failed to materialize instructions bundle for ${manifestAgent.slug}: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
await applyImportedAgentPermissionGrants(
|
||||
targetCompany.id,
|
||||
created.id,
|
||||
manifestAgent.permissionGrants ?? [],
|
||||
actorUserId ?? null,
|
||||
);
|
||||
agentStatusById.set(created.id, created.status ?? createdStatus);
|
||||
await secrets.syncEnvBindingsForTarget?.(
|
||||
targetCompany.id,
|
||||
|
||||
@@ -4,6 +4,19 @@ export { companySearchService } from "./company-search.js";
|
||||
export { feedbackService } from "./feedback.js";
|
||||
export { companySkillService } from "./company-skills.js";
|
||||
export { agentService, deduplicateAgentName } from "./agents.js";
|
||||
export {
|
||||
builtInAgentService,
|
||||
deriveBuiltInAgentStatus,
|
||||
getBuiltInAgentDefinition,
|
||||
listBuiltInAgentDefinitions,
|
||||
reconcileBuiltInAgentsOnStartup,
|
||||
validateBuiltInAgentDefinitions,
|
||||
type BuiltInAgentDefinition,
|
||||
type BuiltInManagedResourceState,
|
||||
type BuiltInManagedResourceStockStatus,
|
||||
type BuiltInAgentState,
|
||||
type BuiltInAgentStatus,
|
||||
} from "./built-in-agents.js";
|
||||
export { agentInstructionsService, syncInstructionsBundleConfigFromFilePath } from "./agent-instructions.js";
|
||||
export { assetService } from "./assets.js";
|
||||
export { documentService, extractLegacyPlanBody } from "./documents.js";
|
||||
|
||||
@@ -54,6 +54,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableTaskWatchdogs: parsed.data.enableTaskWatchdogs ?? false,
|
||||
enableCloudSync: parsed.data.enableCloudSync ?? false,
|
||||
enableExternalObjects: parsed.data.enableExternalObjects ?? false,
|
||||
enableBuiltInAgents: parsed.data.enableBuiltInAgents ?? false,
|
||||
enableGoalsSidebarLink: parsed.data.enableGoalsSidebarLink ?? false,
|
||||
enableServerInfoDebugView: parsed.data.enableServerInfoDebugView ?? false,
|
||||
autoRestartDevServerWhenIdle: parsed.data.autoRestartDevServerWhenIdle ?? false,
|
||||
@@ -76,6 +77,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableExperimentalFileViewer: false,
|
||||
enableCloudSync: false,
|
||||
enableExternalObjects: false,
|
||||
enableBuiltInAgents: false,
|
||||
enableGoalsSidebarLink: false,
|
||||
enableServerInfoDebugView: false,
|
||||
autoRestartDevServerWhenIdle: false,
|
||||
|
||||
Reference in new issue
Block a user