From f710d94aad7c6e0d18545c6d2663af13f9e388c7 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 13:44:06 -0400 Subject: [PATCH 01/12] feat(j5): choose which models custom Crew members can use (#744) Add a project-scoped crewMemberModels setting (checked provider/model pairs, null until saved) and one J5 service that decides whether a resolved model may run a custom worker. Crew launches and additions, a plain j5_spawn_agent and a plain delegate_task call it; a persona that keeps its own model skips it. A refusal names the model, the project and the setting and lists what is eligible. delegate_task gets an optional authorizeTarget hook in upstream's delegateTask so the check sees the model the child will really run on. Co-Authored-By: Claude Sonnet 5.5 --- FORK.md | 2 + .../src/j5/a2a/CrewLaunchService.test.ts | 277 +++++++++++++++++ apps/server/src/j5/a2a/CrewLaunchService.ts | 64 +++- .../src/j5/a2a/CrewProposalService.test.ts | 119 ++++++- apps/server/src/j5/a2a/CrewProposalService.ts | 1 + apps/server/src/j5/a2a/SpawnAgentService.ts | 14 + apps/server/src/j5/a2a/clientActionRpc.ts | 1 + apps/server/src/j5/a2a/mcp/handlers.test.ts | 7 + apps/server/src/j5/a2a/mcp/handlers.ts | 16 +- .../j5/a2a/mcp/orchestratorSurface.test.ts | 2 + apps/server/src/j5/a2a/mcp/tools.ts | 3 + apps/server/src/j5/a2a/runtimeLayer.ts | 2 + apps/server/src/j5/a2a/spawnWorkspace.test.ts | 77 +++++ apps/server/src/j5/agents/agentDelegation.ts | 20 +- .../agents/agentSubagent.integration.test.ts | 290 ++++++++++++------ apps/server/src/j5/agents/crewMemberModels.ts | 85 +++++ .../src/j5/test-support/crewMemberModels.ts | 41 +++ apps/server/src/mcp/OrchestratorMcpService.ts | 10 + .../toolkits/worktree/registration.test.ts | 2 + packages/contracts/src/j5.ts | 1 + .../contracts/src/j5/crewMemberModels.test.ts | 106 +++++++ packages/contracts/src/j5/crewMemberModels.ts | 104 +++++++ packages/contracts/src/settings.ts | 6 + packages/shared/src/projectSettings.test.ts | 24 ++ 24 files changed, 1154 insertions(+), 120 deletions(-) create mode 100644 apps/server/src/j5/agents/crewMemberModels.ts create mode 100644 apps/server/src/j5/test-support/crewMemberModels.ts create mode 100644 packages/contracts/src/j5/crewMemberModels.test.ts create mode 100644 packages/contracts/src/j5/crewMemberModels.ts diff --git a/FORK.md b/FORK.md index 3def0e8a96ae4..948a3c2c38f5d 100644 --- a/FORK.md +++ b/FORK.md @@ -485,6 +485,8 @@ migrations after upstream migrations. 89. Deferred Crew assignments ([#745](https://github.com/Jacksondr5/j5code/issues/745)): `orchestration-v2/runtimeLayer.ts` wraps the shared orchestrator with J5-owned `CrewDeliveryContext.ts` for first-assignment workspace preparation and guards, and supplies J5-owned `CrewTurnContext.ts` to provider turn start and provider turn control. `orchestration-v2/ProviderTurnStartService.ts` asks that service whether the thread is a Crew seat (one indexed read) and delegates only a seat's selected assignment text to it immediately around provider delivery; every other thread keeps upstream's fast path and delivery unchanged, and `CrewDeliveryContext.ts` likewise passes any non-seat thread's dispatch straight through. `orchestration-v2/ProviderTurnControlService.ts` wraps the live session with the service's `steering`, one hook beside upstream's `steerTurn` call, so a message steered into a busy seat carries the current context too. The service builds the approved introduction or net roster changes from the current roster, sends the full introduction again when the provider conversation it reached is replaced (a model or provider switch, or a missing native session rebuilt from history), and records what it sent only after the provider accepts the prompt; a send that never happens (the run was stopped or superseded before `startTurn`) leaves it owed. Editable messages and shared author prefixes stay unchanged, so queued edits, cancellations and reordering cannot consume context. Waiting seats whose Crew is retired fail visibly; a retained worktree guard applies even after retirement. J5 migration 49 owns the context, and `CrewSeatPreparation.ts` uses upstream's persisted preparation path. `orchestration-v2/ProviderTurnStartService.test.ts` and `ProviderTurnControlService.test.ts` exercise the hooks against the real seat context, including a retained and a replaced native conversation and a Stop before the provider send. On an advance, retain the hooks at actual delivery and steering after queue selection, shared by every provider and transport. +90. Models for custom members ([#744](https://github.com/Jacksondr5/j5code/issues/744), maintainer-approved upstream edit to `delegateTask`): `packages/contracts/src/settings.ts` imports J5's `CrewMemberModels` schema (`packages/contracts/src/j5/crewMemberModels.ts`) and registers `crewMemberModels`, a nullable list of checked `(providerInstanceId, model)` pairs (never saved is `null`, every model eligible), in the project-scoped key list, project overrides (also in the nullable-override list), server settings and patches. `apps/server/src/mcp/OrchestratorMcpService.ts` gives `delegateTask` an optional `authorizeTarget` input, called right after `resolveTargetRechecking` with the child's project and resolved model selection unless the command already has a receipt, so a plain `delegate_task` is checked on the model the child will actually run on, inherited included. Upstream behavior is unchanged when no hook is passed; J5's `agents/agentDelegation.ts` passes one that calls the J5-owned `CrewMemberModels` service (`apps/server/src/j5/agents/crewMemberModels.ts`), which Crew launches and `j5_spawn_agent` also call. `apps/server/src/mcp/toolkits/worktree/registration.test.ts` stubs that service among the J5 tool dependencies. On an advance, keep the one call after the target resolves and before anything is created. + ## Pin and upstream advance runbook Current pin: `70d60e03a7a35c6fa131825bbfa05ec893e69912`, upstream's nightly tag `v0.1.1-nightly.20261017.3238` on `main` (frozen 2026-10-17). The previous pin was `29980a31409234b676f97bd477c4e46fdb61a929`, from upstream `main`. diff --git a/apps/server/src/j5/a2a/CrewLaunchService.test.ts b/apps/server/src/j5/a2a/CrewLaunchService.test.ts index c6db88cbed05b..763a463a788e0 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.test.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.test.ts @@ -28,6 +28,11 @@ import { resolveAgentPersonaRuntime } from "../agents/agentPersonaRuntime.ts"; import { guardAgentPersonaThreadCreate } from "../agents/agentPersonaOrchestration.ts"; import { ServerSecretStore } from "../../auth/ServerSecretStore.ts"; import { personaLibraryLayer } from "../test-support/personaLibrary.ts"; +import { CrewMemberModels } from "../agents/crewMemberModels.ts"; +import { + crewMemberModelsLayer, + permissiveCrewMemberModels, +} from "../test-support/crewMemberModels.ts"; import { AnalyticsService } from "../../telemetry/AnalyticsService.ts"; import { OrchestratorDispatchError, @@ -231,8 +236,11 @@ const dependencies = ( workspace: Parameters[0] = { checkout: { isRepo: true, refName: "main" }, }, + // Every model is eligible unless a test saves a list. + memberModels: Layer.Layer = permissiveCrewMemberModels, ) => Layer.mergeAll( + memberModels, fakeSpawnWorkspaceLayer(workspace).pipe( Layer.provideMerge( threadManagementFake( @@ -2191,3 +2199,272 @@ it.effect("binds an existing worktree's live branch, so a stale preview can't ap }).pipe(Effect.provide(layer)); }), ); + +const captainProjectId = () => ProjectId.make("project:crew-launch"); + +const eligibilityFixture = (input: { + readonly providers: ReadonlyArray; + readonly settings?: Parameters[0]["settings"]; +}) => + Effect.gen(function* () { + const { context, commands, captain } = yield* fixture; + const layer = crewLaunchLayer.pipe( + Layer.provideMerge( + dependencies( + commands, + input.providers, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + crewMemberModelsLayer({ + providers: input.providers, + ...(input.settings === undefined ? {} : { settings: input.settings }), + projectTitle: "Billing Migration", + }), + ), + ), + Layer.provideMerge(Layer.succeedContext(context)), + Layer.provideMerge( + personaLibraryLayer("j5-crew-models-", Object.values(BUILT_IN_AGENT_PERSONAS)), + ), + Layer.provideMerge(NodeServices.layer), + ); + return { layer, captain, commands }; + }); + +const sol = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }; +const terra = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-terra" }; +const codexModels = (...slugs: ReadonlyArray) => + provider( + "codex", + "codex", + slugs.map((slug) => ({ slug, options: ["high"] })), + ); +const customSeat = (name: string, modelSelection?: typeof sol) => ({ + workspace: { type: "shared" as const }, + name, + agentId: null, + reason: "Works", + instructions: "Do the work.", + ...(modelSelection === undefined ? {} : { modelSelection }), +}); + +it.effect("every model is eligible for a custom seat until a list is saved", () => + Effect.gen(function* () { + const { layer, captain } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol", "gpt-5.6-terra")], + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + const resolved = yield* launcher.resolveSeats(captain, [ + customSeat("inherits"), + customSeat("explicit", terra), + ]); + assert.deepStrictEqual( + resolved.map((seat) => seat.modelSelection.model), + ["gpt-5.6-sol", "gpt-5.6-terra"], + ); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a saved list holds a custom seat to its checked models and names what to use", () => + Effect.gen(function* () { + const { layer, captain, commands } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol", "gpt-5.6-terra")], + settings: { crewMemberModels: [sol] }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + const checked = yield* launcher.resolveSeats(captain, [ + customSeat("inherits"), + customSeat("explicit", sol), + ]); + assert.lengthOf(checked, 2); + const refused = yield* launcher + .resolveSeats(captain, [customSeat("explicit", terra)]) + .pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchModelNotEligibleError"); + for (const part of [ + "gpt-5.6-terra", + "Billing Migration", + "Models for custom members in Agent Setup", + "codex/gpt-5.6-sol", + ]) + assert.include(refused.message, part); + // The refusal covers a launch as it does a preview, and nothing is created. + const launched = yield* launcher + .launch({ + providerSessionId: "session", + requestKey: "launch-ineligible", + captain, + displayName: "Crew", + seats: [customSeat("explicit", terra)], + brief: "Work.", + }) + .pipe(Effect.flip); + assert.equal(launched._tag, "CrewLaunchModelNotEligibleError"); + assert.lengthOf(yield* Ref.get(commands), 0); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a model new to the catalog after the list was saved starts unchecked", () => + Effect.gen(function* () { + const { layer, captain } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.7-new")], + // Saved when the catalog held two models, and both were checked. + settings: { crewMemberModels: [sol, terra] }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + yield* launcher.resolveSeats(captain, [customSeat("known", terra)]); + const refused = yield* launcher + .resolveSeats(captain, [ + customSeat("fresh", { instanceId: sol.instanceId, model: "gpt-5.7-new" }), + ]) + .pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchModelNotEligibleError"); + assert.include(refused.message, "codex/gpt-5.6-sol, codex/gpt-5.6-terra."); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a custom seat that inherits the Captain's model is held to the list", () => + Effect.gen(function* () { + // The Captain runs on gpt-5.6-sol, which the list leaves out. + const { layer, captain } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol", "gpt-5.6-terra")], + settings: { crewMemberModels: [terra] }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + const refused = yield* launcher + .resolveSeats(captain, [customSeat("inherits")]) + .pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchModelNotEligibleError"); + assert.include(refused.message, "Model gpt-5.6-sol on codex"); + assert.include(refused.message, "codex/gpt-5.6-terra"); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a saved list with nothing checked makes no model eligible", () => + Effect.gen(function* () { + const { layer, captain } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol", "gpt-5.6-terra")], + settings: { crewMemberModels: [] }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + const refused = yield* launcher + .resolveSeats(captain, [customSeat("inherits")]) + .pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchModelNotEligibleError"); + assert.include(refused.message, "nothing is checked"); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a stale entry for a model the catalog no longer lists changes nothing", () => + Effect.gen(function* () { + const { layer, captain } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol", "gpt-5.6-terra")], + settings: { + crewMemberModels: [{ instanceId: sol.instanceId, model: "retired-model" }, sol], + }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + yield* launcher.resolveSeats(captain, [customSeat("inherits")]); + const refused = yield* launcher + .resolveSeats(captain, [customSeat("other", terra)]) + .pipe(Effect.flip); + assert.include(refused.message, "Eligible models: codex/gpt-5.6-sol."); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a project's own list replaces the environment's", () => + Effect.gen(function* () { + const { layer, captain } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol", "gpt-5.6-terra")], + settings: { + crewMemberModels: [sol], + projectSettingsOverrides: { [captainProjectId()]: { crewMemberModels: [terra] } }, + }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + yield* launcher.resolveSeats(captain, [customSeat("allowed", terra)]); + const refused = yield* launcher + .resolveSeats(captain, [customSeat("inherits")]) + .pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchModelNotEligibleError"); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a project can override a saved list with every model", () => + Effect.gen(function* () { + const { layer, captain } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol", "gpt-5.6-terra")], + settings: { + crewMemberModels: [], + projectSettingsOverrides: { [captainProjectId()]: { crewMemberModels: null } }, + }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + yield* launcher.resolveSeats(captain, [customSeat("inherits"), customSeat("other", terra)]); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a persona keeps its own model off the list, until its model is overridden", () => + Effect.gen(function* () { + const { layer, captain } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna")], + settings: { crewMemberModels: [] }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + const persona = { + workspace: { type: "shared" as const }, + name: "builder", + agentId: "builder", + reason: "Builds", + }; + const [own] = yield* launcher.resolveSeats(captain, [persona]); + const personaModel = { + instanceId: own!.modelSelection.instanceId, + model: own!.modelSelection.model, + }; + // Editing a field on the roster card freezes the persona's model into the seat; it is the + // same model, so the seat still keeps it, with or without the options the card carried. + const [frozen] = yield* launcher.resolveSeats(captain, [ + { ...persona, modelSelection: own!.modelSelection, runtimeMode: "approval-required" }, + ]); + assert.equal(frozen!.modelSelection.model, personaModel.model); + const [bare] = yield* launcher.resolveSeats(captain, [ + { ...persona, modelSelection: personaModel }, + ]); + assert.equal(bare!.modelSelection.model, personaModel.model); + // A different model on the card makes it a custom choice, held to the list. + const other = ["gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"].find( + (model) => model !== personaModel.model, + )!; + const refused = yield* launcher + .resolveSeats(captain, [ + { ...persona, modelSelection: { instanceId: personaModel.instanceId, model: other } }, + ]) + .pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchModelNotEligibleError"); + assert.include(refused.message, `Model ${other} on codex`); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); diff --git a/apps/server/src/j5/a2a/CrewLaunchService.ts b/apps/server/src/j5/a2a/CrewLaunchService.ts index ed9c9c3276031..ee083b01b2179 100644 --- a/apps/server/src/j5/a2a/CrewLaunchService.ts +++ b/apps/server/src/j5/a2a/CrewLaunchService.ts @@ -23,6 +23,7 @@ import * as Result from "effect/Result"; import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; import { ProviderRegistry } from "../../provider/ProviderRegistry.ts"; +import { CrewMemberModels } from "../agents/crewMemberModels.ts"; import { prepareAgentPersonaLaunch } from "../agents/agentPersonaLaunch.ts"; import { agentHandoffArtifactPath } from "../agents/agentPersonaArtifacts.ts"; import { @@ -184,6 +185,15 @@ export class CrewLaunchSeatUnavailableError extends Data.TaggedError( } } +/** A custom seat's model is not on the project's "Models for custom members" list. */ +export class CrewLaunchModelNotEligibleError extends Data.TaggedError( + "CrewLaunchModelNotEligibleError", +)<{ readonly seatName: string; readonly detail: string }> { + override get message(): string { + return `Seat ${this.seatName}: ${this.detail} Nothing was spawned.`; + } +} + /** The Crew is full; the seats it holds already reach the cap once the request is counted. */ export class CrewLaunchCapError extends Data.TaggedError("CrewLaunchCapError")<{ readonly crewInstanceId: string; @@ -221,6 +231,7 @@ export class CrewLaunchOperationError extends Data.TaggedError("CrewLaunchOperat export type CrewLaunchError = | CrewLaunchSeatUnavailableError + | CrewLaunchModelNotEligibleError | CrewLaunchCapError | CrewLaunchSeatConflictError | CrewLaunchOperationError @@ -268,6 +279,7 @@ export const layer = Layer.effect( const registry = yield* ProviderRegistry; const agents = yield* makeAgentPersonaLibrary; const spawnWorkspace = yield* SpawnWorkspaceService; + const memberModels = yield* CrewMemberModels; // Resolve every seat before creating anything: a Crew launches whole or not at all. const resolveSeats = Effect.fn("j5.a2a.crewLaunch.resolveSeats")(function* ( @@ -304,9 +316,12 @@ export const layer = Layer.effect( ), ); const resolved: Array = []; + // `custom` seats run on whatever the project's list of models for custom members allows. A + // persona seat that keeps its persona's own model is not custom and skips the list. const resolveSelection = Effect.fn("j5.a2a.crewLaunch.resolveSelection")(function* ( seat: CrewLaunchSeat, selection: ModelSelection, + custom: boolean, ) { const provider = providers.find( (candidate) => candidate.instanceId === selection.instanceId, @@ -344,13 +359,25 @@ export const layer = Layer.effect( agentId: seat.agentId ?? "custom seat", detail: optionProblem, }); + if (custom) + yield* memberModels + .assertEligible({ projectId: captain.thread.projectId, selection }) + .pipe( + Effect.mapError( + (error) => + new CrewLaunchModelNotEligibleError({ + seatName: seat.name, + detail: error.message, + }), + ), + ); return { modelSelection, provider: provider! }; }); for (const seat of seats) { const agentId = seat.agentId; if (agentId === null) { const selection = seat.modelSelection ?? captain.thread.modelSelection; - const { modelSelection, provider } = yield* resolveSelection(seat, selection); + const { modelSelection, provider } = yield* resolveSelection(seat, selection, true); // Access is the one setting a custom seat does not take from its Captain: a seat nobody // configured runs in Full access, so it never stops for approvals in a thread the person // is not watching (#326). The person sees and can change it on the roster card. @@ -394,11 +421,29 @@ export const layer = Layer.effect( resolvedModelSelection: (yield* resolveSelection( seat, prepared.resolvedModelSelection, + false, )).modelSelection, ...(seat.runtimeMode === undefined ? {} : { runtimeModeOverride: seat.runtimeMode }), }; } - const { modelSelection, provider } = yield* resolveSelection(seat, seat.modelSelection); + // Editing any field on the roster card freezes the persona's model into the seat, so a + // seat counts as keeping the persona's model by comparing it, never by its absence. + const personaModel = yield* prepareAgentPersonaLaunch( + { personaId: agentId }, + providers, + agents, + ).pipe( + Effect.map(({ resolvedModelSelection }) => resolvedModelSelection), + Effect.orElseSucceed(() => null), + ); + const keepsPersonaModel = + personaModel?.instanceId === seat.modelSelection.instanceId && + personaModel.model === seat.modelSelection.model; + const { modelSelection, provider } = yield* resolveSelection( + seat, + seat.modelSelection, + !keepsPersonaModel, + ); const catalog = yield* agents.catalog(); const definition = catalog.definitions.find(({ id }) => id === agentId); if (definition === undefined || catalog.disabledIds.includes(agentId)) @@ -433,13 +478,14 @@ export const layer = Layer.effect( ...(seat.runtimeMode === undefined ? {} : { runtimeModeOverride: seat.runtimeMode }), }; }).pipe( - Effect.mapError( - (error) => - new CrewLaunchSeatUnavailableError({ - seatName: seat.name, - agentId, - detail: error.message, - }), + Effect.mapError((error) => + error._tag === "CrewLaunchModelNotEligibleError" + ? error + : new CrewLaunchSeatUnavailableError({ + seatName: seat.name, + agentId, + detail: error.message, + }), ), ); // The person's edited text runs instead of the persona's, never beside it: the seat's diff --git a/apps/server/src/j5/a2a/CrewProposalService.test.ts b/apps/server/src/j5/a2a/CrewProposalService.test.ts index ca977b5416857..3fd9fbe83d193 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.test.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.test.ts @@ -47,6 +47,7 @@ import { buildAgentPersonaCatalog } from "../agents/agentPersonaRouting.ts"; import { playbookTools } from "../playbooks/mcp.ts"; import { makePlaybookCrewRelay } from "../playbooks/PlaybookCrewRelay.ts"; import { crewLaunchReportText } from "./crewGateNotice.ts"; +import { crewMemberModelsLayer } from "../test-support/crewMemberModels.ts"; import { crewSeatFromInput } from "./mcp/handlers.ts"; import { J5ProposeCrewInput } from "./mcp/tools.ts"; import { PlaybookStore, playbookStoreLayer } from "../playbooks/PlaybookStore.ts"; @@ -1752,9 +1753,18 @@ const playbookFixtureWithSettings = ( const barrier = yield* Ref.make | null>(null); const arrivals = yield* Ref.make(0); const providers = yield* Ref.make>([codex]); + // One settings layer object, so a test's settings change reaches the launcher's model check. + const settingsLayer = ServerSettings.layerTest(overrides); const layer = crewProposalLayer.pipe( - Layer.provideMerge(ServerSettings.layerTest(overrides)), + Layer.provideMerge(settingsLayer), Layer.provideMerge(crewLaunchLayer), + Layer.provideMerge( + crewMemberModelsLayer({ + providers: [codex], + settingsLayer, + projectTitle: "Billing Migration", + }), + ), Layer.provideMerge(Layer.mock(CrewLaunchReporter)({ watch: () => Effect.void })), Layer.provideMerge(playbookStoreLayer), Layer.provideMerge(fakeSpawnWorkspaceLayer({ checkout: noRepository })), @@ -3384,6 +3394,113 @@ it.effect("refuses a signed-out provider before recording an automatic launch or }).pipe(Effect.scoped), ); +const codexSol = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" }; + +it.effect("refuses a model off the list before recording an automatic launch or addition", () => + Effect.gen(function* () { + const { layer, commands } = yield* playbookFixtureWithSettings({ + crewAutoApprove: true, + crewMemberModels: [], + }); + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const store = yield* AgentCrewProposalService; + const settings = yield* ServerSettings.ServerSettingsService; + const input = { + requestKey: "model-roster", + captain, + displayName: "Models", + brief: "Inspect", + seats: [custom("scout")], + }; + // The Captain's own model is what the custom seat inherits, and nothing is checked. + const refused = yield* gate.propose(input).pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchModelNotEligibleError"); + assert.include(refused.message, "scout"); + assert.include(refused.message, "Models for custom members in Agent Setup"); + assert.lengthOf(yield* store.listForCaptain(captainId), 0); + assert.lengthOf(yield* Ref.get(commands), 0); + yield* settings.updateSettings({ crewMemberModels: [codexSol] }); + const launched = yield* gate.propose(input); + assert.equal(launched.proposal.status, "approved"); + yield* settings.updateSettings({ crewMemberModels: [] }); + const commandsBefore = (yield* Ref.get(commands)).length; + const addition = yield* gate + .requestMember({ + requestKey: "model-addition", + captain, + crewInstanceId: launched.instance!.id, + seat: custom("reviewer"), + brief: null, + }) + .pipe(Effect.flip); + assert.equal(addition._tag, "CrewLaunchModelNotEligibleError"); + assert.lengthOf( + (yield* (yield* AgentCrewInstanceService).read(launched.instance!.id))!.members, + 1, + ); + assert.lengthOf(yield* Ref.get(commands), commandsBefore); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a retry of an accepted launch or addition is not held to a list saved since", () => + Effect.gen(function* () { + const { layer, commands } = yield* playbookFixtureWithSettings({ crewAutoApprove: true }); + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const settings = yield* ServerSettings.ServerSettingsService; + const input = { + requestKey: "accepted-roster", + captain, + displayName: "Accepted", + brief: "Inspect", + seats: [custom("scout")], + }; + const launched = yield* gate.propose(input); + const addition = { + requestKey: "accepted-addition", + captain, + crewInstanceId: launched.instance!.id, + seat: custom("reviewer"), + brief: null, + }; + const added = yield* gate.requestMember(addition); + const commandsBefore = (yield* Ref.get(commands)).length; + // The person saves a list that leaves out the model both seats already run on. + yield* settings.updateSettings({ crewMemberModels: [] }); + const replayedLaunch = yield* gate.propose(input); + const replayedAddition = yield* gate.requestMember(addition); + assert.equal(replayedLaunch.proposal.id, launched.proposal.id); + assert.equal(replayedAddition.proposal.id, added.proposal.id); + assert.lengthOf(yield* Ref.get(commands), commandsBefore); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + +it.effect("a preview refuses a seat whose model is off the list until it is checked", () => + Effect.gen(function* () { + const { layer } = yield* playbookFixtureWithSettings({ crewMemberModels: [] }); + yield* Effect.gen(function* () { + const gate = yield* CrewProposalService; + const settings = yield* ServerSettings.ServerSettingsService; + const opened = yield* gate.propose({ + requestKey: "model-preview", + captain, + displayName: "Preview", + brief: "Inspect", + seats: [custom("scout")], + }); + assert.equal(opened.proposal.status, "open"); + const refused = yield* gate.preview({ proposalId: opened.proposal.id }).pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchModelNotEligibleError"); + yield* settings.updateSettings({ crewMemberModels: [codexSol] }); + const preview = yield* gate.preview({ proposalId: opened.proposal.id }); + assert.equal(preview.seats[0]?.modelSelection.model, "gpt-5.6-sol"); + }).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped), +); + it.effect( "direct additions preserve supervised access and launch only once on concurrent retries", () => diff --git a/apps/server/src/j5/a2a/CrewProposalService.ts b/apps/server/src/j5/a2a/CrewProposalService.ts index 0e65eb8529ae1..1d6a8d0b9fdcc 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.ts @@ -1005,6 +1005,7 @@ export const layer = Layer.effect( Effect.catchTags({ CrewProposalRequestError: refused, CrewLaunchSeatUnavailableError: refused, + CrewLaunchModelNotEligibleError: refused, CrewLaunchCapError: refused, CrewLaunchSeatConflictError: refused, CrewStepAlreadyOwnedError: refused, diff --git a/apps/server/src/j5/a2a/SpawnAgentService.ts b/apps/server/src/j5/a2a/SpawnAgentService.ts index 11a691be7309d..a8231d5753079 100644 --- a/apps/server/src/j5/a2a/SpawnAgentService.ts +++ b/apps/server/src/j5/a2a/SpawnAgentService.ts @@ -37,6 +37,7 @@ import { } from "../../orchestration-v2/DispatchModeLimit.ts"; import { makeAgentPersonaLibrary } from "../agents/agentPersonaLibrary.ts"; +import { CrewMemberModels } from "../agents/crewMemberModels.ts"; import { translateAgentPersonaProviderPolicy } from "../agents/agentPersonaProviderPolicy.ts"; import { prepareAgentPersonaPeerSpawn } from "../agents/agentPersonaSpawn.ts"; @@ -478,6 +479,19 @@ const spawn = Effect.fn("j5.a2a.spawnAgent")(function* ( }), ), ); + // A persona runs on its own model. A plain agent runs on one the project's list allows, and a + // retry finishes the agent its first attempt created, so only a first attempt is held to it. + if (persona === undefined && firstAttempt) + yield* (yield* CrewMemberModels) + .assertEligible({ projectId: target, selection: modelSelection }) + .pipe( + Effect.mapError((error) => + stateError( + error.message, + "Retry j5_spawn_agent with one of the eligible models, or name a persona.", + ), + ), + ); if (input.scratch === true && input.workspace.type !== "root") { return yield* stateError( "An agent without a project works in a folder of its own, not in a checkout or a worktree.", diff --git a/apps/server/src/j5/a2a/clientActionRpc.ts b/apps/server/src/j5/a2a/clientActionRpc.ts index 3e2739732dddb..6db431a25ebec 100644 --- a/apps/server/src/j5/a2a/clientActionRpc.ts +++ b/apps/server/src/j5/a2a/clientActionRpc.ts @@ -59,6 +59,7 @@ const proposalFailure = failAsJ5ActionError({ "CrewProposalNotOpenError", "CrewProposalRequestError", "CrewLaunchSeatUnavailableError", + "CrewLaunchModelNotEligibleError", "CrewLaunchCapError", "CrewLaunchSeatConflictError", "CrewStepAlreadyOwnedError", diff --git a/apps/server/src/j5/a2a/mcp/handlers.test.ts b/apps/server/src/j5/a2a/mcp/handlers.test.ts index b13e707bb0a44..d7e2908f4f702 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.test.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.test.ts @@ -44,6 +44,7 @@ import { import { DispatchModeLimit } from "../../../orchestration-v2/DispatchModeLimit.ts"; import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts"; import { ProviderRegistry } from "../../../provider/ProviderRegistry.ts"; +import { permissiveCrewMemberModels } from "../../test-support/crewMemberModels.ts"; import { type AgentCrewInstance, AgentCrewInstanceService } from "../AgentCrewInstanceService.ts"; import { ArchiveCrewConfirmationRequiredError, @@ -1290,6 +1291,7 @@ it.effect("preflights home before creation and records facts before the one stab orchestrator, Layer.mock(ParticipantPlacementService)({}), Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([]) }), + permissiveCrewMemberModels, Layer.mock(AgentCrewInstanceService)({ findMembership: () => Effect.succeed(null) }), Layer.mock(A2ADeliveryWorker)({ notify: Effect.void }), Layer.mock(ArchiveCrewService)({}), @@ -1454,6 +1456,7 @@ it.effect("refuses spawn before thread creation when the caller is a Subagent", dispatch: () => Ref.update(dispatches, (count) => count + 1).pipe(Effect.as({} as never)), }), Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([]) }), + permissiveCrewMemberModels, Layer.mock(AgentCrewInstanceService)({ findMembership: () => Effect.succeed(null) }), Layer.mock(A2ADeliveryWorker)({ notify: Effect.void }), Layer.mock(ArchiveCrewService)({}), @@ -1658,6 +1661,7 @@ it.effect("spawns a saved agent as a Peer Agent only within its declared routes" }), }), Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([codex, claude]) }), + permissiveCrewMemberModels, Layer.mock(AgentCrewInstanceService)({ findMembership: () => Effect.succeed(null) }), Layer.mock(ParticipantPlacementService)({}), Layer.mock(A2ADeliveryWorker)({ notify: Effect.void }), @@ -1982,6 +1986,7 @@ it.effect("archives a crew only as a unit through its captain with one confirmat threadManagementMock({}), Layer.mock(OrchestratorMcpService)({}), Layer.mock(ProviderRegistry)({}), + permissiveCrewMemberModels, Layer.mock(ParticipantPlacementService)({}), Layer.mock(AgentCrewInstanceService)({}), Layer.mock(CrewProposalService)({}), @@ -2119,6 +2124,7 @@ it.effect("lists saved agents with purpose, policy, availability, and route", () threadManagementMock({}), Layer.mock(OrchestratorMcpService)({}), Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed([codex]) }), + permissiveCrewMemberModels, Layer.mock(AgentCrewInstanceService)({ findMembership: () => Effect.succeed(null) }), Layer.mock(ParticipantPlacementService)({}), Layer.mock(A2ADeliveryWorker)({ notify: Effect.void }), @@ -2228,6 +2234,7 @@ it.effect("routes crew proposals through a captain that is not itself a crew mem }), Layer.mock(OrchestratorMcpService)({}), Layer.mock(ProviderRegistry)({}), + permissiveCrewMemberModels, Layer.mock(AgentCrewInstanceService)({ findMembership: () => Ref.get(membership), listForCaptain: () => Effect.succeed([]), diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index bba5b87b8d0d1..dea1435fd841f 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -227,13 +227,15 @@ const crewProposalNextStep = (error: CrewProposalError) => ? error.nextStep : error._tag === "CrewLaunchSeatUnavailableError" ? "Choose a different persona from j5_list_personas or ask the user to fix that persona, then retry." - : error._tag === "CrewLaunchCapError" - ? "The crew is full. Work with the seats it has, or propose a new crew for the extra work." - : error._tag === "CrewLaunchSeatConflictError" - ? "Choose a seat name the crew does not already use, then retry." - : error._tag === "CrewStepAlreadyOwnedError" - ? "Claim only steps no seat owns yet, then retry." - : "Retry with the same client_request_id; recovery is forward-only."; + : error._tag === "CrewLaunchModelNotEligibleError" + ? "Give that custom member one of the eligible models above, or leave its model unset to use yours if yours is eligible, then retry." + : error._tag === "CrewLaunchCapError" + ? "The crew is full. Work with the seats it has, or propose a new crew for the extra work." + : error._tag === "CrewLaunchSeatConflictError" + ? "Choose a seat name the crew does not already use, then retry." + : error._tag === "CrewStepAlreadyOwnedError" + ? "Claim only steps no seat owns yet, then retry." + : "Retry with the same client_request_id; recovery is forward-only."; const projectCrewProposal = (outcome: CrewProposalOutcome) => ({ proposal_id: outcome.proposal.id, diff --git a/apps/server/src/j5/a2a/mcp/orchestratorSurface.test.ts b/apps/server/src/j5/a2a/mcp/orchestratorSurface.test.ts index 10c2c96d10d21..34926f14f19da 100644 --- a/apps/server/src/j5/a2a/mcp/orchestratorSurface.test.ts +++ b/apps/server/src/j5/a2a/mcp/orchestratorSurface.test.ts @@ -17,6 +17,7 @@ import { import { OrchestratorMcpService } from "../../../mcp/OrchestratorMcpService.ts"; import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts"; import { ProviderRegistry } from "../../../provider/ProviderRegistry.ts"; +import { permissiveCrewMemberModels } from "../../test-support/crewMemberModels.ts"; import { J5OrchestratorSurface, J5_ORCHESTRATOR_CAPABILITIES_DESCRIPTION, @@ -107,6 +108,7 @@ const TestLayer = McpHttpServer.toolkitRegistration( }), Layer.mock(ThreadManagementService)({}), Layer.mock(ProviderRegistry)({}), + permissiveCrewMemberModels, ), ), Layer.provideMerge(McpServer.McpServer.layer), diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index e5b0075984e55..e3fb43f03d830 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -29,6 +29,7 @@ import { OrchestratorMcpService } from "../../../mcp/OrchestratorMcpService.ts"; import { OrchestratorV2 } from "../../../orchestration-v2/Orchestrator.ts"; import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts"; import { ProviderRegistry } from "../../../provider/ProviderRegistry.ts"; +import { CrewMemberModels } from "../../agents/crewMemberModels.ts"; import { AgentCrewInstanceService } from "../AgentCrewInstanceService.ts"; import { ArchiveCrewService } from "../ArchiveCrewService.ts"; import { @@ -640,6 +641,8 @@ const spawnDependencies = [ // A Crew member is refused before anything is created (members never spawn Peer Agents). AgentCrewInstanceService, ProviderRegistry, + // A plain agent's model is held to the project's list of models for custom members. + CrewMemberModels, // Another project, the "No project" project and its per-thread folder, and brief attachments. ProjectService, ManagedProjectFolders, diff --git a/apps/server/src/j5/a2a/runtimeLayer.ts b/apps/server/src/j5/a2a/runtimeLayer.ts index dace4f4e02276..f2f3e3ea0fcdf 100644 --- a/apps/server/src/j5/a2a/runtimeLayer.ts +++ b/apps/server/src/j5/a2a/runtimeLayer.ts @@ -16,6 +16,7 @@ import { layer as archiveCrewLayer } from "./ArchiveCrewService.ts"; import { layerNotifying as agentCrewProposalNotifyingLayer } from "./AgentCrewProposalService.ts"; import { manualLayer as crewLaunchReporterLayer } from "./CrewLaunchReporter.ts"; import { layer as crewLaunchLayer } from "./CrewLaunchService.ts"; +import { layer as crewMemberModelsLayer } from "../agents/crewMemberModels.ts"; import { layer as crewProposalLayer } from "./CrewProposalService.ts"; import { layer as crewSeatFinishNotifierLayer } from "./CrewSeatFinishNotifier.ts"; import * as NativeQuestionNotifier from "./NativeQuestionNotifier.ts"; @@ -181,6 +182,7 @@ export const makeJ5A2AAuxiliaryLayer = ( const crewLaunchProvided = crewLaunchLayer.pipe( Layer.provideMerge(agentCrewInstanceLayer), Layer.provideMerge(spawnWorkspaceProvided), + Layer.provideMerge(crewMemberModelsLayer), ); // The report watches the seats an approval launched and tells the Captain how they started; the // finish notifier's stream feeds it, so one stream serves every Crew reaction. diff --git a/apps/server/src/j5/a2a/spawnWorkspace.test.ts b/apps/server/src/j5/a2a/spawnWorkspace.test.ts index 857225fdb3b8b..87d725f71926f 100644 --- a/apps/server/src/j5/a2a/spawnWorkspace.test.ts +++ b/apps/server/src/j5/a2a/spawnWorkspace.test.ts @@ -13,6 +13,7 @@ import { type OrchestrationV2ServerCommand, type OrchestrationV2ThreadProjection, type RuntimeMode, + type ServerProvider, } from "@t3tools/contracts"; import * as Context from "effect/Context"; import { layerMemory } from "../../persistence/Sqlite.ts"; @@ -63,6 +64,11 @@ import { type SpawnCheckout, } from "./spawnWorkspace.ts"; import { type FakeCheckout, fakeSpawnWorkspaceLayer } from "./test-support/spawnWorkspaceFakes.ts"; +import { CrewMemberModels } from "../agents/crewMemberModels.ts"; +import { + crewMemberModelsLayer, + permissiveCrewMemberModels, +} from "../test-support/crewMemberModels.ts"; const checkout = ( overrides: Partial> = {}, @@ -187,6 +193,8 @@ const spawnHarness = (input: { readonly beforeProjectRead?: Effect.Effect; /** Who calls; the thread caller unless a test calls as an outside agent. */ readonly scope?: McpInvocationScope; + /** The check on a plain agent's model; every model is eligible unless a test saves a list. */ + readonly memberModels?: Layer.Layer; }) => Effect.gen(function* () { const log = yield* Ref.make>([]); @@ -213,6 +221,7 @@ const spawnHarness = (input: { acceptsUrgency: false, } satisfies ParticipantDirectoryRow; const dependencies = Layer.mergeAll( + input.memberModels ?? permissiveCrewMemberModels, Layer.mock(A2ASendService)({ listParticipants: () => Effect.succeed([callerRow]) }), Layer.mock(A2AHomeRegistrar)({ getHomeForThread: () => @@ -583,6 +592,74 @@ it.effect("spawns into another project's main checkout, as a root of that projec }), ); +const codexSolAndTerra = { + instanceId: ProviderInstanceId.make("codex"), + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + status: "ready", + availability: "available", + models: ["gpt-5.6-sol", "gpt-5.6-terra"].map((slug) => ({ slug, name: slug })), +} as unknown as ServerProvider; +const terraOnly = { + crewMemberModels: [{ instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-terra" }], +}; + +it.effect("a plain spawn runs on a model its project's list allows", () => + Effect.gen(function* () { + const { layer, call, commands } = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + memberModels: crewMemberModelsLayer({ + providers: [codexSolAndTerra], + settings: { + ...terraOnly, + // The other project keeps every model, so the list that applies is the target's. + projectSettingsOverrides: { [otherProjectId]: { crewMemberModels: null } }, + }, + projectTitle: "Billing Migration", + }), + }); + yield* Effect.gen(function* () { + const refused = yield* call({ ...spawnArgs, client_request_id: "off-list" }); + assert.isTrue(refused.isFailure); + for (const part of [ + "Model gpt-5.6-sol on codex", + "Billing Migration", + "Models for custom members in Agent Setup", + "codex/gpt-5.6-terra", + ]) + assert.include(message(refused), part); + assert.lengthOf(yield* Ref.get(commands), 0, "a refused spawn creates nothing"); + const elsewhere = yield* call({ + ...spawnArgs, + project_id: LedgerProjectId.make(otherProjectId), + workspace: { type: "root" }, + client_request_id: "other-project-list", + }); + assert.isFalse(elsewhere.isFailure); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect( + "a retry of a spawn that already created its agent is not held to a list saved since", + () => + Effect.gen(function* () { + const { layer, call } = yield* spawnHarness({ + checkout: { isRepo: true, refName: "j5/main" }, + existingChildRuntimeMode: "full-access", + memberModels: crewMemberModelsLayer({ + providers: [codexSolAndTerra], + settings: terraOnly, + }), + }); + yield* Effect.gen(function* () { + const replayed = yield* call({ ...spawnArgs, client_request_id: "already-created" }); + assert.isFalse(replayed.isFailure); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("spawns an agent with no project into a folder of its own", () => Effect.gen(function* () { const { layer, call, commands } = yield* spawnHarness({ diff --git a/apps/server/src/j5/agents/agentDelegation.ts b/apps/server/src/j5/agents/agentDelegation.ts index b546539f7afd3..732ea59829bf3 100644 --- a/apps/server/src/j5/agents/agentDelegation.ts +++ b/apps/server/src/j5/agents/agentDelegation.ts @@ -13,6 +13,7 @@ import { OrchestratorMcpService } from "../../mcp/OrchestratorMcpService.ts"; import { ThreadManagementService } from "../../orchestration-v2/ThreadManagementService.ts"; import * as ProviderRegistry from "../../provider/ProviderRegistry.ts"; import { invokeAgent } from "./agentInvocation.ts"; +import { CrewMemberModels } from "./crewMemberModels.ts"; /** * Upstream's delegate_task input plus an optional persona. With `persona`, the server applies @@ -51,6 +52,8 @@ export const J5DelegateTaskTool = Tool.make("delegate_task", { OrchestratorMcpService, ThreadManagementService, ProviderRegistry.ProviderRegistry, + // A plain child's model is held to the project's list of models for custom members. + CrewMemberModels, ], }) .annotate(Tool.Title, "Delegate a child task") @@ -62,7 +65,22 @@ export const delegateTask = Effect.fn("j5.delegateTask")(function* (input: J5Del if (personaId === undefined) { const scope = yield* McpInvocationContext; const service = yield* OrchestratorMcpService; - return yield* service.delegateTask(scope, delegate); + const memberModels = yield* CrewMemberModels; + // A persona runs on its own model; a plain child, even one that inherits its parent's model, + // runs on one the project's list allows. Upstream calls this with the model it resolved. + return yield* service.delegateTask(scope, { + ...delegate, + authorizeTarget: ({ projectId, modelSelection }) => + memberModels.assertEligible({ projectId, selection: modelSelection }).pipe( + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ + code: "model_unavailable", + message: `${error.message} Retry with target set to one of them as providerInstanceId and model.`, + }), + ), + ), + }); } if (delegate.target !== undefined || delegate.runtimeMode !== undefined) { return yield* new OrchestratorMcpFailure({ diff --git a/apps/server/src/j5/agents/agentSubagent.integration.test.ts b/apps/server/src/j5/agents/agentSubagent.integration.test.ts index 78e45e94c6b2e..f2edc98c3895f 100644 --- a/apps/server/src/j5/agents/agentSubagent.integration.test.ts +++ b/apps/server/src/j5/agents/agentSubagent.integration.test.ts @@ -37,12 +37,18 @@ import { ScheduledTaskService } from "../../scheduledTasks/ScheduledTaskService. import { BUILT_IN_AGENT_PERSONAS } from "./agentPersonas.ts"; import { personaLibraryLayer } from "../test-support/personaLibrary.ts"; import { delegateTask } from "./agentDelegation.ts"; +import { CrewMemberModels } from "./crewMemberModels.ts"; +import { + crewMemberModelsLayer, + permissiveCrewMemberModels, +} from "../test-support/crewMemberModels.ts"; import { invokeAgent } from "./agentInvocation.ts"; const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: BUILT_IN_AGENT_PERSONAS.scout.modelRoute[0].model, }; +const otherModel = "gpt-5.6-other"; const provider: ServerProvider = { instanceId: modelSelection.instanceId, driver: ProviderDriverKind.make("codex"), @@ -55,23 +61,21 @@ const provider: ServerProvider = { availability: "available", slashCommands: [], skills: [], - models: [ - { - slug: modelSelection.model, - name: "Model", - isCustom: false, - capabilities: { - optionDescriptors: [ - { - id: "reasoningEffort", - label: "Reasoning", - type: "select", - options: [{ id: "high", label: "High" }], - }, - ], - }, + models: [modelSelection.model, otherModel].map((slug) => ({ + slug, + name: "Model", + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "reasoningEffort", + label: "Reasoning", + type: "select" as const, + options: [{ id: "high", label: "High" }], + }, + ], }, - ], + })), }; const adapter = { instanceId: modelSelection.instanceId, @@ -106,97 +110,106 @@ const mcp = Mcp.layer.pipe( Layer.provide(settings), Layer.provide(NodeServices.layer), ); -const testLayer = Layer.mergeAll( - orchestration, - threads, - registry, - mcp, - Projections.layer.pipe(Layer.provide(database)), - NodeServices.layer, -).pipe( - Layer.provideMerge(personaLibraryLayer("j5-saved-subagent-", [BUILT_IN_AGENT_PERSONAS.scout])), -); +const makeTestLayer = (memberModels: Layer.Layer) => + Layer.mergeAll( + orchestration, + threads, + registry, + mcp, + memberModels, + Projections.layer.pipe(Layer.provide(database)), + NodeServices.layer, + ).pipe( + Layer.provideMerge(personaLibraryLayer("j5-saved-subagent-", [BUILT_IN_AGENT_PERSONAS.scout])), + ); +const testLayer = makeTestLayer(permissiveCrewMemberModels); -it.effect("persists the saved persona on a nested child and reuses that child on retry", () => - Effect.gen(function* () { - const orchestrator = yield* OrchestratorV2; - const projections = yield* Projections.ProjectionStoreV2; - const now = yield* DateTime.now; - const threadId = ThreadId.make("parent"); - const runId = RunId.make("parent-run"); - const nodeId = NodeId.make("parent-node"); - yield* orchestrator.dispatch({ - type: "thread.create", - commandId: CommandId.make("parent-create"), - createdBy: "user", - creationSource: "web", +/** A parent thread with an active run, as the tool call of a running agent sees it. */ +const runningParent = Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + const projections = yield* Projections.ProjectionStoreV2; + const now = yield* DateTime.now; + const threadId = ThreadId.make("parent"); + const runId = RunId.make("parent-run"); + const nodeId = NodeId.make("parent-node"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("parent-create"), + createdBy: "user", + creationSource: "web", + threadId, + projectId: ProjectId.make("project"), + title: "Parent conversation", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* projections.apply({ + id: EventId.make("parent-run-event"), + type: "run.updated", + threadId, + occurredAt: now, + payload: { + id: runId, threadId, - projectId: ProjectId.make("project"), - title: "Parent conversation", + ordinal: 1, + providerInstanceId: modelSelection.instanceId, modelSelection, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - }); - yield* projections.apply({ - id: EventId.make("parent-run-event"), - type: "run.updated", + providerThreadId: null, + userMessageId: MessageId.make("parent-message"), + rootNodeId: nodeId, + activeAttemptId: null, + status: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + }); + yield* projections.apply({ + id: EventId.make("parent-node-event"), + type: "node.updated", + threadId, + occurredAt: now, + payload: { + id: nodeId, threadId, - occurredAt: now, - payload: { - id: runId, - threadId, - ordinal: 1, - providerInstanceId: modelSelection.instanceId, - modelSelection, - providerThreadId: null, - userMessageId: MessageId.make("parent-message"), - rootNodeId: nodeId, - activeAttemptId: null, - status: "running", - requestedAt: now, - startedAt: now, - completedAt: null, - checkpointId: null, - contextHandoffId: null, - }, - }); - yield* projections.apply({ - id: EventId.make("parent-node-event"), - type: "node.updated", + runId, + parentNodeId: null, + rootNodeId: nodeId, + kind: "root_turn", + status: "running", + countsForRun: true, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: now, + completedAt: null, + }, + }); + const scope = { + environmentId: EnvironmentId.make("environment"), + requestNamespace: "session", + thread: { threadId, - occurredAt: now, - payload: { - id: nodeId, - threadId, - runId, - parentNodeId: null, - rootNodeId: nodeId, - kind: "root_turn", - status: "running", - countsForRun: true, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: null, - runtimeRequestId: null, - checkpointScopeId: null, - startedAt: now, - completedAt: null, - }, - }); - const scope = { - environmentId: EnvironmentId.make("environment"), - requestNamespace: "session", - thread: { - threadId, - providerInstanceId: modelSelection.instanceId, - providerSessionId: "session", - }, - client: undefined, - capabilities: new Set(["orchestration" as const]), - issuedAt: 1, - }; + providerInstanceId: modelSelection.instanceId, + providerSessionId: "session", + }, + client: undefined, + capabilities: new Set(["orchestration" as const]), + issuedAt: 1, + }; + return { orchestrator, scope, threadId }; +}); + +it.effect("persists the saved persona on a nested child and reuses that child on retry", () => + Effect.gen(function* () { + const { orchestrator, scope, threadId } = yield* runningParent; const request = invokeAgent({ personaId: "scout", task: "Return a short evidence brief.", @@ -243,3 +256,76 @@ it.effect("persists the saved persona on a nested child and reuses that child on assert.equal(plainChild.thread.lineage.relationshipToParent, "subagent"); }).pipe(Effect.provide(testLayer)), ); + +const settingsLayer = ServerSettings.layerTest({}); +const listedLayer = Layer.merge( + makeTestLayer( + crewMemberModelsLayer({ + providers: [provider], + settingsLayer, + projectTitle: "Billing Migration", + }), + ), + settingsLayer, +); + +it.effect("holds a plain delegated child to the list, inherited model included", () => + Effect.gen(function* () { + const { orchestrator, scope } = yield* runningParent; + const settings = yield* ServerSettings.ServerSettingsService; + const asParent = Effect.provideService(McpInvocationContext, scope); + const plain = (clientRequestId: string, target?: { readonly model: string }) => + delegateTask({ + task: "Plain child work.", + clientRequestId, + ...(target === undefined + ? {} + : { target: { providerInstanceId: modelSelection.instanceId, model: target.model } }), + }).pipe(asParent); + + // Until a list is saved, the child inherits the parent's model as it always did. + const free = yield* plain("free"); + assert.equal( + (yield* orchestrator.getThreadProjection(free.childThreadId)).thread.modelSelection.model, + modelSelection.model, + ); + + // The parent's own model is off the list, so inheriting it is refused with what to use. + yield* settings.updateSettings({ + crewMemberModels: [{ instanceId: modelSelection.instanceId, model: otherModel }], + }); + const refused = yield* plain("inherits").pipe(Effect.flip); + assert.equal(refused.code, "model_unavailable"); + for (const part of [ + modelSelection.model, + "Billing Migration", + "Models for custom members in Agent Setup", + `codex/${otherModel}`, + "Retry with target", + ]) + assert.include(refused.message, part); + + // A persona runs on its own model whatever the list says; an explicit checked target works. + const persona = yield* delegateTask({ + task: "Return a short evidence brief.", + persona: "scout", + clientRequestId: "persona", + }).pipe(asParent); + assert.equal( + (yield* orchestrator.getThreadProjection(persona.childThreadId)).thread.modelSelection.model, + modelSelection.model, + ); + const explicit = yield* plain("explicit", { model: otherModel }); + assert.equal( + (yield* orchestrator.getThreadProjection(explicit.childThreadId)).thread.modelSelection.model, + otherModel, + ); + + // A list saved afterwards does not refuse the retry of a delegation already accepted. + yield* settings.updateSettings({ crewMemberModels: [] }); + const replayed = yield* plain("explicit", { model: otherModel }); + assert.equal(replayed.childThreadId, explicit.childThreadId); + const none = yield* plain("fresh", { model: otherModel }).pipe(Effect.flip); + assert.include(none.message, "nothing is checked"); + }).pipe(Effect.provide(listedLayer)), +); diff --git a/apps/server/src/j5/agents/crewMemberModels.ts b/apps/server/src/j5/agents/crewMemberModels.ts new file mode 100644 index 0000000000000..0d5d3ec1c0068 --- /dev/null +++ b/apps/server/src/j5/agents/crewMemberModels.ts @@ -0,0 +1,85 @@ +import type { ModelSelection, ProjectId } from "@t3tools/contracts"; +import { + crewMemberModelRefusal, + eligibleCrewMemberModels, + isCrewMemberModelChecked, +} from "@t3tools/contracts/j5"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { ProjectService } from "../../project/ProjectService.ts"; +import { ProviderRegistry } from "../../provider/ProviderRegistry.ts"; +import * as ServerSettings from "../../serverSettings.ts"; + +/** A model outside the project's "Models for custom members" list, with what to use instead. */ +export class CrewMemberModelNotEligibleError extends Schema.TaggedError()( + "CrewMemberModelNotEligibleError", + { + projectId: Schema.String, + projectTitle: Schema.String, + instanceId: Schema.String, + model: Schema.String, + eligible: Schema.Array( + Schema.Struct({ instanceId: Schema.String, model: Schema.String, name: Schema.String }), + ), + }, +) { + override get message(): string { + return crewMemberModelRefusal({ + selection: this, + projectTitle: this.projectTitle, + eligible: this.eligible, + }); + } +} + +/** + * The one place that decides whether a resolved model may run a custom worker in a project: a + * Crew's custom member, a plain `j5_spawn_agent`, or a plain `delegate_task`. Persona seats that + * keep their persona's model never reach it. + */ +export class CrewMemberModels extends Context.Service< + CrewMemberModels, + { + readonly assertEligible: (input: { + readonly projectId: ProjectId; + readonly selection: Pick; + }) => Effect.Effect; + } +>()("t3/j5/agents/crewMemberModels") {} + +export const layer = Layer.effect( + CrewMemberModels, + Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + const registry = yield* ProviderRegistry; + const projects = yield* ProjectService; + const assertEligible: CrewMemberModels["Service"]["assertEligible"] = Effect.fn( + "j5.crewMemberModels.assertEligible", + )(function* ({ projectId, selection }) { + const list = yield* settings.getSettings.pipe( + Effect.map((all) => resolveProjectSettings(all, projectId).settings.crewMemberModels), + Effect.orDie, + ); + if (isCrewMemberModelChecked(list, selection)) return; + const eligible = eligibleCrewMemberModels(list, yield* registry.getProviders); + const projectTitle = yield* projects.getById(projectId).pipe( + Effect.map(Option.map((project) => project.title)), + Effect.map(Option.getOrElse(() => projectId as string)), + Effect.orElseSucceed(() => projectId as string), + ); + return yield* new CrewMemberModelNotEligibleError({ + projectId, + projectTitle, + instanceId: selection.instanceId, + model: selection.model, + eligible, + }); + }); + return CrewMemberModels.of({ assertEligible }); + }), +); diff --git a/apps/server/src/j5/test-support/crewMemberModels.ts b/apps/server/src/j5/test-support/crewMemberModels.ts new file mode 100644 index 0000000000000..d37194afeea89 --- /dev/null +++ b/apps/server/src/j5/test-support/crewMemberModels.ts @@ -0,0 +1,41 @@ +import type { ServerProvider } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import { ProjectService } from "../../project/ProjectService.ts"; +import { ProviderRegistry } from "../../provider/ProviderRegistry.ts"; +import * as ServerSettings_ from "../../serverSettings.ts"; +import { CrewMemberModels, layer } from "../agents/crewMemberModels.ts"; + +/** For tests of other behavior: every model is eligible, as when no list was ever saved. */ +export const permissiveCrewMemberModels = Layer.mock(CrewMemberModels)({ + assertEligible: () => Effect.void, +}); + +/** + * The real eligibility service over test settings, providers and one project title, so a test + * decides the list and watches the refusal. + */ +export const crewMemberModelsLayer = (input: { + readonly settings?: Parameters[0]; + /** The settings a test also changes through; the same layer object is built once per run. */ + readonly settingsLayer?: ReturnType; + readonly providers: ReadonlyArray; + readonly projectTitle?: string; +}) => + layer.pipe( + Layer.provide( + Layer.mergeAll( + input.settingsLayer ?? ServerSettings_.layerTest(input.settings), + Layer.mock(ProviderRegistry)({ getProviders: Effect.succeed(input.providers) }), + Layer.mock(ProjectService)({ + getById: (id) => + Effect.succeed( + Option.some({ id, title: input.projectTitle ?? "Test project" } as never), + ), + }), + ), + ), + Layer.orDie, + ); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index dff4c6f7a820d..7a0f928f98b74 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -134,6 +134,11 @@ export interface OrchestratorMcpServiceShape { scope: McpInvocationScope, input: OrchestratorMcpDelegateTaskInput & { readonly agentPersonaAssignment?: OrchestrationV2AgentPersonaCommandAssignment; + /** Called with the model the child will run on, before anything is created. */ + readonly authorizeTarget?: (target: { + readonly projectId: ProjectId; + readonly modelSelection: ModelSelection; + }) => Effect.Effect; }, ) => Effect.Effect; readonly taskStatus: ( @@ -1969,6 +1974,11 @@ const make = Effect.gen(function* () { providers, skipProjectEnablementFilter: isRetryOfAcceptedDelegation, }); + if (input.authorizeTarget !== undefined && !isRetryOfAcceptedDelegation) + yield* input.authorizeTarget({ + projectId: parent.thread.projectId, + modelSelection: target.modelSelection, + }); const runtimeMode = yield* resolveRuntimeMode( parent.thread.runtimeMode, input.runtimeMode, diff --git a/apps/server/src/mcp/toolkits/worktree/registration.test.ts b/apps/server/src/mcp/toolkits/worktree/registration.test.ts index 194aa2bffe608..93c0cc4dc3e05 100644 --- a/apps/server/src/mcp/toolkits/worktree/registration.test.ts +++ b/apps/server/src/mcp/toolkits/worktree/registration.test.ts @@ -25,6 +25,7 @@ import { A2AHomeRegistrar } from "../../../j5/a2a/HomeRegistrar.ts"; import { AgentCrewInstanceService } from "../../../j5/a2a/AgentCrewInstanceService.ts"; import { ArchiveCrewService } from "../../../j5/a2a/ArchiveCrewService.ts"; import { CrewProposalService } from "../../../j5/a2a/CrewProposalService.ts"; +import { CrewMemberModels } from "../../../j5/agents/crewMemberModels.ts"; import { CrewStopService } from "../../../j5/a2a/CrewStopService.ts"; import { PeerRegistryService } from "../../../j5/a2a/PeerRegistryService.ts"; import { PlaybookCrewRelay } from "../../../j5/playbooks/PlaybookCrewRelay.ts"; @@ -96,6 +97,7 @@ const layerStubServices = Layer.mergeAll( Layer.mock(AgentCrewInstanceService)({}), Layer.mock(ArchiveCrewService)({}), Layer.mock(CrewProposalService)({}), + Layer.mock(CrewMemberModels)({}), Layer.mock(CrewStopService)({}), Layer.mock(PeerRegistryService)({}), Layer.mock(PlaybookCrewRelay)({}), diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 37449e6e379bc..8ce683e93a29f 100644 --- a/packages/contracts/src/j5.ts +++ b/packages/contracts/src/j5.ts @@ -7,6 +7,7 @@ export * from "./j5/fleet.ts"; export * from "./j5/peerPoll.ts"; export * from "./j5/playbook.ts"; export * from "./j5/access.ts"; +export * from "./j5/crewMemberModels.ts"; export * from "./j5/levels.ts"; export * from "./j5/people.ts"; export * from "./j5/sharedConversation.ts"; diff --git a/packages/contracts/src/j5/crewMemberModels.test.ts b/packages/contracts/src/j5/crewMemberModels.test.ts new file mode 100644 index 0000000000000..991b765aed37f --- /dev/null +++ b/packages/contracts/src/j5/crewMemberModels.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from "vitest"; + +import { ProviderInstanceId } from "../providerInstance.ts"; +import type { ServerProvider } from "../server.ts"; +import { + crewMemberModelCounts, + crewMemberModelRefusal, + eligibleCrewMemberModels, + isCrewMemberModelChecked, +} from "./crewMemberModels.ts"; + +const provider = ( + instanceId: string, + models: ReadonlyArray, + overrides: Partial = {}, +) => + ({ + instanceId: ProviderInstanceId.make(instanceId), + driver: "codex", + enabled: true, + installed: true, + status: "ready", + availability: "available", + models: models.map((slug) => ({ slug, name: slug.toUpperCase() })), + ...overrides, + }) as unknown as ServerProvider; + +const codex = ProviderInstanceId.make("codex"); +const checked = (...models: ReadonlyArray) => + models.map((model) => ({ instanceId: codex, model })); + +describe("crew member models", () => { + const providers = [provider("codex", ["a", "b", "c"]), provider("claude", ["x"])]; + + it("makes every model eligible until a list is saved", () => { + expect(isCrewMemberModelChecked(null, { instanceId: codex, model: "anything" })).toBe(true); + expect(eligibleCrewMemberModels(null, providers).map(({ model }) => model)).toEqual([ + "a", + "b", + "c", + "x", + ]); + expect(crewMemberModelCounts(null, providers)).toEqual({ checked: 4, total: 4 }); + }); + + it("makes only the checked models eligible, so a model new to the catalog starts unchecked", () => { + const list = checked("a", "b"); + expect(isCrewMemberModelChecked(list, { instanceId: codex, model: "b" })).toBe(true); + expect(isCrewMemberModelChecked(list, { instanceId: codex, model: "c" })).toBe(false); + // The same slug on another instance is another model. + expect( + isCrewMemberModelChecked(list, { instanceId: ProviderInstanceId.make("claude"), model: "a" }), + ).toBe(false); + expect(crewMemberModelCounts(list, providers)).toEqual({ checked: 2, total: 4 }); + }); + + it("counts checked models that are in the catalog and keeps stale entries out of the count", () => { + const list = checked("a", "retired"); + expect(crewMemberModelCounts(list, providers)).toEqual({ checked: 1, total: 4 }); + expect(eligibleCrewMemberModels(list, providers).map(({ model }) => model)).toEqual(["a"]); + }); + + it("offers only models of providers that are set up", () => { + const signedOut = provider("cursor", ["z"], { status: "error" }); + const disabled = provider("grok", ["y"], { enabled: false }); + const all = [...providers, signedOut, disabled]; + expect(crewMemberModelCounts(null, all)).toEqual({ checked: 4, total: 4 }); + }); + + it("treats a saved empty list as nothing eligible", () => { + expect(eligibleCrewMemberModels([], providers)).toEqual([]); + expect(crewMemberModelCounts([], providers)).toEqual({ checked: 0, total: 4 }); + }); + + it("names the model, the project, the setting and what is eligible", () => { + const message = crewMemberModelRefusal({ + selection: { instanceId: "codex", model: "c" }, + projectTitle: "Billing Migration", + eligible: eligibleCrewMemberModels(checked("a"), providers), + }); + expect(message).toContain("Model c on codex"); + expect(message).toContain('"Billing Migration"'); + expect(message).toContain("Models for custom members in Agent Setup"); + expect(message).toContain("Eligible models: codex/a."); + }); + + it("says when nothing is eligible, and bounds a long list", () => { + const none = crewMemberModelRefusal({ + selection: { instanceId: "codex", model: "c" }, + projectTitle: "P", + eligible: [], + }); + expect(none).toContain("nothing is checked"); + const many = Array.from({ length: 40 }, (_, index) => ({ + instanceId: "codex", + model: `m${index}`, + })); + const long = crewMemberModelRefusal({ + selection: { instanceId: "codex", model: "c" }, + projectTitle: "P", + eligible: many, + }); + expect(long).toContain("and 10 more"); + expect(long).not.toContain("m39"); + }); +}); diff --git a/packages/contracts/src/j5/crewMemberModels.ts b/packages/contracts/src/j5/crewMemberModels.ts new file mode 100644 index 0000000000000..52457352a5c87 --- /dev/null +++ b/packages/contracts/src/j5/crewMemberModels.ts @@ -0,0 +1,104 @@ +import * as Schema from "effect/Schema"; + +import { TrimmedNonEmptyString } from "../baseSchemas.ts"; +import { ProviderInstanceId } from "../providerInstance.ts"; +import type { ServerProvider, ServerProviderModel } from "../server.ts"; + +/** One checked model: the same `(instance, slug)` key the catalog and `ModelSelection` use. */ +export const CrewMemberModel = Schema.Struct({ + instanceId: ProviderInstanceId, + model: TrimmedNonEmptyString, +}); +export type CrewMemberModel = typeof CrewMemberModel.Type; + +/** + * The models custom Crew members and plain delegated or spawned agents may run on. `null` means + * no list was ever saved and every model is eligible. A saved list holds only the checked pairs, + * so a model new to the catalog is unchecked until someone checks it, and an empty saved list + * makes no model eligible. + */ +export const CrewMemberModels = Schema.NullOr(Schema.Array(CrewMemberModel)); +export type CrewMemberModels = typeof CrewMemberModels.Type; + +export const CREW_MEMBER_MODELS_SETTING_LABEL = "Models for custom members in Agent Setup"; + +type ModelKey = Pick; + +/** + * A provider whose models a person can choose from: the same test the roster card's provider + * picker applies, so the setting and the picker offer the same catalog. + */ +export const isCrewMemberProviderSetUp = ( + provider: Pick, +): boolean => + provider.enabled && + provider.installed && + provider.status === "ready" && + provider.availability !== "unavailable" && + provider.models.length > 0; + +export const isCrewMemberModelChecked = ( + list: CrewMemberModels | undefined, + selection: ModelKey, +): boolean => + list === null || + list === undefined || + list.some( + (entry) => entry.instanceId === selection.instanceId && entry.model === selection.model, + ); + +export interface CrewMemberModelChoice { + readonly instanceId: ServerProvider["instanceId"]; + readonly model: ServerProviderModel["slug"]; + readonly name: string; +} + +/** The catalog models the list makes eligible, in provider order. Stale entries match nothing. */ +export const eligibleCrewMemberModels = ( + list: CrewMemberModels | undefined, + providers: ReadonlyArray, +): ReadonlyArray => + providers.filter(isCrewMemberProviderSetUp).flatMap((provider) => + provider.models + .filter((model) => + isCrewMemberModelChecked(list, { instanceId: provider.instanceId, model: model.slug }), + ) + .map((model) => ({ + instanceId: provider.instanceId, + model: model.slug, + name: model.name, + })), + ); + +/** "6 of 12": checked models that are in the catalog, over the catalog. */ +export const crewMemberModelCounts = ( + list: CrewMemberModels | undefined, + providers: ReadonlyArray, +): { readonly checked: number; readonly total: number } => ({ + checked: eligibleCrewMemberModels(list, providers).length, + total: providers + .filter(isCrewMemberProviderSetUp) + .reduce((count, provider) => count + provider.models.length, 0), +}); + +const MAX_LISTED_MODELS = 30; + +/** + * What a refused model tells the agent or the person: the model, the project, the setting that + * decided it, and the models they can use instead. + */ +export const crewMemberModelRefusal = (input: { + readonly selection: { readonly instanceId: string; readonly model: string }; + readonly projectTitle: string; + readonly eligible: ReadonlyArray<{ readonly instanceId: string; readonly model: string }>; +}): string => { + const listed = input.eligible + .slice(0, MAX_LISTED_MODELS) + .map((choice) => `${choice.instanceId}/${choice.model}`); + const more = input.eligible.length - listed.length; + const alternatives = + input.eligible.length === 0 + ? "No model is eligible: nothing is checked." + : `Eligible models: ${listed.join(", ")}${more > 0 ? `, and ${more} more` : ""}.`; + return `Model ${input.selection.model} on ${input.selection.instanceId} is not eligible for custom members in project "${input.projectTitle}". The project's list is the setting ${CREW_MEMBER_MODELS_SETTING_LABEL}. ${alternatives}`; +}; diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 995570edf557a..84345e49ea81d 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -27,6 +27,7 @@ import { DEFAULT_TEXT_GENERATION_REASONING_EFFORT, ProviderOptionSelections, } from "./model.ts"; +import { CrewMemberModels } from "./j5/crewMemberModels.ts"; import { ModelSelection } from "./modelSelection.ts"; import { ProjectScript, type ProjectMutation } from "./project.ts"; import { DEFAULT_RUNTIME_MODE, RuntimeMode } from "./providerPolicy.ts"; @@ -892,6 +893,7 @@ export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [ "newWorktreesStartFromOrigin", "worktreeSubmodules", "crewAutoApprove", + "crewMemberModels", "defaultAutoPull", "defaultProjectScripts", "enableAgentBrowserAccess", @@ -936,6 +938,7 @@ export const ProjectSettingsOverrides = Schema.Struct({ newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean), worktreeSubmodules: ForwardCompatibleOptional(WorktreeSubmodules), crewAutoApprove: Schema.optionalKey(Schema.Boolean), + crewMemberModels: Schema.optionalKey(CrewMemberModels), defaultAutoPull: Schema.optionalKey(Schema.Boolean), defaultProjectScripts: Schema.optionalKey(Schema.Array(ProjectScript)), enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean), @@ -980,6 +983,7 @@ const NULLABLE_PROJECT_SETTINGS_OVERRIDES: ReadonlySet { expect(resolveProjectSettings(settings, otherProjectId).settings.defaultAutoPull).toBe(true); }); + it("replaces the models for custom members whole, and lets a project hold null or its own list", () => { + const entry = (model: string) => ({ instanceId: ProviderInstanceId.make("codex"), model }); + expect(DEFAULT_SERVER_SETTINGS.crewMemberModels).toBeNull(); + const three = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { + crewMemberModels: [entry("a"), entry("b"), entry("c")], + }); + // A shorter list is the whole list, never merged into the longer one by position. + const one = applyServerSettingsPatch(three, { crewMemberModels: [entry("a")] }); + expect(one.crewMemberModels).toEqual([entry("a")]); + const settings = applyServerSettingsPatch(one, { + projectSettingsOverrides: { + [projectId]: { crewMemberModels: null }, + [otherProjectId]: { crewMemberModels: [entry("z")] }, + }, + }); + const everything = resolveProjectSettings(settings, projectId); + expect(everything.settings.crewMemberModels).toBeNull(); + expect(everything.sources.crewMemberModels).toBe("project"); + expect(resolveProjectSettings(settings, otherProjectId).settings.crewMemberModels).toEqual([ + entry("z"), + ]); + expect(resolveProjectSettings(settings, null).settings.crewMemberModels).toEqual([entry("a")]); + }); + it("keeps the environment text generation model when the override's provider is disabled", () => { const disabledSelection = createModelSelection(ProviderInstanceId.make("claudeAgent"), "opus"); const settings = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { From 1cb6afd4972713de82f7c3e3a0915e45b0b6e724 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 13:49:00 -0400 Subject: [PATCH 02/12] feat(web): choose the models custom Crew members can use in Agent Setup (#744) A Models for custom members row in the Crews section of Agent Setup shows how many catalog models are checked, opens in place, lists each set-up provider's models with checkboxes, warns when a saved list leaves nothing eligible, and notes that personas and native subagents are outside the list. The roster card offers a custom member only the models its project allows. Co-Authored-By: Claude Sonnet 5.5 --- apps/web/src/j5/crew/CrewApprovalSettings.tsx | 2 + .../src/j5/crew/CrewMemberModelsSettings.tsx | 222 ++++++++++++++++++ .../web/src/j5/crew/CrewProposalCard.test.tsx | 31 ++- apps/web/src/j5/crew/CrewProposalCard.tsx | 6 + .../src/j5/crew/CrewProposalMemberDialog.tsx | 4 +- apps/web/src/j5/crew/CrewSeatEditor.tsx | 49 ++-- .../j5/crew/crewMemberModels.logic.test.ts | 93 ++++++++ .../web/src/j5/crew/crewMemberModels.logic.ts | 81 +++++++ apps/web/src/j5/crew/useCrewMemberModels.ts | 26 ++ 9 files changed, 498 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/j5/crew/CrewMemberModelsSettings.tsx create mode 100644 apps/web/src/j5/crew/crewMemberModels.logic.test.ts create mode 100644 apps/web/src/j5/crew/crewMemberModels.logic.ts create mode 100644 apps/web/src/j5/crew/useCrewMemberModels.ts diff --git a/apps/web/src/j5/crew/CrewApprovalSettings.tsx b/apps/web/src/j5/crew/CrewApprovalSettings.tsx index a2bfd635a0fee..639e52c0e3770 100644 --- a/apps/web/src/j5/crew/CrewApprovalSettings.tsx +++ b/apps/web/src/j5/crew/CrewApprovalSettings.tsx @@ -9,6 +9,7 @@ import { useUpdateScopedSettings, } from "../../components/settings/useScopedSettings"; import { Switch } from "../../components/ui/switch"; +import { CrewMemberModelsSettings } from "./CrewMemberModelsSettings"; export function CrewApprovalSettings() { const settings = useScopedSettings(); @@ -41,6 +42,7 @@ export function CrewApprovalSettings() { /> } /> + ); } diff --git a/apps/web/src/j5/crew/CrewMemberModelsSettings.tsx b/apps/web/src/j5/crew/CrewMemberModelsSettings.tsx new file mode 100644 index 0000000000000..3cd7723a918a7 --- /dev/null +++ b/apps/web/src/j5/crew/CrewMemberModelsSettings.tsx @@ -0,0 +1,222 @@ +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentId, ServerProvider } from "@t3tools/contracts"; +import { + crewMemberModelCounts, + isCrewMemberModelChecked, + isCrewMemberProviderSetUp, + type CrewMemberModel, + type CrewMemberModels, +} from "@t3tools/contracts/j5"; +import { Link } from "@tanstack/react-router"; +import { AlertTriangleIcon, ChevronDownIcon, ChevronRightIcon } from "lucide-react"; +import { useMemo, useState } from "react"; + +import { ProviderInstanceIcon } from "../../components/chat/ProviderInstanceIcon"; +import { SettingResetButton, SettingsRow } from "../../components/settings/settingsLayout"; +import { useSettingsScope } from "../../components/settings/SettingsScopeContext"; +import { + useScopedSettings, + useScopedSettingsMixed, + useUpdateScopedSettings, +} from "../../components/settings/useScopedSettings"; +import { Button } from "../../components/ui/button"; +import { Checkbox } from "../../components/ui/checkbox"; +import { deriveProviderInstanceEntries } from "../../providerInstances"; +import { serverEnvironment } from "../../state/server"; +import { useEnvironmentQuery } from "../../state/query"; +import { agentPersonaEnvironment } from "../agents/agentPersonaAtoms"; +import { + crewMemberModelsSummary, + personasOffCrewMemberModels, + setCrewMemberModelChecked, + setCrewMemberProviderChecked, +} from "./crewMemberModels.logic"; + +const NO_ENVIRONMENT = "" as EnvironmentId; + +/** + * The same "New" tag the composer's model picker shows for a model carrying the catalog's `new` + * badge. + */ +function NewTag() { + return ( + + New + + ); +} + +function ProviderModels(props: { + readonly provider: ServerProvider; + readonly providers: ReadonlyArray; + readonly entry: ReturnType[number]; + readonly list: CrewMemberModels; + readonly onChange: (next: ReadonlyArray) => void; +}) { + const { provider, entry, list } = props; + const { checked, total } = crewMemberModelCounts(list, [provider]); + return ( +
+
+
+ + {entry.displayName} + + {checked} of {total} + +
+ +
+
    + {provider.models.map((model) => ( +
  • + +
  • + ))} +
+
+ ); +} + +/** + * Which models custom Crew members, and plain agents started without a persona, may run on. + * Personas keep their own model, and native subagents are outside the list on every provider + * (docs/j5/product/crews.md). + */ +export function CrewMemberModelsSettings() { + const settings = useScopedSettings(); + const mixed = useScopedSettingsMixed(["crewMemberModels"]); + const updateSettings = useUpdateScopedSettings(); + const { target } = useSettingsScope(); + const environmentId = target?.environmentId ?? null; + const list = settings.crewMemberModels; + const [open, setOpen] = useState(false); + const providers = useAtomValue( + serverEnvironment.providersValueAtom(environmentId ?? NO_ENVIRONMENT), + ); + const catalog = useEnvironmentQuery( + environmentId === null ? null : agentPersonaEnvironment.catalog({ environmentId, input: {} }), + ); + const entries = useMemo(() => deriveProviderInstanceEntries(providers ?? []), [providers]); + const known = providers ?? []; + const summary = crewMemberModelsSummary(list, known); + const offList = personasOffCrewMemberModels(catalog.data, list); + const save = (next: ReadonlyArray) => updateSettings({ crewMemberModels: next }); + const Chevron = open ? ChevronDownIcon : ChevronRightIcon; + + return ( + + + ); +} diff --git a/apps/web/src/j5/crew/CrewProposalCard.test.tsx b/apps/web/src/j5/crew/CrewProposalCard.test.tsx index 8bf401ba1ceaa..420025f3fba2b 100644 --- a/apps/web/src/j5/crew/CrewProposalCard.test.tsx +++ b/apps/web/src/j5/crew/CrewProposalCard.test.tsx @@ -15,7 +15,12 @@ import { act } from "react"; import { createRoot, type Root } from "react-dom/client"; import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test"; -const state = vi.hoisted(() => ({ permitted: true, preview: vi.fn(), read: vi.fn() })); +const state = vi.hoisted(() => ({ + permitted: true, + preview: vi.fn(), + read: vi.fn(), + memberModels: null as ReadonlyArray<{ instanceId: string; model: string }> | null, +})); vi.mock("@effect/atom-react", () => ({ useAtomValue: (atom: unknown) => atom })); vi.mock("../state", () => ({ j5Environment: { resolveCrewProposal: { permissionAtom: () => state.permitted } }, @@ -25,6 +30,7 @@ vi.mock("../a2a/ParticipantIdentitiesClient", () => ({ useParticipantLabels: () => new Map([["captain", "Release Captain"]]), })); vi.mock("../sharing/access", () => ({ useCanOperateThread: () => state.permitted })); +vi.mock("./useCrewMemberModels", () => ({ useCrewMemberModels: () => state.memberModels })); vi.mock("../../state/query", () => ({ useEnvironmentQuery: (query: unknown) => ({ data: query === "crew-proposals" ? [proposal] : {} }), })); @@ -142,6 +148,7 @@ beforeEach(() => { }, ); state.permitted = true; + state.memberModels = null; state.preview.mockReset().mockImplementation(preview); state.read.mockReset().mockImplementation(({ input }: { input: { personaId: string } }) => Promise.resolve({ @@ -617,3 +624,25 @@ it("Reset to persona text restores the persona's own and sends no replacement", await click(approve()); expect(resolve.mock.calls[0]?.[1][1]).toEqual(proposal.requestedSeats[1]); }); + +it("offers a custom member only the models its project's list allows", async () => { + state.memberModels = [{ instanceId: "codex", model: "gpt-6" }]; + await render(); + await click(button("Edit seat builder")); + await click(button("builder model")); + expect(option("builder model", "GPT-6")).toBeDefined(); + expect(option("builder model", "Other model")).toBeUndefined(); + await click(option("builder model", "GPT-6")); + // No model of the other provider is on the list, so it is not offered at all. + await click(button("builder provider")); + expect(option("builder provider", "Codex")).toBeDefined(); + expect(option("builder provider", "Claude")).toBeUndefined(); +}); + +it("leaves a persona member's pickers whole, since it runs on its own model", async () => { + state.memberModels = [{ instanceId: "codex", model: "gpt-6" }]; + await render(); + await click(button("Edit seat reviewer")); + await click(button("reviewer model")); + expect(option("reviewer model", "Other model")).toBeDefined(); +}); diff --git a/apps/web/src/j5/crew/CrewProposalCard.tsx b/apps/web/src/j5/crew/CrewProposalCard.tsx index 8c0dfb22ad0c9..6a19ec50b4d3a 100644 --- a/apps/web/src/j5/crew/CrewProposalCard.tsx +++ b/apps/web/src/j5/crew/CrewProposalCard.tsx @@ -17,6 +17,7 @@ import { describePersonaSwap, removedSeatSteps, stepTitle, unownedSteps } from " import { CrewProposalMemberDialog } from "./CrewProposalMemberDialog"; import type { CrewProposalRow } from "./crewProposalDraft"; import { CrewProposalMemberRow } from "./CrewProposalMemberRow"; +import { useCrewMemberModels } from "./useCrewMemberModels"; import { useCrewProposalPreview } from "./useCrewProposalPreview"; import { ComposerBanner } from "../../components/chat/ComposerBanner"; import { useCanOperateThread } from "../sharing/access"; @@ -58,6 +59,10 @@ export function CrewProposalCard(props: { proposal.captainThreadId as ThreadId, ); const canResolve = permitted && writesToCaptain; + const memberModels = useCrewMemberModels( + props.environmentId, + proposal.captainThreadId as ThreadId, + ); const [rows, setRows] = useState( () => readCrewProposalDraft(props.environmentId, proposal.id) ?? @@ -332,6 +337,7 @@ export function CrewProposalCard(props: { previewSeatName={editing.original?.seat ?? proposal.requestedSeats[0]!.seat} environmentId={props.environmentId} workspaceOptions={preview.workspaceOptions} + memberModels={memberModels} agents={agents} disabled={props.busy} onClose={() => setEditing(null)} diff --git a/apps/web/src/j5/crew/CrewProposalMemberDialog.tsx b/apps/web/src/j5/crew/CrewProposalMemberDialog.tsx index ac03dbf8c5ea6..f373d7cd0b2be 100644 --- a/apps/web/src/j5/crew/CrewProposalMemberDialog.tsx +++ b/apps/web/src/j5/crew/CrewProposalMemberDialog.tsx @@ -2,7 +2,7 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; import { XIcon } from "lucide-react"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId } from "@t3tools/contracts"; -import type { CrewWorkspaceOptions } from "@t3tools/contracts/j5"; +import type { CrewMemberModels, CrewWorkspaceOptions } from "@t3tools/contracts/j5"; import { useEffect, useEffectEvent, useMemo, useState, type RefObject } from "react"; import { Button } from "../../components/ui/button"; @@ -33,6 +33,7 @@ export function CrewProposalMemberDialog(props: { previewSeatName: string; environmentId: EnvironmentId | null; workspaceOptions?: CrewWorkspaceOptions | undefined; + memberModels?: CrewMemberModels | undefined; agents: ReadonlyArray<{ personaId: string; displayName: string }>; disabled: boolean; onClose: () => void; @@ -144,6 +145,7 @@ export function CrewProposalMemberDialog(props: { agents={props.agents} runtime={runtime} workspaceOptions={props.workspaceOptions ?? preview.workspaceOptions} + memberModels={props.memberModels} disabled={props.disabled} loadingInstructions={loadingPersona} onChange={setValue} diff --git a/apps/web/src/j5/crew/CrewSeatEditor.tsx b/apps/web/src/j5/crew/CrewSeatEditor.tsx index 1bade9c543ccd..6ecd055c0344f 100644 --- a/apps/web/src/j5/crew/CrewSeatEditor.tsx +++ b/apps/web/src/j5/crew/CrewSeatEditor.tsx @@ -1,6 +1,11 @@ import { useAtomValue } from "@effect/atom-react"; import type { EnvironmentId } from "@t3tools/contracts"; -import type { CrewProposalSeatRuntime, CrewWorkspaceOptions } from "@t3tools/contracts/j5"; +import { + isCrewMemberModelChecked, + type CrewMemberModels, + type CrewProposalSeatRuntime, + type CrewWorkspaceOptions, +} from "@t3tools/contracts/j5"; import { useMemo } from "react"; import { getProviderOptionCurrentValue } from "@t3tools/shared/model"; @@ -39,6 +44,8 @@ interface CrewSeatEditorProps { readonly runtime?: CrewProposalSeatRuntime | undefined; /** What the Captain's repository offers a seat's workspace, from the latest preview. */ readonly workspaceOptions?: CrewWorkspaceOptions | undefined; + /** The project's models for custom members; a custom member's pickers offer only these. */ + readonly memberModels?: CrewMemberModels | undefined; readonly disabled: boolean; readonly loadingInstructions?: boolean; readonly onPersonaChange: (personaId: string) => void; @@ -214,23 +221,38 @@ function CrewSeatWorkspaceField(props: CrewSeatEditorProps) { function CrewSeatRuntimeFields(props: CrewSeatEditorProps & { environmentId: EnvironmentId }) { const providers = useAtomValue(serverEnvironment.providersValueAtom(props.environmentId)) ?? []; + // A custom member runs on a model the project's list allows; a persona keeps its own model, so + // its pickers stay whole (the server checks a persona seat whose model was changed). + const memberModels = props.value.agentId === CUSTOM_AGENT ? props.memberModels : null; const choices = useMemo( () => - providers.filter( - (provider) => - provider.enabled && - provider.installed && - provider.status === "ready" && - provider.availability !== "unavailable" && - provider.models.length > 0, - ), - [providers], + providers.flatMap((provider) => { + if ( + !( + provider.enabled && + provider.installed && + provider.status === "ready" && + provider.availability !== "unavailable" && + provider.models.length > 0 + ) + ) + return []; + const models = provider.models.filter((model) => + isCrewMemberModelChecked(memberModels, { + instanceId: provider.instanceId, + model: model.slug, + }), + ); + return models.length === 0 ? [] : [{ ...provider, models }]; + }), + [providers, memberModels], ); const entries = useMemo(() => deriveProviderInstanceEntries(choices), [choices]); const value = resolvedCrewSeatDraft(props.value, props.runtime); const selection = value.modelSelection; const provider = providers.find(({ instanceId }) => instanceId === selection?.instanceId); const model = provider?.models.find(({ slug }) => slug === selection?.model); + const offered = choices.find(({ instanceId }) => instanceId === selection?.instanceId); const reasoning = crewReasoningDescriptor(model); const reasoningValue = selection?.options?.find(({ id }) => id === reasoning?.id)?.value ?? @@ -312,9 +334,8 @@ function CrewSeatRuntimeFields(props: CrewSeatEditorProps & { environmentId: Env props.disabled || !choices.some((candidate) => candidate.instanceId === activeProvider) } onValueChange={(slug) => { - const nextModel = provider?.models.find((candidate) => candidate.slug === slug); - if (provider && nextModel) - props.onChange(chooseCrewHarness(value, provider, nextModel)); + const nextModel = offered?.models.find((candidate) => candidate.slug === slug); + if (offered && nextModel) props.onChange(chooseCrewHarness(value, offered, nextModel)); }} > @@ -323,7 +344,7 @@ function CrewSeatRuntimeFields(props: CrewSeatEditorProps & { environmentId: Env - {(provider?.models ?? []).map((entry) => ( + {(offered?.models ?? []).map((entry) => ( {entry.name.replace(/^Claude\s+/u, "")} diff --git a/apps/web/src/j5/crew/crewMemberModels.logic.test.ts b/apps/web/src/j5/crew/crewMemberModels.logic.test.ts new file mode 100644 index 0000000000000..27cb127ffe21e --- /dev/null +++ b/apps/web/src/j5/crew/crewMemberModels.logic.test.ts @@ -0,0 +1,93 @@ +import { + ProviderInstanceId, + type OrchestrationV2AgentPersonaCatalog, + type ServerProvider, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + crewMemberModelsSummary, + personasOffCrewMemberModels, + setCrewMemberModelChecked, + setCrewMemberProviderChecked, +} from "./crewMemberModels.logic"; + +const codex = ProviderInstanceId.make("codex"); +const claude = ProviderInstanceId.make("claudeAgent"); +const provider = ( + instanceId: ProviderInstanceId, + models: ReadonlyArray, + overrides: Partial = {}, +) => + ({ + instanceId, + driver: "codex", + enabled: true, + installed: true, + status: "ready", + availability: "available", + models: models.map((slug) => ({ slug, name: slug })), + ...overrides, + }) as unknown as ServerProvider; + +const providers = [provider(codex, ["a", "b", "c"]), provider(claude, ["x"])]; +const pair = (instanceId: ProviderInstanceId, model: string) => ({ instanceId, model }); + +describe("crew member models settings logic", () => { + it("starts from the whole catalog when the first box is unchecked", () => { + const next = setCrewMemberModelChecked(null, providers, pair(codex, "b"), false); + expect(next).toEqual([pair(codex, "a"), pair(codex, "c"), pair(claude, "x")]); + }); + + it("checks a model once and keeps entries for models the catalog no longer lists", () => { + const saved = [pair(codex, "retired")]; + const checked = setCrewMemberModelChecked(saved, providers, pair(codex, "a"), true); + expect(checked).toEqual([pair(codex, "retired"), pair(codex, "a")]); + expect(setCrewMemberModelChecked(checked, providers, pair(codex, "a"), true)).toEqual(checked); + expect(setCrewMemberModelChecked(checked, providers, pair(codex, "a"), false)).toEqual(saved); + }); + + it("checks and unchecks a whole provider without touching the others", () => { + const only = [pair(claude, "x")]; + const all = setCrewMemberProviderChecked(only, providers, providers[0]!, true); + expect(all).toEqual([pair(claude, "x"), pair(codex, "a"), pair(codex, "b"), pair(codex, "c")]); + expect(setCrewMemberProviderChecked(all, providers, providers[0]!, false)).toEqual(only); + }); + + it("counts checked models in the catalog and warns when a saved list leaves none", () => { + expect(crewMemberModelsSummary(null, providers)).toEqual({ + label: "4 of 4", + nothingEligible: false, + }); + expect(crewMemberModelsSummary([pair(codex, "a"), pair(codex, "retired")], providers)).toEqual({ + label: "1 of 4", + nothingEligible: false, + }); + expect(crewMemberModelsSummary([], providers)).toEqual({ + label: "0 of 4", + nothingEligible: true, + }); + // A list holding only stale entries leaves nothing eligible too. + expect(crewMemberModelsSummary([pair(codex, "retired")], providers).nothingEligible).toBe(true); + // With no provider set up there is nothing to warn about. + expect(crewMemberModelsSummary([], []).nothingEligible).toBe(false); + }); + + it("names the personas that run on a model the list leaves out", () => { + const entry = (displayName: string, model: string, available = true) => ({ + displayName, + availability: available + ? { + status: "available" as const, + resolvedModelSelection: { instanceId: codex, model }, + } + : { status: "unavailable" as const, reason: "routes-unavailable" as const }, + }); + const catalog = { + personas: [entry("Scout", "a"), entry("Critic", "c"), entry("Blocked", "c", false)], + } as unknown as OrchestrationV2AgentPersonaCatalog; + expect(personasOffCrewMemberModels(catalog, [pair(codex, "a")])).toEqual(["Critic"]); + expect(personasOffCrewMemberModels(catalog, null)).toEqual([]); + expect(personasOffCrewMemberModels(null, [])).toEqual([]); + }); +}); diff --git a/apps/web/src/j5/crew/crewMemberModels.logic.ts b/apps/web/src/j5/crew/crewMemberModels.logic.ts new file mode 100644 index 0000000000000..b7ec51e2c6c36 --- /dev/null +++ b/apps/web/src/j5/crew/crewMemberModels.logic.ts @@ -0,0 +1,81 @@ +import type { OrchestrationV2AgentPersonaCatalog, ServerProvider } from "@t3tools/contracts"; +import { + crewMemberModelCounts, + isCrewMemberModelChecked, + isCrewMemberProviderSetUp, + type CrewMemberModel, + type CrewMemberModels, +} from "@t3tools/contracts/j5"; + +type ModelKey = Pick; + +const sameModel = (left: ModelKey, right: ModelKey) => + left.instanceId === right.instanceId && left.model === right.model; + +/** Every model of every provider a person can choose from, as checked pairs. */ +const catalogEntries = (providers: ReadonlyArray): ReadonlyArray => + providers + .filter(isCrewMemberProviderSetUp) + .flatMap((provider) => + provider.models.map((model) => ({ instanceId: provider.instanceId, model: model.slug })), + ); + +/** + * The list after one box is changed. Until a list is saved every model counts as checked, so the + * first change starts from the whole catalog. Entries for models no longer in the catalog stay: + * they come back if the model does. + */ +export const setCrewMemberModelChecked = ( + list: CrewMemberModels, + providers: ReadonlyArray, + model: ModelKey, + checked: boolean, +): ReadonlyArray => { + const base = list ?? catalogEntries(providers); + const without = base.filter((entry) => !sameModel(entry, model)); + return checked ? [...without, { instanceId: model.instanceId, model: model.model }] : without; +}; + +/** The list after every model of one provider is checked or unchecked. */ +export const setCrewMemberProviderChecked = ( + list: CrewMemberModels, + providers: ReadonlyArray, + provider: ServerProvider, + checked: boolean, +): ReadonlyArray => { + const base = list ?? catalogEntries(providers); + const others = base.filter((entry) => entry.instanceId !== provider.instanceId); + return checked + ? [ + ...others, + ...provider.models.map((model) => ({ + instanceId: provider.instanceId, + model: model.slug, + })), + ] + : others; +}; + +/** "6 of 12", and whether a saved list leaves no model eligible. */ +export const crewMemberModelsSummary = ( + list: CrewMemberModels, + providers: ReadonlyArray, +) => { + const { checked, total } = crewMemberModelCounts(list, providers); + return { + label: `${checked} of ${total}`, + nothingEligible: list !== null && total > 0 && checked === 0, + }; +}; + +/** The saved personas that run on a model the list leaves out, which they are free to do. */ +export const personasOffCrewMemberModels = ( + catalog: OrchestrationV2AgentPersonaCatalog | null | undefined, + list: CrewMemberModels, +): ReadonlyArray => + (catalog?.personas ?? []).flatMap((persona) => + persona.availability.status === "available" && + !isCrewMemberModelChecked(list, persona.availability.resolvedModelSelection) + ? [persona.displayName] + : [], + ); diff --git a/apps/web/src/j5/crew/useCrewMemberModels.ts b/apps/web/src/j5/crew/useCrewMemberModels.ts new file mode 100644 index 0000000000000..57784a3540b52 --- /dev/null +++ b/apps/web/src/j5/crew/useCrewMemberModels.ts @@ -0,0 +1,26 @@ +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import type { CrewMemberModels } from "@t3tools/contracts/j5"; +import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; + +import { useServerConfigs, useThreadShell } from "../../state/entities"; + +const NO_ENVIRONMENT = "" as EnvironmentId; + +/** + * The models custom members may run on in the Captain's project, as the server will check them: + * the environment's list, or the project's own. `null` while either is unknown, which offers every + * model, so the card never hides a choice the server would allow. + */ +export function useCrewMemberModels( + environmentId: EnvironmentId | null, + captainThreadId: ThreadId, +): CrewMemberModels { + const projectId = + useThreadShell(environmentId === null ? null : scopeThreadRef(environmentId, captainThreadId)) + ?.projectId ?? null; + const config = useServerConfigs().get(environmentId ?? NO_ENVIRONMENT); + return config === undefined || projectId === null + ? null + : resolveProjectSettings(config.settings, projectId).settings.crewMemberModels; +} From e1daa0d23fefbe86d212e0a54b151006c829eacf Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 13:52:16 -0400 Subject: [PATCH 03/12] docs(j5): record models for custom members and the native-subagent limits (#744) Rewrite the Crews definition, the agent tool contracts for j5_propose_crew, j5_request_crew_member, delegate_task and j5_spawn_agent, the persona follow-up note and the user guide. Record per provider that native subagents sit outside the list, and divergence D39 for the delegateTask hook. Each tool description gains one sentence on the eligible models. Co-Authored-By: Claude Sonnet 5.5 --- FORK.md | 2 +- apps/server/src/j5/a2a/mcp/tools.ts | 6 ++--- apps/server/src/j5/agents/agentDelegation.ts | 2 +- docs/j5/product/a2a/agent-tools.md | 24 ++++++++++++-------- docs/j5/product/agent-personas/index.md | 2 +- docs/j5/product/features/crews.md | 14 +++++++++++- docs/j5/product/upstream.md | 13 +++++++++++ docs/j5/user/personas.md | 4 +++- 8 files changed, 50 insertions(+), 17 deletions(-) diff --git a/FORK.md b/FORK.md index 948a3c2c38f5d..ad38b08ef1cd1 100644 --- a/FORK.md +++ b/FORK.md @@ -485,7 +485,7 @@ migrations after upstream migrations. 89. Deferred Crew assignments ([#745](https://github.com/Jacksondr5/j5code/issues/745)): `orchestration-v2/runtimeLayer.ts` wraps the shared orchestrator with J5-owned `CrewDeliveryContext.ts` for first-assignment workspace preparation and guards, and supplies J5-owned `CrewTurnContext.ts` to provider turn start and provider turn control. `orchestration-v2/ProviderTurnStartService.ts` asks that service whether the thread is a Crew seat (one indexed read) and delegates only a seat's selected assignment text to it immediately around provider delivery; every other thread keeps upstream's fast path and delivery unchanged, and `CrewDeliveryContext.ts` likewise passes any non-seat thread's dispatch straight through. `orchestration-v2/ProviderTurnControlService.ts` wraps the live session with the service's `steering`, one hook beside upstream's `steerTurn` call, so a message steered into a busy seat carries the current context too. The service builds the approved introduction or net roster changes from the current roster, sends the full introduction again when the provider conversation it reached is replaced (a model or provider switch, or a missing native session rebuilt from history), and records what it sent only after the provider accepts the prompt; a send that never happens (the run was stopped or superseded before `startTurn`) leaves it owed. Editable messages and shared author prefixes stay unchanged, so queued edits, cancellations and reordering cannot consume context. Waiting seats whose Crew is retired fail visibly; a retained worktree guard applies even after retirement. J5 migration 49 owns the context, and `CrewSeatPreparation.ts` uses upstream's persisted preparation path. `orchestration-v2/ProviderTurnStartService.test.ts` and `ProviderTurnControlService.test.ts` exercise the hooks against the real seat context, including a retained and a replaced native conversation and a Stop before the provider send. On an advance, retain the hooks at actual delivery and steering after queue selection, shared by every provider and transport. -90. Models for custom members ([#744](https://github.com/Jacksondr5/j5code/issues/744), maintainer-approved upstream edit to `delegateTask`): `packages/contracts/src/settings.ts` imports J5's `CrewMemberModels` schema (`packages/contracts/src/j5/crewMemberModels.ts`) and registers `crewMemberModels`, a nullable list of checked `(providerInstanceId, model)` pairs (never saved is `null`, every model eligible), in the project-scoped key list, project overrides (also in the nullable-override list), server settings and patches. `apps/server/src/mcp/OrchestratorMcpService.ts` gives `delegateTask` an optional `authorizeTarget` input, called right after `resolveTargetRechecking` with the child's project and resolved model selection unless the command already has a receipt, so a plain `delegate_task` is checked on the model the child will actually run on, inherited included. Upstream behavior is unchanged when no hook is passed; J5's `agents/agentDelegation.ts` passes one that calls the J5-owned `CrewMemberModels` service (`apps/server/src/j5/agents/crewMemberModels.ts`), which Crew launches and `j5_spawn_agent` also call. `apps/server/src/mcp/toolkits/worktree/registration.test.ts` stubs that service among the J5 tool dependencies. On an advance, keep the one call after the target resolves and before anything is created. +90. Models for custom members ([#744](https://github.com/Jacksondr5/j5code/issues/744), register D39, Bryant's approval of the upstream edit to `delegateTask`): `packages/contracts/src/settings.ts` imports J5's `CrewMemberModels` schema (`packages/contracts/src/j5/crewMemberModels.ts`) and registers `crewMemberModels`, a nullable list of checked `(providerInstanceId, model)` pairs (never saved is `null`, every model eligible), in the project-scoped key list, project overrides (also in the nullable-override list), server settings and patches. `apps/server/src/mcp/OrchestratorMcpService.ts` gives `delegateTask` an optional `authorizeTarget` input, called right after `resolveTargetRechecking` with the child's project and resolved model selection unless the command already has a receipt, so a plain `delegate_task` is checked on the model the child will actually run on, inherited included. Upstream behavior is unchanged when no hook is passed; J5's `agents/agentDelegation.ts` passes one that calls the J5-owned `CrewMemberModels` service (`apps/server/src/j5/agents/crewMemberModels.ts`), which Crew launches and `j5_spawn_agent` also call. `apps/server/src/mcp/toolkits/worktree/registration.test.ts` stubs that service among the J5 tool dependencies. On an advance, keep the one call after the target resolves and before anything is created. ## Pin and upstream advance runbook diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index e3fb43f03d830..574455044e6ed 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -575,16 +575,16 @@ export const J5ArchiveCrewFailure = Schema.Struct({ export type J5ArchiveCrewFailure = typeof J5ArchiveCrewFailure.Type; export const J5_SPAWN_AGENT_DESCRIPTION = - "Spawn a Peer Agent: a full-citizen teammate with its own top-level thread, starting on your brief as its first turn. It joins your project unless you name another with project_id or set scratch for none, and records you as its immutable spawner; in your own project it is placed under you. It is addressable the moment this returns. In your brief, tell the new agent what it should do first and whether it should reply to you. Choose provider, model, and reasoning for the work in the brief — see orchestrator_capabilities for what's available. To run a persona from j5_list_personas, set `persona` to its id: the spawn gets that persona's instructions and runtime policy, and provider, model, and reasoning must be one of that persona's declared routes. Without a persona it runs in your permission and interaction modes, or in narrower ones you set with runtime_mode and interaction_mode. Attach files to the brief with attachments. Choose its workspace every time (see the workspace field). A new worktree is prepared after this returns, and the agent begins once it is bound, possibly while the project's setup script is still running; if preparing it fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to retry the same spawn safely; reusing it with any change to the request is refused, so use a fresh one for new work."; + "Spawn a Peer Agent: a full-citizen teammate with its own top-level thread, starting on your brief as its first turn. It joins your project unless you name another with project_id or set scratch for none, and records you as its immutable spawner; in your own project it is placed under you. It is addressable the moment this returns. In your brief, tell the new agent what it should do first and whether it should reply to you. Choose provider, model, and reasoning for the work in the brief — see orchestrator_capabilities for what's available. To run a persona from j5_list_personas, set `persona` to its id: the spawn gets that persona's instructions and runtime policy, and provider, model, and reasoning must be one of that persona's declared routes. Without a persona it runs in your permission and interaction modes, or in narrower ones you set with runtime_mode and interaction_mode. Without a persona its model must be one the project's Models for custom members list allows; an ineligible one is refused with the eligible models. Attach files to the brief with attachments. Choose its workspace every time (see the workspace field). A new worktree is prepared after this returns, and the agent begins once it is bound, possibly while the project's setup script is still running; if preparing it fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to retry the same spawn safely; reusing it with any change to the request is refused, so use a fresh one for new work."; export const J5_LIST_AGENTS_DESCRIPTION = "List the personas in this environment: id, purpose, runtime policy, whether each can start now, and the provider, model, and reasoning it would run on. Read this before choosing a persona for j5_spawn_agent or a crew roster so the choice fits the task and the user's budget. Read-only."; export const J5_PROPOSE_CREW_DESCRIPTION = - "Propose the crew you need for the brief you were given. Use it when the user asks for a crew or the work splits into distinct responsibilities that should run at once. Mix saved personas and custom seats in the same roster: call j5_list_personas when choosing a saved persona, or leave persona unset for a custom seat with its own instructions (required) and the brief. Custom seats inherit your harness, model, and reasoning by default and run with full-access unless you set runtime_mode; to choose different ones, set model_selection (instanceId, model, options) and/or runtime_mode using orchestrator_capabilities. Saved personas are proposed with their own configuration; only the human may override their runtime before approval. To have the crew follow a playbook, set playbook to a name from j5_playbook_list and give seats the step ids they own (steps, from j5_playbook_read); a step has one owner, steps no seat owns are yours as Captain, and the result reports unowned steps and any step whose persona differs from its seat's. For a crew built from a playbook, staff one seat per distinct persona its steps name, each owning that persona's steps, and propose a custom seat, noted in its reason, where a named persona isn't available. Every seat names its workspace, with the same three choices as j5_spawn_agent. Name the crew for what it is for and give each seat a short lowercase-hyphen name like code-reviewer. By default the user reviews and edits the roster in this thread, then approves or declines. If Auto-approve new Crews is on for your project, the proposed roster is created immediately with no approval card. The result says whether it is open or approved; the launch report arrives here once creation finishes or fails. Approval creates seats without starting turns. Send each member its first assignment when it has work; reuse finished members for follow-up work in the same thread. Each seat keeps its configured access and tool approvals, which may exceed yours. You become the crew's Captain and may command several crews at once; later requests, stops, and archives name the crew they mean. Use j5_send_message for member-to-member, member-to-Captain, and Captain-to-Captain coordination, including findings and direct results; artifacts do not gate these conversations. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. This tool works under every sandbox and approval policy, including approval policy never; never refuse the brief because approvals are disabled."; + "Propose the crew you need for the brief you were given. Use it when the user asks for a crew or the work splits into distinct responsibilities that should run at once. Mix saved personas and custom seats in the same roster: call j5_list_personas when choosing a saved persona, or leave persona unset for a custom seat with its own instructions (required) and the brief. Custom seats inherit your harness, model, and reasoning by default and run with full-access unless you set runtime_mode; to choose different ones, set model_selection (instanceId, model, options) and/or runtime_mode using orchestrator_capabilities. A custom seat's model, yours included, must be one the project's Models for custom members list allows; an ineligible one is refused with the eligible models. Saved personas are proposed with their own configuration; only the human may override their runtime before approval. To have the crew follow a playbook, set playbook to a name from j5_playbook_list and give seats the step ids they own (steps, from j5_playbook_read); a step has one owner, steps no seat owns are yours as Captain, and the result reports unowned steps and any step whose persona differs from its seat's. For a crew built from a playbook, staff one seat per distinct persona its steps name, each owning that persona's steps, and propose a custom seat, noted in its reason, where a named persona isn't available. Every seat names its workspace, with the same three choices as j5_spawn_agent. Name the crew for what it is for and give each seat a short lowercase-hyphen name like code-reviewer. By default the user reviews and edits the roster in this thread, then approves or declines. If Auto-approve new Crews is on for your project, the proposed roster is created immediately with no approval card. The result says whether it is open or approved; the launch report arrives here once creation finishes or fails. Approval creates seats without starting turns. Send each member its first assignment when it has work; reuse finished members for follow-up work in the same thread. Each seat keeps its configured access and tool approvals, which may exceed yours. You become the crew's Captain and may command several crews at once; later requests, stops, and archives name the crew they mean. Use j5_send_message for member-to-member, member-to-Captain, and Captain-to-Captain coordination, including findings and direct results; artifacts do not gate these conversations. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. This tool works under every sandbox and approval policy, including approval policy never; never refuse the brief because approvals are disabled."; export const J5_REQUEST_CREW_MEMBER_DESCRIPTION = - "Add one seat directly to a running crew you command when the work needs expertise the roster lacks. No human approval is needed, regardless of Auto-approve new Crews. Give a seat name, a persona id from j5_list_personas or required instructions for a custom seat, a reason identifying the missing expertise, and its workspace (the same choices as j5_propose_crew). Custom seats inherit your model selection and run with full-access unless you set model_selection or runtime_mode; saved personas use their own configuration. Optionally give a brief; otherwise the seat gets the Crew's brief. On a playbook Crew, steps may claim only unowned step ids from j5_playbook_read. The result returns the updated roster or refuses the seat with its name and reason; creation is reported separately here. The new member waits for its first assignment; send it with j5_send_message when the work is ready. Each member's configured access still controls tool approvals. Captain-only: a member sends the concern to its Captain with j5_send_message. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. Works under every approval policy, including approval policy never."; + "Add one seat directly to a running crew you command when the work needs expertise the roster lacks. No human approval is needed, regardless of Auto-approve new Crews. Give a seat name, a persona id from j5_list_personas or required instructions for a custom seat, a reason identifying the missing expertise, and its workspace (the same choices as j5_propose_crew). Custom seats inherit your model selection and run with full-access unless you set model_selection or runtime_mode; a custom seat's model must be one the project's Models for custom members list allows, and saved personas use their own configuration. Optionally give a brief; otherwise the seat gets the Crew's brief. On a playbook Crew, steps may claim only unowned step ids from j5_playbook_read. The result returns the updated roster or refuses the seat with its name and reason; creation is reported separately here. The new member waits for its first assignment; send it with j5_send_message when the work is ready. Each member's configured access still controls tool approvals. Captain-only: a member sends the concern to its Captain with j5_send_message. Reuse client_request_id to retry safely; a changed request is refused, so use a fresh one for new work. Works under every approval policy, including approval policy never."; export const J5_STOP_AGENT_DESCRIPTION = "Stop one Peer Agent the way a user Stop does: its running turn is interrupted now, turns already queued behind it, messages you sent it included, are held until a person resumes its queue or the next message reaches it (that message resumes the queue and runs after them, in order), its pull request watches end, and the tasks it delegated stop too. The agent remains, stays readable, and can be messaged again later — stopping halts work, it retires nothing. It reaches any agent on this server, in any project. Reuse client_request_id to retry safely."; diff --git a/apps/server/src/j5/agents/agentDelegation.ts b/apps/server/src/j5/agents/agentDelegation.ts index 732ea59829bf3..613446a6a34ea 100644 --- a/apps/server/src/j5/agents/agentDelegation.ts +++ b/apps/server/src/j5/agents/agentDelegation.ts @@ -38,7 +38,7 @@ export type J5DelegateTaskInput = typeof J5DelegateTaskInput.Type; * fallback. */ export const J5_DELEGATE_TASK_DESCRIPTION = - "Run one task as a J5-owned child of THIS thread with only the supplied task prompt; parent conversation history is not copied. Pass persona=ID when the user writes @persona:ID or asks for a persona by name: the server pins that persona's instructions, provider, model, reasoning, and runtime policy, so omit target and runtimeMode. Give the persona a self-contained task, and if that call fails, report the error instead of substituting a plain child. Without persona, this is a plain J5-tracked child for cross-provider work or for work the user wants tracked as a J5 task; for an ordinary subagent request, use your provider's native subagent mechanism instead. The childThreadId is backing storage, not an ordinary top-level thread. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn."; + "Run one task as a J5-owned child of THIS thread with only the supplied task prompt; parent conversation history is not copied. Pass persona=ID when the user writes @persona:ID or asks for a persona by name: the server pins that persona's instructions, provider, model, reasoning, and runtime policy, so omit target and runtimeMode. Give the persona a self-contained task, and if that call fails, report the error instead of substituting a plain child. Without persona, this is a plain J5-tracked child for cross-provider work or for work the user wants tracked as a J5 task; for an ordinary subagent request, use your provider's native subagent mechanism instead. The childThreadId is backing storage, not an ordinary top-level thread. Set isolation to worktree for a separate checkout based on the parent local commit, with project setup completed before the child starts. Uncommitted edits are not copied; omitted isolation shares the parent checkout. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. Without persona the child's model, an inherited one included, must be one the project's Models for custom members list allows; a refusal lists the eligible models to retry with in target. A requested runtimeMode must be one the target provider lists in orchestrator_capabilities runtimeModes; an inherited one steps down to the broadest mode it offers. Leave runtimeMode unset unless the user asks for a supervised child: approval-required and auto-accept-edits usually make the child wait for a person at each action that needs approval. Prefer mode='async' for long work; mode='wait' blocks until completion, a blocking question, or timeout. If hasPendingQuestion, pass threadId=childThreadId to t3_pending_request_list, t3_pending_request_read (with requestId) and t3_pending_request_respond, or ask the user; the task's completion still wakes this thread. timeoutMs on mode=wait is only the parent's wait budget and does not cancel the child. waitTimedOut on that wait call means the timeout fired; keep that taskId and read status on later task_status. An async child's completion wakes this thread through a notification, steered into active turns where supported or queued otherwise, so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn."; /** J5's delegate_task: the upstream tool with the persona extension, registered in place of it. */ export const J5DelegateTaskTool = Tool.make("delegate_task", { diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 87e21abb335cf..f0291a180cccc 100644 --- a/docs/j5/product/a2a/agent-tools.md +++ b/docs/j5/product/a2a/agent-tools.md @@ -83,8 +83,9 @@ for the work in the brief — see orchestrator_capabilities for what's available from j5_list_personas, set `persona` to its id: the spawn gets that persona's instructions and runtime policy, and provider, model, and reasoning must be one of that persona's declared routes. Without a persona it runs in your permission and interaction modes, or in narrower ones you set with -runtime_mode and interaction_mode. Attach files to the brief with attachments. Choose its workspace -every time (see the workspace field). A new worktree is prepared after this returns, and the agent +runtime_mode and interaction_mode. Without a persona its model must be one the project's Models for +custom members list allows; an ineligible one is refused with the eligible models. Attach files to +the brief with attachments. Choose its workspace every time (see the workspace field). A new worktree is prepared after this returns, and the agent begins once it is bound, possibly while the project's setup script is still running; if preparing it fails, the agent's thread shows why, and it is not retried. Reuse client_request_id to retry the same spawn safely; reusing it with any change to the request is refused, so use a fresh one for new @@ -115,13 +116,13 @@ work." | `attachments` | attachment list | no | One to eight pending uploads for the brief | | `client_request_id` | string, non-empty | no | Supply and reuse to make retries safe | -**Rules.** The new agent is an ordinary root-lineage thread created through upstream's creation seam, never through delegation. It is created in the caller's project unless the caller names another with `project_id` or sets `scratch`, and it joins that project's ledger. An [outside agent](index.md#participants) has no project, so it passes one of the two on every spawn. These are what upstream's own launch tool offers and J5's lacked (Jackson, 2026-10-11). In another project the caller is still recorded as the spawner, but the placement tree is one project's, so the agent is a root there and stays at the top level of the sidebar. An outside agent is in no project's tree, so every agent it starts is a root, with the outside agent's `outside:` id recorded as its spawner. Without a persona the agent runs in the caller's permission and interaction modes, or in ones the caller chose, which may be no broader than the caller's own. For an outside agent the caller's modes are the level its sign-in was approved at, and a read-only sign-in spawns nothing. A persona's policy sets its permissions. For a thread caller it has no ceiling (2026-09-16). For an outside agent it must be within the approved level, because that level is a promise the approval page makes about an agent the person does not watch. Either caller may still choose a narrower interaction mode for a persona. A retry finishes the agent its first attempt created, in the modes it was created with, so it is refused when those are now broader than the caller's own; a caller's modes can be narrowed between the two. An outside agent's retry keys belong to its sign-in, whose level never changes. `attachments` are pending uploads, claimed into the new thread once it exists and carried by the brief. Placement and provenance are recorded atomically with creation; then the brief starts as the first turn. The new agent's first turn also states its own participant id and project as platform-provided facts, beside the brief and never inside it. When an outside agent started it, those facts name the outside agent by its label and say that `j5_send_message` cannot reply to it. Provider, model and reasoning are required and explicit even when a Role is given: a Role's allowlist constrains the choice and an out-of-list pick is an error naming the Role, never a silent default. The brief carries the task and the reply expectation; the spawner does not follow a spawn with a reply-expected `j5_send_message` — that form is for later work owed by an existing participant. Selection guidance and brief-writing conventions live in the [Spawning Guide](../features/spawning-guide.md). +**Rules.** The new agent is an ordinary root-lineage thread created through upstream's creation seam, never through delegation. It is created in the caller's project unless the caller names another with `project_id` or sets `scratch`, and it joins that project's ledger. An [outside agent](index.md#participants) has no project, so it passes one of the two on every spawn. These are what upstream's own launch tool offers and J5's lacked (Jackson, 2026-10-11). In another project the caller is still recorded as the spawner, but the placement tree is one project's, so the agent is a root there and stays at the top level of the sidebar. An outside agent is in no project's tree, so every agent it starts is a root, with the outside agent's `outside:` id recorded as its spawner. Without a persona the agent runs in the caller's permission and interaction modes, or in ones the caller chose, which may be no broader than the caller's own. Without a persona its model must also be one the project's [Models for custom members](../features/crews.md) list allows, the project being the one the agent joins. The check runs before anything is created and only on a first attempt, so a retry that finds its agent already created is not held to a list saved since; a refusal names the model, the project and the setting and lists the eligible models. A persona's own model is never checked. For an outside agent the caller's modes are the level its sign-in was approved at, and a read-only sign-in spawns nothing. A persona's policy sets its permissions. For a thread caller it has no ceiling (2026-09-16). For an outside agent it must be within the approved level, because that level is a promise the approval page makes about an agent the person does not watch. Either caller may still choose a narrower interaction mode for a persona. A retry finishes the agent its first attempt created, in the modes it was created with, so it is refused when those are now broader than the caller's own; a caller's modes can be narrowed between the two. An outside agent's retry keys belong to its sign-in, whose level never changes. `attachments` are pending uploads, claimed into the new thread once it exists and carried by the brief. Placement and provenance are recorded atomically with creation; then the brief starts as the first turn. The new agent's first turn also states its own participant id and project as platform-provided facts, beside the brief and never inside it. When an outside agent started it, those facts name the outside agent by its label and say that `j5_send_message` cannot reply to it. Provider, model and reasoning are required and explicit even when a Role is given: a Role's allowlist constrains the choice and an out-of-list pick is an error naming the Role, never a silent default. The brief carries the task and the reply expectation; the spawner does not follow a spawn with a reply-expected `j5_send_message` — that form is for later work owed by an existing participant. Selection guidance and brief-writing conventions live in the [Spawning Guide](../features/spawning-guide.md). **Workspace.** The spawner chooses where a Peer Agent works every time; there is no default, because the spawner knows whether it is starting a reviewer that must see uncommitted work, a builder that must not collide, or a scout that can't collide at all (Jackson, 2026-10-03). `{type: "shared"}` is the caller's own checkout and branch, and asks nothing of git; it is refused for an agent that joins another project, and for an outside agent, which has no checkout. `{type: "root"}` is the project's main checkout, upstream's name for it, and the only choice with `scratch`. As upstream's launch does, a main-checkout thread in the "No project" project gets a fresh folder of its own, whether the caller set `scratch` or named that project by its id. `{type: "worktree"}` is a new worktree from `base_ref`, which is required and must resolve to a commit (with `start_from_origin`, its fetched origin copy counts); a `branch` that already exists is refused. `{type: "existing_worktree"}` is one of the project's git worktrees other than its main checkout, named by path; the agent works on the branch git has checked out there, and any other path is refused with the valid ones listed. A choice that needs git is refused when the repository can't be read, before anything is created. A new worktree's thread is created unbound, with its registration and placement committed, so `j5_spawn_agent` returns as soon as the agent is registered and its brief accepted, not once the worktree is ready. Upstream's ThreadLaunch then creates the worktree, names a temporary `j5code/` branch and renames it from the brief in the background, and holds the brief as a preparing run until the worktree is bound and the project's setup script has started. The setup script is awaited first only when it is set to finish before the agent starts (`async: false`); otherwise the agent may begin while it is still running. If preparation fails, the agent's thread shows the failed preparation, as any upstream launch does; it is not retried or retired, and the spawner is not told. The agent is then unbound, which upstream reads as the project's checkout, so a later message to it runs there, where every Peer Agent worked before workspaces existed. J5 doesn't guard this upstream behaviour: in Jackson's install, 3 of 61 preparations failed, all on the first day, and none was messaged again (Jackson, 2026-10-06). A shared checkout or an existing worktree binds at creation, so its brief starts at once. A `client_request_id` is bound to the whole request it was first accepted with, before anything is created, and the binding survives a restart. A retry with any change, including another workspace, `base_ref` or `worktree_path`, is refused, naming the agent the first attempt created; new work needs a fresh `client_request_id`. A request refused before it is accepted, such as one with duplicate attachment ids or an unusable workspace, binds nothing, so it can be corrected under the same key. A retry of a spawn from before request binding binds its first retry when the workspace type matches its accepted create receipt, and is refused otherwise; later request changes under that key are refused. A second start for the same thread while one is in flight is refused with a retry instruction, so two concurrent retries cannot both create it. An existing worktree is looked up in upstream's ref listing, which refreshes every few seconds, so one created moments ago may be refused once; retry in a moment. Closing or archiving a Peer Agent never removes its worktree. **Result:** the new agent's `participant_id` and `thread_id`, its `project_id` and `project_title`, and its placement with the caller recorded as spawner: under the caller in the caller's own project, and with no parent in another or when the caller is an outside agent. -**Errors**, each naming state and next command: the caller is a provider Subagent; the caller's membership is missing or ambiguous; the caller's project ledger cannot be read; the caller sits in a Crew (naming its Captain as the escalation and `delegate_task` for its own subagents; only a Captain grows a Crew, through the gate); the chosen workspace can't be used (a path that isn't one of the project's worktrees, a `base_ref` that doesn't resolve, a `branch` that exists, an unreadable repository); the `client_request_id` is bound to a different request, or a start for it is already in flight; creation failed. For an outside agent: no `project_id` and no `scratch` (naming `t3_project_list`); the `shared` workspace (naming the three it may choose); a persona whose policy is broader than the approved level (naming the level, and a persona within it or a new sign-in at a higher level). +**Errors**, each naming state and next command: the caller is a provider Subagent; the caller's membership is missing or ambiguous; the caller's project ledger cannot be read; the caller sits in a Crew (naming its Captain as the escalation and `delegate_task` for its own subagents; only a Captain grows a Crew, through the gate); the chosen workspace can't be used (a path that isn't one of the project's worktrees, a `base_ref` that doesn't resolve, a `branch` that exists, an unreadable repository); the model, with no persona, is off the project's list of models for custom members; the `client_request_id` is bound to a different request, or a start for it is already in flight; creation failed. For an outside agent: no `project_id` and no `scratch` (naming `t3_project_list`); the `shared` workspace (naming the three it may choose); a persona whose policy is broader than the approved level (naming the level, and a persona within it or a new sign-in at a higher level). **Events:** participant joined, placement created. @@ -201,8 +202,9 @@ custom seats in the same roster: call j5_list_personas when choosing a saved per persona unset for a custom seat with its own instructions (required) and the brief. Custom seats inherit your harness, model, and reasoning by default and run with full-access unless you set runtime_mode; to choose different ones, set model_selection (instanceId, model, options) and/or -runtime_mode using orchestrator_capabilities. Saved personas are proposed with their own -configuration; only the human may override their runtime before approval. To have the crew follow +runtime_mode using orchestrator_capabilities. A custom seat's model, yours included, must be one +the project's Models for custom members list allows; an ineligible one is refused with the eligible +models. Saved personas are proposed with their own configuration; only the human may override their runtime before approval. To have the crew follow a playbook, set playbook to a name from j5_playbook_list and give seats the step ids they own (steps, from j5_playbook_read); a step has one owner, steps no seat owns are yours as Captain, and the result reports unowned steps and any step whose persona differs from its seat's. For a crew @@ -256,6 +258,7 @@ caller, persona-backed where a seat names one, records the Crew snapshot with ea a `` launch report into the caller's thread immediately after creation: the roster, what the user changed against the proposal, and per seat `start=waiting|started|failed|pending`, with a `seat_failed` line carrying the run's error (`not_started` when the seat's thread exists but registration failed) and a `seat_not_created` line for an approved seat whose thread was never created, which is left off the roster. A proposal resolves once: a seat that fails does not stop the others or reopen the gate. Declines post the decline at once. Every seat names its workspace, with the same three choices as `j5_spawn_agent`, so there is no Captain-aware default (Jackson, 2026-10-03). Each seat's workspace resolves at preview against the Captain's repository, and the approval token binds it, as it binds the Captain's branch and worktree. Every preview also carries the Captain's current branch, the directory its branch picker searches, and its worktrees, for the roster card's editor; the branches themselves are searched live, so no list is capped. A seat the person adds starts in the Captain's checkout. A seat recorded before workspaces were required stays readable but is refused at preview and approval until one is chosen. New and added seats wait for their first assignment. A direct chat message, participant message, or playbook handoff activates the seat with its approved instructions and shared brief, the current roster with responsibilities and participant ids, and the assignment with its envelope and reply obligation intact. A new-worktree seat prepares its workspace before running that assignment; failed preparation is reported as a seat failure. New Crews require human approval by default. **Settings → Agent Setup → Crews → Auto-approve new Crews** skips that gate, off by default and overridable per project. The server reads the Captain's project setting only for a new request; changing it leaves existing Crews and open proposals alone. Automatic approval launches the proposed configuration through the same provider, workspace, capacity, and persona checks. Tool approvals still follow each seat's access. The persisted proposal and launch report distinguish automatic approval from a human decision. +**Models for custom members** is a project setting holding the checked provider models; until one is saved every model is eligible. A custom seat, including one that inherits the Captain's model, must run on an eligible model, checked at preview, at approval, and for an automatic launch, so a roster naming another is refused whole before anything spawns, with an error naming the seat, the model, the project and the setting and listing the eligible models. A saved persona seat that keeps the persona's model skips the check; one whose model the person changed on the card is checked like a custom seat. An accepted proposal is not checked again. ### `j5_request_crew_member` @@ -264,7 +267,8 @@ lacks. No human approval is needed, regardless of Auto-approve new Crews. Give a persona id from j5_list_personas or required instructions for a custom seat, a reason identifying the missing expertise, and its workspace (the same choices as j5_propose_crew). Custom seats inherit your model selection and run with full-access unless you set model_selection or -runtime_mode; saved personas use their own configuration. Optionally give a brief; otherwise the +runtime_mode; a custom seat's model must be one the project's Models for custom members list +allows, and saved personas use their own configuration. Optionally give a brief; otherwise the seat gets the Crew's brief. On a playbook Crew, steps may claim only unowned step ids from j5_playbook_read. The result returns the updated roster or refuses the seat with its name and reason; creation is reported separately here. The new member waits for its first assignment; send @@ -285,7 +289,7 @@ work. Works under every approval policy, including approval policy never." | `workspace` | object | yes | Where the seat works; the same three choices as `j5_propose_crew` | | `client_request_id` | string | no | Supply and reuse to make retries safe | -Result: as `j5_propose_crew`. Only the Captain can add a seat. The member is added directly regardless of the auto-approval setting, with the same validation and capacity checks as a launch. The result returns the updated roster or a refusal naming the seat and reason; the launch report later records its startup outcome. Retries reuse the original request and cannot add a second copy. A refused automatic request repeats its original reason on retry; a revised request needs a new `client_request_id`. Existing pending addition requests remain human decisions above their Captain's composer, where they can still be approved or declined; additions never appear in the Inbox or its bell count. Member tool approvals remain in the Inbox. +Result: as `j5_propose_crew`. Only the Captain can add a seat. The member is added directly regardless of the auto-approval setting, with the same validation, model and capacity checks as a launch, so a custom seat on a model off the project's list is refused naming the seat, the model and the setting. The result returns the updated roster or a refusal naming the seat and reason; the launch report later records its startup outcome. Retries reuse the original request and cannot add a second copy. A refused automatic request repeats its original reason on retry; a revised request needs a new `client_request_id`. Existing pending addition requests remain human decisions above their Captain's composer, where they can still be approved or declined; additions never appear in the Inbox or its bell count. Member tool approvals remain in the Inbox. ### Handoff artifacts in Crews @@ -390,7 +394,7 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. ### Kept upstream tools - `orchestrator_capabilities` — providers and models (ids, labels, option descriptors) for spawn targeting, plus runtime and interaction-mode facts. It deliberately stays silent about delegation even though `delegate_task` is back on the surface: that tool's own description carries its persona use, and J5 verbs are advertised by their own descriptions. -- `delegate_task`, `task_status`, `task_cancel` — upstream's provider-owned child delegation. J5 re-declares `delegate_task` with its own description, which leads with the optional `persona` (a persona id from an `@persona:ID` mention or the Settings → Agent Setup library) and presents the plain child as the fallback for cross-provider or T3-tracked work rather than the default for any subagent request. With `persona`, the server pins that persona's instructions, model route, reasoning, and runtime policy and refuses `target` and `runtimeMode`; without it, the child is upstream's plain subagent. Upstream's `isolation: "worktree"` gives a child a checkout of its own, started from the parent's local commit, and the description says so in upstream's words. The child is backing storage under the calling thread, not a Peer Agent; use `j5_spawn_agent` for a participant. Its wait mode is safe where `t3_thread_wait` was not: a child that messages its parent ends its own turn, so the wait returns and the parent reads the message on its next turn (latency, never starvation). +- `delegate_task`, `task_status`, `task_cancel` — upstream's provider-owned child delegation. J5 re-declares `delegate_task` with its own description, which leads with the optional `persona` (a persona id from an `@persona:ID` mention or the Settings → Agent Setup library) and presents the plain child as the fallback for cross-provider or T3-tracked work rather than the default for any subagent request. With `persona`, the server pins that persona's instructions, model route, reasoning, and runtime policy and refuses `target` and `runtimeMode`; without it, the child is upstream's plain subagent, and the model it will run on, one inherited from its parent included, must be one the project's [Models for custom members](../features/crews.md) list allows. J5's wrapper hands upstream's `delegateTask` a hook that is called with that resolved model before anything is created, so the check sees what the child will really run on; a retry of a delegation already accepted is not checked again. A refusal is a `model_unavailable` error naming the model, the project and the setting and listing the eligible models, which the agent passes in `target`; a persona's own model is never checked. Upstream's `isolation: "worktree"` gives a child a checkout of its own, started from the parent's local commit, and the description says so in upstream's words. The child is backing storage under the calling thread, not a Peer Agent; use `j5_spawn_agent` for a participant. Its wait mode is safe where `t3_thread_wait` was not: a child that messages its parent ends its own turn, so the wait returns and the parent reads the message on its next turn (latency, never starvation). - `schedule_task`, `list_scheduled_tasks`, `update_scheduled_task`, `delete_scheduled_task` — consumed as-is. - `t3_thread_list`, `t3_thread_read` — consumed as-is; if an upstream description mentions delegation, J5 re-declares that tool with corrected prose. - `html_preview`, `html_render`, `request_secret`, `preview_dialog`, `preview_hover`, `preview_select`, `preview_drag`, `preview_upload`, `watch_pull_request`, `unwatch_pull_request` — consumed as-is. @@ -438,6 +442,7 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. 35. `j5_spawn_agent` refuses an outside agent that passes neither `project_id` nor `scratch`, and one that asks for the `shared` workspace, each with an error naming the legal move. 36. An agent an outside agent spawns has no placement parent, records the outside agent as its spawner, and is told in its first turn that an outside agent started it and that `j5_send_message` cannot reply to it. 37. `j5_spawn_agent` gives an outside agent's spawn the level its sign-in was approved at, or a narrower mode it chose. A broader mode is refused. A persona whose policy is broader than that level is refused with an error that names the level and the legal moves. +38. A custom Crew seat, a `j5_spawn_agent` without a persona and a `delegate_task` without a persona run only on a model the project's list of models for custom members allows, an inherited model included; a refusal names the model, the project and the setting, lists the eligible models, and creates nothing. A persona's own model is never checked, and a retry of an accepted call is not checked again. ## History @@ -489,3 +494,4 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. - 2026-10-24 — `j5_send_message`'s `deliveryNotice` also tells the sender when its message waits on the receiver's held queue, failed worktree setup or usage limit, and that it should not be sent again (Jackson, [#272](https://github.com/Jacksondr5/j5code/issues/272)). - 2026-10-24 — upstream's queue tools join the kept upstream tools; `t3_queue_edit` edits only a message the caller sent, inside its envelope (Jackson, [#136](https://github.com/Jacksondr5/j5code/issues/136)). - 2026-10-24 — a pre-upgrade spawn retry binds its request when the workspace type matches its accepted create receipt and is refused otherwise (Jackson, 2026-10-24; [PR #660](https://github.com/Jacksondr5/j5code/pull/660)). +- 2026-10-27 — custom Crew seats, a plain `j5_spawn_agent` and a plain `delegate_task` run only on a model the project's list of models for custom members allows, an inherited model included; AC38 (Bryant; [#744](https://github.com/Jacksondr5/j5code/issues/744)). diff --git a/docs/j5/product/agent-personas/index.md b/docs/j5/product/agent-personas/index.md index f0e6964329a28..68485eb70152f 100644 --- a/docs/j5/product/agent-personas/index.md +++ b/docs/j5/product/agent-personas/index.md @@ -211,7 +211,7 @@ Agents can also launch a persona as a Peer Agent: `j5_spawn_agent` accepts an op Focused verification covers imported ids and custom artifacts, malformed and missing sources, duplicates, route eligibility, unsupported policies, snapshot integrity, source edits/removal, launch receipts, compatibility with old assignments, and shared client presentation. Server, contracts, and affected client typechecks accompany the focused tests. Browser and simulator verification require an explicit request. -Follow-up work: in-app git commit/push/pull (status nudges and open-in-editor ship; write operations are deliberately out of scope), skill and model allowlists beyond this slice, posture visibility, validation of handoff artifact contents beyond existence, and supported diagnostic/publication operations. None is marked complete by this contract. +Follow-up work: in-app git commit/push/pull (status nudges and open-in-editor ship; write operations are deliberately out of scope), skill allowlists and ordered model allowlists beyond a persona's two routes, posture visibility, validation of handoff artifact contents beyond existence, and supported diagnostic/publication operations. None is marked complete by this contract. A project's [Models for custom members](../features/crews.md) list is not a persona allowlist: a persona always runs on its own configured route, even on a model that list leaves out. ## History diff --git a/docs/j5/product/features/crews.md b/docs/j5/product/features/crews.md index b1e6a2776ad04..d7f457d08124c 100644 --- a/docs/j5/product/features/crews.md +++ b/docs/j5/product/features/crews.md @@ -11,12 +11,14 @@ Complex work needs a group of agents with defined jobs working together with a h ## Definition -A **Crew** is a group of agents formed as a unit from a **roster its Captain proposes, approved by the person by default**, composed for the brief in front of it. Nobody writes a Crew file in advance. The person asks the agent in an ordinary conversation to compose a Crew (web and desktop). The agent uses the conversation as context, keeps its current persona, model, and policy, and proposes the team before starting its work. There is no Crew slash command. No dedicated Captain agent exists; the agent that proposes becomes the Captain. It proposes a roster — a name, the brief every seat will start on, and a responsibility with a reason and instructions for each member. Saved personas are optional templates; a roster can mix them with custom members. A seat may name no persona at all: a **custom seat**, named and briefed by the Captain or the person, defaults to the Captain's provider, model, and reasoning but to Full access, with harness, model, reasoning, and access editable before approval, so a Crew need not fit a mold anyone saved before (Jackson and Bryant, 2026-09-17). The Captain's access is never carried: a seat nobody configured would otherwise stop for approvals in a thread the person is not watching (Jackson, 2026-09-26). Its instructions are required at every door, since nothing else defines it. By default the proposal is a **human gate**, answered inline above the Captain's composer and never on the Inbox bell. **Settings → Agent Setup → Crews → Auto-approve new Crews** skips that gate when enabled for the Captain's project; it is off by default with project overrides. The setting is read for each new request, and changes leave existing Crews and open proposals alone. The Captain is the thread the person watches, so its own tool approvals and questions are answered inline there too. A seat runs out of view, so its provider tool approvals are answered from the Inbox (Jackson, 2026-09-26). A seat has no native question tool: when it needs a decision it asks its Captain with `j5_send_message`, and the Captain answers, or asks the person with its own question tool, inline in the Captain thread (Jackson, 2026-09-26). Claude seats run without `AskUserQuestion` and Codex seats without `request_user_input`; Cursor exposes no structured native question tool. Other harnesses keep their native tools and the standing rule to ask the Captain. If a seat still raises a native question, its Captain receives a queued notice naming the question and its thread. The person also sees a link in the Inbox to answer in the seat's original question form (Bryant, 2026-10-19). The person may drop seats, select personas from the library, or create custom seats with names, instructions, and runtime settings. Every proposed or manually added member uses the same editor before approval. Saved personas supply defaults; the person may override harness, model, reasoning, and access for this member without changing the saved definition. Approval creates every seat as a Peer Agent placed under the Captain, with a persona assignment only when the seat names a saved definition, and records the roster snapshot (the _Manifest_ in implementation vocabulary: name, brief, members with each one's reason and version). It starts no provider turns. The Captain receives a creation report naming what the person changed and which seats were created or failed. A decline is told at once. Each seat's first delivered assignment carries the platform's identity facts, the current Crew context and roster, any seat instructions, a handoff artifact obligation when its definition declares one, and the approved brief. +A **Crew** is a group of agents formed as a unit from a **roster its Captain proposes, approved by the person by default**, composed for the brief in front of it. Nobody writes a Crew file in advance. The person asks the agent in an ordinary conversation to compose a Crew (web and desktop). The agent uses the conversation as context, keeps its current persona, model, and policy, and proposes the team before starting its work. There is no Crew slash command. No dedicated Captain agent exists; the agent that proposes becomes the Captain. It proposes a roster — a name, the brief every seat will start on, and a responsibility with a reason and instructions for each member. Saved personas are optional templates; a roster can mix them with custom members. A seat may name no persona at all: a **custom seat**, named and briefed by the Captain or the person, defaults to the Captain's provider, model, and reasoning, where the project's models for custom members allow that model, but to Full access, with harness, model, reasoning, and access editable before approval, so a Crew need not fit a mold anyone saved before (Jackson and Bryant, 2026-09-17). The Captain's access is never carried: a seat nobody configured would otherwise stop for approvals in a thread the person is not watching (Jackson, 2026-09-26). Its instructions are required at every door, since nothing else defines it. By default the proposal is a **human gate**, answered inline above the Captain's composer and never on the Inbox bell. **Settings → Agent Setup → Crews → Auto-approve new Crews** skips that gate when enabled for the Captain's project; it is off by default with project overrides. The setting is read for each new request, and changes leave existing Crews and open proposals alone. The Captain is the thread the person watches, so its own tool approvals and questions are answered inline there too. A seat runs out of view, so its provider tool approvals are answered from the Inbox (Jackson, 2026-09-26). A seat has no native question tool: when it needs a decision it asks its Captain with `j5_send_message`, and the Captain answers, or asks the person with its own question tool, inline in the Captain thread (Jackson, 2026-09-26). Claude seats run without `AskUserQuestion` and Codex seats without `request_user_input`; Cursor exposes no structured native question tool. Other harnesses keep their native tools and the standing rule to ask the Captain. If a seat still raises a native question, its Captain receives a queued notice naming the question and its thread. The person also sees a link in the Inbox to answer in the seat's original question form (Bryant, 2026-10-19). The person may drop seats, select personas from the library, or create custom seats with names, instructions, and runtime settings. Every proposed or manually added member uses the same editor before approval. Saved personas supply defaults; the person may override harness, model, reasoning, and access for this member without changing the saved definition. Approval creates every seat as a Peer Agent placed under the Captain, with a persona assignment only when the seat names a saved definition, and records the roster snapshot (the _Manifest_ in implementation vocabulary: name, brief, members with each one's reason and version). It starts no provider turns. The Captain receives a creation report naming what the person changed and which seats were created or failed. A decline is told at once. Each seat's first delivered assignment carries the platform's identity facts, the current Crew context and roster, any seat instructions, a handoff artifact obligation when its definition declares one, and the approved brief. **Captains add members directly.** When the work needs expertise the roster lacks, the Captain adds one seat with a reason and optional brief. No human approval is needed, regardless of the auto-approval setting. The same launch checks apply; the tool returns the updated roster or a refusal naming the member and reason, and the launch report follows. A Crew holds at most **twelve seats**, counting open legacy requests. Members escalate staffing needs to their Captain. Pending addition requests from before this change remain approvable or declinable above their Captain's composer and stay off the Inbox and its bell. **Configured access controls tool approvals.** A seat runs with its proposed configuration, or the person's final configuration when a human approves it, using its persona's policy when no override is selected; the Captain may be read-only. The gate shows each seat's persona or custom-seat choice, instructions, and resolved harness, model, reasoning level, and access before approval, and the Captain's reason for a seat stays readable in its row. Human-approved rosters and legacy additions use the same preview. Automatically approved rosters and direct additions use the proposed configuration through the same runtime validation; their history records automatic approval. Automatic approval never changes a seat's tool approval policy. A custom member started automatically, by an auto-approved roster or a Captain's addition, defaults to Full access like any custom seat, so a Supervised Captain can start a Full-access member without review; that is accepted (2026-10-28), and the Agent Setup setting governs rosters only. Approval binds the displayed roster and configuration; changed configuration requires a fresh review, and a launch uses the validated resolution rather than choosing a different route afterward. Seats are checked where they are structured: a persona missing from the library or turned off, a duplicate seat name, or a roster past the cap is refused to the Captain with the next step, before anyone spawns. Prose in a brief is never parsed or validated. +**Models for custom members.** **Settings → Agent Setup → Crews → Models for custom members** chooses which provider models custom workers may run on, as a list of checked models that a project can override like auto-approval. Until a list is saved every model is eligible; once one is saved only the checked models are, and a model added to the catalog later starts unchecked. The platform enforces the list for every custom seat, at launch and when added, auto-approved launches included, and for an agent started without a persona by `j5_spawn_agent` or `delegate_task`; the roster card offers a custom member only eligible models. A persona always runs on its own configured model, even one that isn't checked, and Agent Setup names any persona whose model isn't on the list; a persona seat whose model the person changed on the card is a custom choice and is checked. The list chooses models; it is not a spending cap. **Native subagents are outside it, per provider.** Codex and Cursor choose a native subagent's model themselves and J5 only records what the provider reports once the subagent runs: not supported here. Claude shows its permission callback the subagent call and the model it asked for before the subagent starts, but J5 does not check the list there, and whether a denial would hold in every permission mode is unverified; it is not supported here either. Agent Setup says the list doesn't cover native subagents. + **Several people.** Where more than one person can write to a Captain's thread, "the person" in this definition is any of them. The roster and a seat's tool approvals go to everyone who can write to that thread, and the first answer settles each; anyone who can write to the Captain's thread can write to its seats too ([shared conversations](shared-conversations.md), [people and access](people-and-access.md)). **Communication is direct; handoff artifacts record durable outputs.** Members exchange findings, questions, blockers, and results directly with one another and their Captain; Captains can coordinate with other Captains. Neither an artifact nor a human approval is required for these messages. Members send their final result with evidence and unresolved issues to the Captain. Active Codex GPT 6 and Claude runs accept peer steering, Claude once its running tool calls finish; other models and providers queue messages until the next safe turn boundary. A seat whose persona declares an output artifact (a Critic's ReviewHandoff, a Scout's ContextBrief) owes it as the same shared handoff artifact every persona writes — `handoffs//-.md` in the project's artifacts (see the [persona contract](../agent-personas/index.md)) — and its first turn names that exact path. The handoff gate checks for the file when a run ends and reminds the seat once. File existence is evidence of delivery, not validation or acceptance of the result; the Captain reviews the handoff artifact against the task. **Every seat tells its Captain when it finishes**, as measured facts: how the run ended first, the run's error when it failed, and whether its handoff artifact was written, missing, unavailable (with why), or never declared, with the artifact inline when short. A first turn that fails is a launch outcome, told once by the launch report and not again as a finish; and a seat's failure that its Captain hears this way is not repeated by the silence detector as an unanswered ask. The notice is posted the first time a seat finishes and again only when those facts change; a finish that would repeat the last notice word for word is silent, because the seat's own reply already reached the Captain. Notices that arrive while the Captain's turn is running fold into the one seat notice already queued behind that turn, so the Captain absorbs its Crew's news in one turn rather than one per seat. Notice delivery retries on a later finish or the next server startup if dispatch fails; it is not guaranteed promptly while the seat stays idle. Sign-in and permission failures also raise a platform notice in the person’s Inbox, with replies routed to the Captain; other failures remain for the Captain to assess. A Captain normally does not have to interview its Crew to learn a seat is done, and it never waits for one inside a turn: `t3_thread_wait` is not on its surface, because a turn that blocks cannot receive the notice it is waiting for. The person opens every handoff on the Artifacts page. A direct result message does not replace a handoff artifact explicitly required by a saved persona. @@ -94,6 +96,14 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif 23. Where more than one person can write to a Captain's thread, a seat's approvals are listed in the inbox of each of them, the first answer settles each, and each of them can message, stop and answer the prompts of the Crew's seats. +### Models for custom members + +24. Until a list is saved every model is eligible and nothing changes; a saved list makes only its checked models eligible, a model new to the catalog starts unchecked, and a saved list with nothing checked makes none eligible and says so on its row. +25. A custom seat, whether the Captain proposed it, the person added it, the Captain added it, it inherits the Captain's model, or an automatic approval launches it, is refused when its model is off the list: the refusal names the seat, the model, the project and the setting, lists the eligible models, and creates nothing. The roster card offers a custom member only eligible models. +26. A persona seat that keeps its persona's model is not checked. One whose model was changed on the card is checked like a custom seat, the two compared by provider instance and model alone. Agent Setup names any persona whose model isn't on the list. +27. A plain `j5_spawn_agent` and a plain `delegate_task`, the child's inherited model included, are held to the list of the project the child joins. A retry of a call or proposal already accepted is not checked again. +28. The Agent Setup row reads the checked models in the catalog over the catalog ("6 of 12"), opens in place, lists each set-up provider's models with the catalog's New tag and sends the others to Providers, keeps entries for models that left the catalog, and carries the scoped-setting indicator, inheritance and reset. Its note says the list doesn't cover native subagents on Codex, Claude and Cursor. + ## Scenarios - **A pull-request Crew.** In Billing Migration the user sends "Put together a crew to land the invoice-export PR: build, review, sit on CI." The Captain proposes Builder, Critic, and Sitter with a reason each; the user drops the Sitter, approves, and the two seats appear under the Captain as Not started. The Captain sends the Builder its assignment, then sends the Critic the review assignment when code is ready. Each receives the brief and current roster on activation. The Critic finishes and writes its ReviewHandoff into the project's artifacts; the Captain's thread receives the notice with the findings inline. (AC1, AC2, AC6, AC8, AC12, AC13) @@ -102,6 +112,7 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif - **A flaky launch.** One of three approved seats cannot be created when the user approves the roster. The other two wait for assignments; the launch report says the third was never created and why, and the Captain asks for it again with `j5_request_crew_member`. (AC7) - **Stop everything.** The Builder is heading down a path the person recognizes as wrong while the Critic is mid-review. The person clicks Stop crew on the Crew's Fleet header; both running turns end, the seats stay on the roster, and the Captain briefs them again. (AC21) - **A playbook-shaped Crew.** After talking through a change with the agent, the user sends "ok, lets create a crew to implement what we have discussed. Please use @playbook:release for this work." The agent reads the playbook and proposes a roster above its composer: "Follows playbook: Release", a planner seat and a builder seat each owning the steps that name them, the step that names no persona placed with the builder, and a stand-in custom seat for the turned-off reviewer persona, flagged as a swap. The user approves; the launch report names the playbook, the Captain starts it, and the first step reaches the planner seat. Asking for "the release playbook" by name does the same; a message that only mentions the playbook in passing gets an ordinary roster. (AC1, AC2, AC3, AC6) +- **A smaller bench.** In Billing Migration the user checks two models under Models for custom members. The Captain, running on a third, proposes a Builder persona and a custom scribe that inherits the Captain's model; the roster card's preview refuses the scribe naming the model, the project and the setting and listing the two. The user picks one of them for the scribe from a picker that offers only those, and approves; the Builder still runs on its own model, which isn't checked. (AC24–AC26) - **A poisoned Crew.** The Critic has gone wrong and confused its crewmates. The Captain asks to archive the Crew; the refusal lists two open asks and one running turn seat by seat with a token; the Captain confirms after checking with the user, writes a fresh brief from the surviving branch and handoff artifacts, and proposes a successor. (AC16, AC19, AC20) ## History @@ -142,3 +153,4 @@ The platform ships the machinery — propose, gate, spawn, render, remind, notif - 2026-10-22 — active peer steering covers Claude (Bryant). - 2026-10-17 — several people (Jackson; [record](../../worklog/2026-10-16-people-and-access-session.md)): "the person" is anyone who can write to the Captain's thread, and a Crew's later requests reach all of them, which ends the stall where a guest who asked for a Crew never saw its seats' approvals (AC23; [#534](https://github.com/Jacksondr5/j5code/issues/534)). - 2026-10-27 — the Captain's timeline shows the person only what they would act on: launch and finish notices become one line per seat that needs them, a Crew member's message a compact row, and each seat's row says how its last run ended (Bryant; [#741](https://github.com/Jacksondr5/j5code/issues/741)). +- 2026-10-27 — models for custom members: a project's list of checked models decides what custom seats, plain spawned agents and plain delegated tasks run on; personas keep their own model; native subagents are outside the list on every provider, and AC24–AC28 (Bryant; [#744](https://github.com/Jacksondr5/j5code/issues/744)). diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index ed9333c256813..b040b88d089e7 100644 --- a/docs/j5/product/upstream.md +++ b/docs/j5/product/upstream.md @@ -118,6 +118,18 @@ Letter codes in the Decided lines (SC2, QS1, AR3, and so on) are rulings recorde **Decided:** Jackson, 2026-10-13. Recorded in FORK.md case 74. +#### D39. A plain delegated task runs only on a model the project allows + +**Upstream:** `delegate_task` runs the child on the model it resolves from the call's `target`, or on the parent's own model when none is given, and J5's persona-aware wrapper only sees `target`. + +**J5:** upstream's `delegateTask` takes an optional `authorizeTarget` hook that it calls with the child's project and resolved model, after resolving the target and before creating anything. J5's wrapper passes one for a call without a persona, which refuses a model that is off the project's list under Settings → Agent Setup → Crews → Models for custom members, an inherited model included, and lists the eligible models so the agent can retry with `target`. A call that names a persona, and a retry of a delegation already accepted, are not checked. + +**Why:** the list is one decision that custom Crew seats, `j5_spawn_agent` and `delegate_task` all follow ([Crews](features/crews.md), AC27). The wrapper cannot see the model a child inherits, so the check needs the one place that resolves it. + +**Consequences:** one optional input and four lines in `OrchestratorMcpService.ts` (FORK.md case 90), with no change to upstream's behavior when no hook is passed. Check at each advance that the call still sits after the target resolves and before the command is dispatched. `t3_thread_launch` and `create_threads`, which J5 hides from agents, are not checked. + +**Decided:** Bryant, 2026-10-27 ([#744](https://github.com/Jacksondr5/j5code/issues/744)). Recorded in FORK.md case 90. + ### New threads #### D12. Multi-model send is refused from a persona draft @@ -604,6 +616,7 @@ J5 kept a run from resuming after a usage-limit reset when the person had presse - 2026-10-19 — D33: T3 Connect's sessions are the first owner's, as they were full access before levels (review of [#638](https://github.com/Jacksondr5/j5code/pull/638)). - 2026-10-19 — D37 added: a connection that keeps failing can be retried at once on web and desktop (Jackson). - 2026-10-24 — D38 added: a completion sound can be a local MP3 on web and desktop (proposed by Abraham, accepted by Jackson). +- 2026-10-27 — D39 added: a plain `delegate_task` is held to the project's models for custom members through one hook in upstream's `delegateTask` (Bryant; [#744](https://github.com/Jacksondr5/j5code/issues/744)). - 2026-10-20 — D2 clarifies that native-question answers retain upstream access and attribution behavior, and placed-agent notices replace raw thread waiting ([#674](https://github.com/Jacksondr5/j5code/pull/674), [#281](https://github.com/Jacksondr5/j5code/issues/281), [existing access decision](https://github.com/Jacksondr5/j5code/issues/345#issuecomment-6092125478)). - 2026-10-24 — D2: agents get upstream's queue tools, with edit held to an agent's own messages and the ledger following every edit; D4: the platform delivers in send order and a person or an agent may reorder by hand (Jackson, [#136](https://github.com/Jacksondr5/j5code/issues/136)). - 2026-10-24 — D33: lowering or removing an Owner ends the MCP clients that Owner approved, and only those (Jackson; [#639](https://github.com/Jacksondr5/j5code/issues/639)). diff --git a/docs/j5/user/personas.md b/docs/j5/user/personas.md index 94be2d4ed95e7..7bf66f8845947 100644 --- a/docs/j5/user/personas.md +++ b/docs/j5/user/personas.md @@ -46,10 +46,12 @@ A crew is a group of agents that one agent, the Captain, runs as a unit for one > Put together a crew to follow @docs/runbooks/release.md for the 2.4 release and report back when the PR is green. -The agent uses the conversation to propose a roster above the composer. Each member has a responsibility, a reason for joining, and instructions. Members may use saved personas or be custom agents created for this task. You can remove members, add a saved persona, or add a custom seat with a name and instructions, then approve or decline. Custom members start with the Captain's harness, model, and reasoning level, and with Full access. Before approval, you can change their harness, model, reasoning level, and access, whether the agent proposed the member or you added it manually. Selecting a saved persona uses that persona's configured runtime policy. No special Captain persona is needed, and one Captain can coordinate several crews in the same conversation. Before you approve, each member shows its resolved harness, model, reasoning level, and access. Members whose access asks before acting are marked **Stops for approvals**: they pause in their own threads until you answer, so give them Full access if you will not be watching. Changing the roster refreshes these details. If the configuration changes before launch, review the refreshed settings and approve again. The preview also covers the Captain's branch and worktree, so switching the Captain's branch before you approve means reviewing a fresh preview. Each member also shows where it works, chosen by the Captain for every member it proposes: **Captain's checkout**, a **New worktree** from a base branch, or an **Existing worktree** of the project. You can change any member's choice before approving. A new worktree offers a searchable branch list, starting at the Captain's current one, with an option to start from the branch's copy on origin; an existing worktree offers the project's worktrees. A member you add yourself starts in the Captain's checkout. A new worktree's setup script starts with it, and unless the script is set to finish first, the member may begin before it does. If preparing a member's worktree fails, the Captain is told why in the launch report. A member on an ACP registry harness offers only **Supervised** and **Full access**, because those harnesses can't enforce **Auto-accept edits** or **Auto**. +The agent uses the conversation to propose a roster above the composer. Each member has a responsibility, a reason for joining, and instructions. Members may use saved personas or be custom agents created for this task. You can remove members, add a saved persona, or add a custom seat with a name and instructions, then approve or decline. Custom members start with the Captain's harness, model, and reasoning level, and with Full access, as long as that model is one **Models for custom members** allows. Before approval, you can change their harness, model, reasoning level, and access, whether the agent proposed the member or you added it manually. Selecting a saved persona uses that persona's configured runtime policy. No special Captain persona is needed, and one Captain can coordinate several crews in the same conversation. Before you approve, each member shows its resolved harness, model, reasoning level, and access. Members whose access asks before acting are marked **Stops for approvals**: they pause in their own threads until you answer, so give them Full access if you will not be watching. Changing the roster refreshes these details. If the configuration changes before launch, review the refreshed settings and approve again. The preview also covers the Captain's branch and worktree, so switching the Captain's branch before you approve means reviewing a fresh preview. Each member also shows where it works, chosen by the Captain for every member it proposes: **Captain's checkout**, a **New worktree** from a base branch, or an **Existing worktree** of the project. You can change any member's choice before approving. A new worktree offers a searchable branch list, starting at the Captain's current one, with an option to start from the branch's copy on origin; an existing worktree offers the project's worktrees. A member you add yourself starts in the Captain's checkout. A new worktree's setup script starts with it, and unless the script is set to finish first, the member may begin before it does. If preparing a member's worktree fails, the Captain is told why in the launch report. A member on an ACP registry harness offers only **Supervised** and **Full access**, because those harnesses can't enforce **Auto-accept edits** or **Auto**. To let Captains launch new Crews without reviewing the initial roster, open **Settings → Agent Setup → Crews** and enable **Auto-approve new Crews**. It starts off. Use the settings scope to set an environment default or a project override. Changing it leaves existing Crews and open proposals alone. +To choose which models custom members may run on, open **Settings → Agent Setup → Crews → Models for custom members**. The row reads, for example, "6 of 12"; open it to check or uncheck each model of the providers you have set up. Until you save a list, every model is allowed, and after you save one a model added later starts unchecked. If nothing is checked, no custom member can start, and the row says so. The same list applies to custom crew members, whether you or the Captain added them and whether the crew launched automatically, and to agents started without a persona by another agent. A custom member's model picker on the roster card offers only the checked models, and a model that isn't checked is refused with the models that are. Set an environment default or a project override like **Auto-approve new Crews**. Personas always run on their own model, even one that isn't checked; the row names any persona whose model isn't. The list doesn't cover native subagents, which Codex, Claude and Cursor start on a model of their own choosing. + A crew can follow a playbook: ask for one by name, and the Captain assigns each member the steps it owns. The roster card then shows the playbook, which member owns which step, the steps no member owns (the Captain does those), and any step whose persona differs from the member's, including when the wanted persona is missing or turned off. You can't move steps between members; removing a member leaves its steps unowned, and the card tells you. If the playbook or a persona it names changes after you open the card, approval asks you to review again. A conversation on any harness can propose a crew. On **Codex** and **Claude**, the roster is the only Crew approval when auto-approval is off. With auto-approval on, it launches directly. Other harnesses may show their own approval prompt once before the roster, and a conversation running as a saved persona with read-only access can't propose a crew on them. Two cases differ: From 9eecba597e698f01e0ed78827caf0ed8613ba1ad Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 13:53:15 -0400 Subject: [PATCH 04/12] chore(j5): keep the models-for-custom-members contract exports minimal (#744) Co-Authored-By: Claude Sonnet 5.5 --- packages/contracts/src/j5/crewMemberModels.test.ts | 2 +- packages/contracts/src/j5/crewMemberModels.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/contracts/src/j5/crewMemberModels.test.ts b/packages/contracts/src/j5/crewMemberModels.test.ts index 991b765aed37f..38957dffc9016 100644 --- a/packages/contracts/src/j5/crewMemberModels.test.ts +++ b/packages/contracts/src/j5/crewMemberModels.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "vitest"; +import { describe, expect, it } from "vite-plus/test"; import { ProviderInstanceId } from "../providerInstance.ts"; import type { ServerProvider } from "../server.ts"; diff --git a/packages/contracts/src/j5/crewMemberModels.ts b/packages/contracts/src/j5/crewMemberModels.ts index 52457352a5c87..12317b1c2ad6e 100644 --- a/packages/contracts/src/j5/crewMemberModels.ts +++ b/packages/contracts/src/j5/crewMemberModels.ts @@ -20,7 +20,7 @@ export type CrewMemberModel = typeof CrewMemberModel.Type; export const CrewMemberModels = Schema.NullOr(Schema.Array(CrewMemberModel)); export type CrewMemberModels = typeof CrewMemberModels.Type; -export const CREW_MEMBER_MODELS_SETTING_LABEL = "Models for custom members in Agent Setup"; +const CREW_MEMBER_MODELS_SETTING_LABEL = "Models for custom members in Agent Setup"; type ModelKey = Pick; From ceeb85d06c800d8e46ded77dfb960bae5bebb5f4 Mon Sep 17 00:00:00 2001 From: Bryant Derosier Date: Tue, 27 Oct 2026 18:54:58 -0400 Subject: [PATCH 05/12] feat(web): models for custom members as collapsible provider cards (#744) A flat checklist of every model was long and hard to scan. Each set-up provider is now a card with its count, one open at a time, with models as toggle chips, and providers that aren't set up fold into one line. Co-Authored-By: Claude Sonnet 5.5 --- .../src/j5/crew/CrewMemberModelsSettings.tsx | 158 ++++++++++-------- 1 file changed, 85 insertions(+), 73 deletions(-) diff --git a/apps/web/src/j5/crew/CrewMemberModelsSettings.tsx b/apps/web/src/j5/crew/CrewMemberModelsSettings.tsx index 3cd7723a918a7..50b9f1820e491 100644 --- a/apps/web/src/j5/crew/CrewMemberModelsSettings.tsx +++ b/apps/web/src/j5/crew/CrewMemberModelsSettings.tsx @@ -8,7 +8,7 @@ import { type CrewMemberModels, } from "@t3tools/contracts/j5"; import { Link } from "@tanstack/react-router"; -import { AlertTriangleIcon, ChevronDownIcon, ChevronRightIcon } from "lucide-react"; +import { AlertTriangleIcon, CheckIcon, ChevronDownIcon, ChevronRightIcon } from "lucide-react"; import { useMemo, useState } from "react"; import { ProviderInstanceIcon } from "../../components/chat/ProviderInstanceIcon"; @@ -20,7 +20,8 @@ import { useUpdateScopedSettings, } from "../../components/settings/useScopedSettings"; import { Button } from "../../components/ui/button"; -import { Checkbox } from "../../components/ui/checkbox"; +import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../../components/ui/collapsible"; +import { Toggle } from "../../components/ui/toggle"; import { deriveProviderInstanceEntries } from "../../providerInstances"; import { serverEnvironment } from "../../state/server"; import { useEnvironmentQuery } from "../../state/query"; @@ -54,63 +55,67 @@ function ProviderModels(props: { readonly providers: ReadonlyArray; readonly entry: ReturnType[number]; readonly list: CrewMemberModels; + readonly open: boolean; + readonly onOpenChange: (open: boolean) => void; readonly onChange: (next: ReadonlyArray) => void; }) { const { provider, entry, list } = props; const { checked, total } = crewMemberModelCounts(list, [provider]); + const Chevron = props.open ? ChevronDownIcon : ChevronRightIcon; return ( -
-
-
- - {entry.displayName} - +
+ +
+ + + {checked} of {total} +
- -
-
    - {provider.models.map((model) => ( -
  • - -
  • - ))} -
