Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/api/scripts/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,8 @@ if (existing) {

// ---- User and organization ------------------------------------------------------------------

// Made as a sign-up makes them, the organization with its owner's vault, then dated back.
// Made as a sign-up makes them, the organization with its owner's vault and Chat, its built-in agent
// and General, then dated back.
const provisioned = must(
await provisionOrganization({
owner: {
Expand Down
4 changes: 3 additions & 1 deletion packages/api/src/harness/fake-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,12 @@ export function fakeStore(): FakeStore {
createAgentTask: mock<HarnessStore['createAgentTask']>(),
listPersonas: mock<HarnessStore['listPersonas']>(),
listAnswers: mock<HarnessStore['listAnswers']>(),
ensureFirstPersona: mock<HarnessStore['ensureFirstPersona']>(),
listMemberNames: mock<HarnessStore['listMemberNames']>(),
getPersona: mock<HarnessStore['getPersona']>(),
createPersona: mock<HarnessStore['createPersona']>(),
updatePersona: mock<HarnessStore['updatePersona']>(),
sharePersona: mock<HarnessStore['sharePersona']>(),
takeBackPersona: mock<HarnessStore['takeBackPersona']>(),
deletePersona: mock<HarnessStore['deletePersona']>(),
getMemberChat: mock<HarnessStore['getMemberChat']>(),
ensureMemberChat: mock<HarnessStore['ensureMemberChat']>(),
Expand Down
224 changes: 197 additions & 27 deletions packages/api/src/harness/route.test.ts

Large diffs are not rendered by default.

131 changes: 109 additions & 22 deletions packages/api/src/harness/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
type ChatPersona,
type ChatThread,
type ChatThreads,
type ListedPersona,
markReadBodySchema,
MAX_ATTACHMENTS,
personaBodySchema,
Expand Down Expand Up @@ -43,7 +44,7 @@ import type {HarnessStore} from './store';

/**
* The Chat page's routes, under the organization: the personas the member sees, their own and
* General, which every member does, each named and given a head, all acting through the
* those shared with every member, each named and given a head, all acting through the
* organization's one built-in agent login, and the member's own chat with each, which holds
* threads: each message they post in the chat opens one, whose agent works on it and answers them
* there, and a reply in a thread goes on with it; the chat lists its threads, and each is read on
Expand All @@ -59,11 +60,13 @@ import type {HarnessStore} from './store';
export type ChatStore = Pick<
HarnessStore,
| 'listPersonas'
| 'listMemberNames'
| 'listAnswers'
| 'ensureFirstPersona'
| 'getPersona'
| 'createPersona'
| 'updatePersona'
| 'sharePersona'
| 'takeBackPersona'
| 'deletePersona'
| 'getMemberChat'
| 'ensureMemberChat'
Expand Down Expand Up @@ -94,7 +97,7 @@ export type RouteFiles = Pick<ChatFiles, 'upload' | 'discard' | 'resolve' | 'sho
/** The harnesses this server has, read where a route needs them, so that nothing is made as the routes are mounted. */
export type Harnesses = () => HarnessRegistry;

// Whether the viewer may rename, reface, switch the harness or the model of, or delete the persona: their own, or one every member sees that they made or whose organization they own (utils/manages.ts).
// Whether the viewer may rename, reface, switch the harness or the model of, share, or delete the persona: their own, or one every member sees that they made or whose organization they own (utils/manages.ts).
function managesPersona(viewer: OrgViewer, persona: PersonaRow): boolean {
return manages(viewer, {ownerUserId: persona.ownerUserId, byId: persona.createdById});
}
Expand All @@ -109,6 +112,29 @@ function draftPreview(persona: {draft?: string | null; draftAttachments?: DraftA
return names.length === 0 ? null : preview(names.join(', '));
}

// What the page says where another member has said something to a shared persona, which its
// maker then can't make theirs alone again.
function inUse(viewer: OrgViewer, persona: PersonaRow): string {
return `Others in ${viewer.name} are using ${persona.name}, so it stays shared.`;
}

// Why the viewer can't make a shared persona theirs alone again: only whoever made it takes it
// back, not the organization's owner, and nobody where they have left or it names no maker; and one
// another member has said something to stays everyone's. Null where they can, and for one that
// isn't shared.
function staysShared(viewer: OrgViewer, persona: PersonaRow, usedByOthers: boolean): string | null {
if (persona.ownerUserId !== null) {
return null;
}
if (persona.createdById !== viewer.userId) {
return `Only whoever made ${persona.name} can make it theirs alone.`;
}
if (usedByOthers) {
return inUse(viewer, persona);
}
return null;
}

// What runs a persona or a thread as this server offers the organization, which is what a turn of
// its gets; as kept where there is no harness at all, where nothing runs.
function asOffered(harnesses: Harnesses, viewer: OrgViewer, model: PersonaModel): PersonaModel {
Expand All @@ -132,6 +158,35 @@ function toPersona(harnesses: Harnesses, viewer: OrgViewer, persona: PersonaRow
};
}

// Who made the persona, as its settings say: the viewer, or another member by what they are called
// (`names`, by their id); nobody for one whose maker has left, or that names none.
function madeBy(viewer: OrgViewer, persona: PersonaRow, names: ReadonlyMap<string, string>): ListedPersona['madeBy'] {
if (persona.createdById === null) {
return null;
}
if (persona.createdById === viewer.userId) {
return 'you';
}
const name = names.get(persona.createdById);
return name === undefined ? null : {name};
}

// A persona as the list has it, with who made it, whether another member has said anything to it
// and why the viewer can't make it theirs alone, which its settings say.
function toListedPersona(
harnesses: Harnesses,
viewer: OrgViewer,
persona: PersonaRow & {usedByOthers: boolean; lastMessage?: LastMessage | null; draft?: string | null; draftAttachments?: DraftAttachment[]},
names: ReadonlyMap<string, string>,
): ListedPersona {
return {
...toPersona(harnesses, viewer, persona),
madeBy: madeBy(viewer, persona, names),
usedByOthers: persona.usedByOthers,
staysShared: staysShared(viewer, persona, persona.usedByOthers),
};
}

// The harnesses a persona of the viewer's organization can run on here, as the dialog offers them.
function toHarnesses(registry: HarnessRegistry, viewer: OrgViewer): ChatHarness[] {
return harnessesOf(offeredTo(registry, viewer)).map(({id, label, models}) => ({id, label, models}));
Expand All @@ -141,28 +196,60 @@ function toHarnesses(registry: HarnessRegistry, viewer: OrgViewer): ChatHarness[
// offers it the organization: a harness named has to be one of those, and a model named one of
// the harness's; the model left out is the harness's first, or the persona's own where the harness
// stays. With neither named, one changed (`existing`) keeps what it has, and a new one gets the
// first harness offered with its first model.
function readPersona(harnesses: Harnesses, viewer: OrgViewer, request: AuthenticatedRequest, existing: PersonaModel | null): Result<Persona, ApiError> {
// first harness offered with its first model. Apart from it, whether it is to be shared with the
// organization, where that is said.
function readPersona(harnesses: Harnesses, viewer: OrgViewer, request: AuthenticatedRequest, existing: PersonaModel | null): Result<{persona: Persona; shared: boolean | undefined}, ApiError> {
const parsed = parseSchema(personaBodySchema, request.body);
if (parsed.isErr()) {
return Err(parsed.error);
}
const {harness, chatModel, ...persona} = parsed.value;
const {harness, chatModel, shared, ...persona} = parsed.value;
if (existing !== null && harness === undefined && chatModel === undefined) {
return Ok(persona);
return Ok({persona, shared});
}
const sameHarness = harness === undefined || harness === existing?.harness;
const chosen = chosenFor(offeredTo(harnesses(), viewer), {harness: harness ?? existing?.harness ?? '', chatModel: chatModel ?? (sameHarness ? (existing?.chatModel ?? '') : '')});
if (chosen === null) {
return Ok(persona);
return Ok({persona, shared});
}
if (harness !== undefined && chosen.harness.id !== harness) {
return Err(ApiErr.validationError(`This server has no harness ${harness}.`));
}
if (chatModel !== undefined && chosen.model !== chatModel) {
return Err(ApiErr.validationError(`${chosen.harness.label} has no model ${chatModel}.`));
}
return Ok({...persona, harness: chosen.harness.id, chatModel: chosen.model});
return Ok({persona: {...persona, harness: chosen.harness.id, chatModel: chosen.model}, shared});
}

// The persona shared with the organization, or made the viewer's alone again, where `shared` says
// it is to be and it isn't yet: their own is theirs to share; a shared one is made theirs again
// only by whoever made it, and only while no other member has said anything to it, the refusal
// saying why. What it is to be, whether the viewer is the only one who has talked to it.
function reshare(store: ChatStore, viewer: OrgViewer, persona: PersonaRow, shared: boolean | undefined): Promise<Result<PersonaRow, ApiError>> {
return Do(async ($) => {
const isShared = persona.ownerUserId === null;
if (shared === undefined || shared === isShared) {
return persona;
}
if (shared && !$(await store.sharePersona(viewer.orgId, viewer.userId, persona.id))) {
return $(Err(ApiErr.notFound('persona', persona.id)));
}
if (shared) {
return {...persona, ownerUserId: null};
}
const refused = staysShared(viewer, persona, false);
if (refused !== null) {
return $(Err(ApiErr.conflict(refused)));
}
const taken = $(await store.takeBackPersona(viewer.orgId, viewer.userId, persona.id));
if (taken === 'used') {
return $(Err(ApiErr.conflict(inUse(viewer, persona))));
}
if (taken === 'missing') {
return $(Err(ApiErr.notFound('persona', persona.id)));
}
return {...persona, ownerUserId: viewer.userId};
});
}

// The persona in the address, one of the organization's the viewer sees: another member's own is not found.
Expand Down Expand Up @@ -197,18 +284,17 @@ function ensureChat(store: ChatStore, viewer: OrgViewer, persona: PersonaRow): P
});
}

/** `GET /api/orgs/:org/chat/personas`: the organization's personas the viewer sees, their own and those every member does, the one last active in the viewer's chat with it first, and the harnesses the server has for one to run on; a General one, every member's, is made where there is none, after the viewer's own, so a message that names no agent always has one to go to. */
/** `GET /api/orgs/:org/chat/personas`: the organization's personas the viewer sees, their own and those every member does, the one last active in the viewer's chat with it first, and the harnesses the server has for one to run on. It makes none: an organization whose personas were all deleted lists none. */
function handleListPersonasRoute(store: ChatStore, harnesses: Harnesses, request: AuthenticatedRequest): Promise<Result<z.infer<typeof personaListSchema>, ApiError>> {
return Do(async ($) => {
const viewer = $(await requireViewer(request));
const personas = $(await store.listPersonas(viewer.orgId, viewer.userId));
const offered = toHarnesses(harnesses(), viewer);
const listed = personas.map((persona) => toPersona(harnesses, viewer, persona));
if (personas.some((persona) => persona.ownerUserId === null)) {
return {personas: listed, harnesses: offered};
}
const general = $(await store.ensureFirstPersona(viewer.orgId));
return {personas: [...listed, toPersona(harnesses, viewer, general)], harnesses: offered};
// What the other members who made the shared ones are called.
const makers = new Set(personas.flatMap(({createdById}) => (createdById === null || createdById === viewer.userId ? [] : [createdById])));
const named = $(await store.listMemberNames([...makers].map((userId) => ({orgId: viewer.orgId, userId}))));
const names = new Map(named.map(({userId, name}) => [userId, name]));
return {personas: personas.map((persona) => toListedPersona(harnesses, viewer, persona, names)), harnesses: offered};
});
}

Expand All @@ -232,26 +318,27 @@ function handleListAnswersRoute(store: ChatStore, request: AuthenticatedRequest)
});
}

/** `POST /api/orgs/:org/chat/personas` with `{name, look, color, harness?, chatModel?}`: a new persona, the viewer's own. */
/** `POST /api/orgs/:org/chat/personas` with `{name, look, color, harness?, chatModel?, shared?}`: a new persona, the viewer's own, or every member's where `shared`. */
function handleCreatePersonaRoute(store: ChatStore, harnesses: Harnesses, request: AuthenticatedRequest): Promise<Result<z.infer<typeof personaAnswerSchema>, ApiError>> {
return Do(async ($) => {
const viewer = $(await requireViewer(request));
const persona = $(readPersona(harnesses, viewer, request, null));
const made = $(await store.createPersona(viewer.orgId, viewer.userId, persona));
const {persona, shared} = $(readPersona(harnesses, viewer, request, null));
const made = $(await store.createPersona(viewer.orgId, viewer.userId, persona, shared ?? false));
return {persona: toPersona(harnesses, viewer, made)};
});
}

/** `PUT /api/orgs/:org/chat/personas/:personaId` with `{name, look, color, harness?, chatModel?}`: the persona renamed, with another head, or switched to another harness or model from its next turn on, in every thread of every chat with it. */
/** `PUT /api/orgs/:org/chat/personas/:personaId` with `{name, look, color, harness?, chatModel?, shared?}`: the persona renamed, with another head, or switched to another harness or model from its next turn on, in every thread of every chat with it; and shared with the organization, or made the viewer's alone again (`reshare`), first, so a refusal changes nothing. */
function handleUpdatePersonaRoute(store: ChatStore, harnesses: Harnesses, request: AuthenticatedRequest): Promise<Result<z.infer<typeof personaAnswerSchema>, ApiError>> {
return Do(async ($) => {
const viewer = $(await requireViewer(request));
const existing = $(await requireManagedPersona(store, viewer, request));
const persona = $(readPersona(harnesses, viewer, request, existing));
const {persona, shared} = $(readPersona(harnesses, viewer, request, existing));
const reshared = $(await reshare(store, viewer, existing, shared));
if (!$(await store.updatePersona(viewer.orgId, existing.id, persona))) {
return $(Err(ApiErr.notFound('persona', existing.id)));
}
return {persona: toPersona(harnesses, viewer, {...existing, ...persona})};
return {persona: toPersona(harnesses, viewer, {...reshared, ...persona})};
});
}

Expand Down
20 changes: 16 additions & 4 deletions packages/api/src/harness/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type {
Persona,
PersonaModel,
PersonaRow,
TakeBack,
ThreadOpening,
SaidToParent,
SubAgentRow,
Expand All @@ -38,6 +39,7 @@ import type {TranscriptKey, TranscriptLine} from '@proxy/db/harness-transcript';
import {type AgentTaskRow, createAgentTask, getAgentTask, type NewAgentTask} from '@proxy/db/task';
import type {SignedInAgent} from '@proxy/db/agent';
import {getUserTimeZone} from '@proxy/db/user';
import {listMemberNames} from '@proxy/db/organization';

/**
* What the harness reads and writes: the job queue, each thread's log and its jobs, the Chat
Expand Down Expand Up @@ -79,12 +81,20 @@ export type HarnessStore = {
getAgentTask: (orgId: string, agentId: string, taskId: string) => Promise<Result<AgentTaskRow | null, ApiError>>;
createAgentTask: (task: NewAgentTask) => Promise<Result<AgentTaskRow | null, ApiError>>;

listPersonas: (orgId: string, userId: string) => Promise<Result<Array<PersonaRow & {lastMessage: LastMessage | null; draft: string | null; draftAttachments: DraftAttachment[]}>, ApiError>>;
listPersonas: (
orgId: string,
userId: string,
) => Promise<Result<Array<PersonaRow & {lastMessage: LastMessage | null; draft: string | null; draftAttachments: DraftAttachment[]; usedByOthers: boolean}>, ApiError>>;
listAnswers: (orgId: string, userId: string) => Promise<Result<ChatAnswerRow[], ApiError>>;
ensureFirstPersona: (orgId: string) => Promise<Result<PersonaRow, ApiError>>;
/** What the members who made shared personas are called, those still in the organization, as the list says who made one. */
listMemberNames: typeof listMemberNames;
getPersona: (orgId: string, userId: string, personaId: string) => Promise<Result<PersonaRow | null, ApiError>>;
createPersona: (orgId: string, userId: string, persona: Persona) => Promise<Result<PersonaRow, ApiError>>;
createPersona: (orgId: string, userId: string, persona: Persona, shared: boolean) => Promise<Result<PersonaRow, ApiError>>;
updatePersona: (orgId: string, personaId: string, persona: Persona) => Promise<Result<boolean, ApiError>>;
/** The member's own persona shared with the organization; false for no such persona of theirs. */
sharePersona: (orgId: string, userId: string, personaId: string) => Promise<Result<boolean, ApiError>>;
/** A shared persona its maker's own again, refused where another member has said anything to it. */
takeBackPersona: (orgId: string, userId: string, personaId: string) => Promise<Result<TakeBack, ApiError>>;
deletePersona: (orgId: string, personaId: string) => Promise<Result<boolean, ApiError>>;
getMemberChat: (personaId: string, userId: string) => Promise<Result<ThreadRow | null, ApiError>>;
ensureMemberChat: (data: {orgId: string; agentId: string; personaId: string; userId: string}) => Promise<Result<ThreadRow, ApiError>>;
Expand Down Expand Up @@ -186,10 +196,12 @@ export const harnessStore: HarnessStore = {

listPersonas: harness.listPersonas,
listAnswers: harness.listAnswers,
ensureFirstPersona: harness.ensureFirstPersona,
listMemberNames,
getPersona: harness.getPersona,
createPersona: harness.createPersona,
updatePersona: harness.updatePersona,
sharePersona: harness.sharePersona,
takeBackPersona: harness.takeBackPersona,
deletePersona: harness.deletePersona,
getMemberChat: harness.getMemberChat,
ensureMemberChat: harness.ensureMemberChat,
Expand Down
36 changes: 36 additions & 0 deletions packages/contracts/src/contracts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -143,4 +143,40 @@ describe('contracts', () => {
const {summary: _summary, ...withoutSummary} = thread;
expect(harness.chatThreadSchema.safeParse(withoutSummary).success).toBe(false);
});

test('a persona is made or changed shared with the organization or not, or left as it is, and is listed with who made it, whether others use it and why it stays shared', () => {
const look = {nose: 0.5, noseOut: 0.3, eye: 25, eyeTheta: 50, eyeLat: 8, eyes: 2 as const};
const body = {name: 'Finance', look, color: 'teal' as const};
expect(harness.personaBodySchema.parse({...body, shared: true}).shared).toBe(true);
expect(harness.personaBodySchema.parse({...body, shared: false}).shared).toBe(false);
expect(harness.personaBodySchema.parse(body).shared).toBeUndefined();
expect(harness.personaBodySchema.safeParse({...body, shared: 'everyone'}).success).toBe(false);

const persona: harness.ListedPersona = {
id: 'p1',
name: 'Finance',
look,
color: 'teal',
harness: 'claude-agent-sdk',
chatModel: 'sonnet',
shared: true,
mayChange: true,
madeBy: 'you',
usedByOthers: true,
staysShared: 'Others in Acme are using Finance, so it stays shared.',
lastMessage: null,
draft: null,
createdAt: '2026-03-02T09:24:00.000Z',
};
expect(harness.listedPersonaSchema.parse(persona)).toEqual(persona);
expect(
harness.listedPersonaSchema.parse({...persona, staysShared: null}).staysShared,
).toBeNull();
expect(harness.listedPersonaSchema.parse({...persona, madeBy: {name: 'Dana'}}).madeBy).toEqual({
name: 'Dana',
});
expect(harness.listedPersonaSchema.parse({...persona, madeBy: null}).madeBy).toBeNull();
const {usedByOthers: _used, ...withoutUse} = persona;
expect(harness.listedPersonaSchema.safeParse(withoutUse).success).toBe(false);
});
});
Loading
Loading