+ +
    + {provider.models.map((model) => { + const pair = { instanceId: provider.instanceId, model: model.slug }; + const isChecked = isCrewMemberModelChecked(list, pair); + return ( +
  • + + props.onChange(setCrewMemberModelChecked(list, props.providers, pair, next)) + } + > + {isChecked ? +
  • + ); + })} +
+
+
); } @@ -128,6 +133,7 @@ export function CrewMemberModelsSettings() { const environmentId = target?.environmentId ?? null; const list = settings.crewMemberModels; const [open, setOpen] = useState(false); + const [openProvider, setOpenProvider] = useState(null); const providers = useAtomValue( serverEnvironment.providersValueAtom(environmentId ?? NO_ENVIRONMENT), ); @@ -136,6 +142,8 @@ export function CrewMemberModelsSettings() { ); const entries = useMemo(() => deriveProviderInstanceEntries(providers ?? []), [providers]); const known = providers ?? []; + const setUp = entries.filter((entry) => isCrewMemberProviderSetUp(entry.snapshot)); + const notSetUp = entries.filter((entry) => !isCrewMemberProviderSetUp(entry.snapshot)); const summary = crewMemberModelsSummary(list, known); const offList = personasOffCrewMemberModels(catalog.data, list); const save = (next: ReadonlyArray) => updateSettings({ crewMemberModels: next }); @@ -173,7 +181,10 @@ export function CrewMemberModelsSettings() { aria-expanded={open} aria-controls="crew-member-models-panel" disabled={environmentId === null} - onClick={() => setOpen((value) => !value)} + onClick={() => { + setOpen((value) => !value); + setOpenProvider((current) => current ?? setUp[0]?.instanceId ?? null); + }} > {mixed ? "Mixed" : summary.label}