diff --git a/FORK.md b/FORK.md index 3949e16d47f5e..039069c2ac58f 100644 --- a/FORK.md +++ b/FORK.md @@ -76,7 +76,7 @@ These files exist upstream, but J5 owns its copy outright and they are not integ ### Sanctioned appended integration cases -Against upstream pin `d2c440312e5f39d59827ed466838a623516454d6`, the inventory has 107 entries: 1–106 plus 15b. Seventeen are retired and keep their numbers (10–14, 15b, 16–18, 20, 27–29, 54, 55, 61, 66), and 19 and 39 are retired except for a remainder. Existing numbers never change; a new case takes the next number. Line coordinates and landing SHAs below describe historical integrations; use named symbols and tests after upstream movement. Branding has its own inventory in `BRANDING.md`; temporary defect patches are listed separately below. +Against upstream pin `d2c440312e5f39d59827ed466838a623516454d6`, the inventory has 108 entries: 1–107 plus 15b. Seventeen are retired and keep their numbers (10–14, 15b, 16–18, 20, 27–29, 54, 55, 61, 66), and 19 and 39 are retired except for a remainder. Existing numbers never change; a new case takes the next number. Line coordinates and landing SHAs below describe historical integrations; use named symbols and tests after upstream movement. Branding has its own inventory in `BRANDING.md`; temporary defect patches are listed separately below. 1. A1's independent communication-ledger migration lane: in `apps/server/src/persistence/Sqlite.ts`, `layerSetup` runs `runJ5CompatibleUpstreamMigrations` and then `runJ5A2AMigrations` where upstream calls `runMigrations()`. Upstream's `layerConfig` has already run `initializeV2Database`, which copies `state.sqlite` to `statev2.sqlite`, so both run only against `statev2.sqlite`. J5 adopts that copy-on-first-start unchanged (Jackson's 2026-09-24 decision #2): an existing `statev2.sqlite` wins and `state.sqlite` is never recopied or written again, so the cutover is one-way: writes after the first V2 boot are invisible to an older binary. Snapshot before the upgrade, and roll back across it by stopping writers and moving `statev2.sqlite` aside (`docs/j5/runbooks/dogfood-runtime.md`); never run old and new binaries against the two files. `layerFromPath` calls one J5 step, `snapshotBeforeMigrations` (`apps/server/src/j5/persistence/MigrationSnapshot.ts`), before it builds the SQL layer, so every file-backed open is covered. When the database has migration history and either lane has a migration pending (upstream's `effect_sql_migrations` against upstream's manifest, or `j5_a2a_migrations` against J5's ledger list), it is first copied with `VACUUM INTO`, through a read-only connection, to `statev2.pre-migration-u-j.sqlite` beside it, named for the newest migration each lane had recorded. The copy is synchronous and does not use `node:sqlite`'s `backup()`: on the Node 26 that release executables embed, `backup()` rejects the one-step rate Node 24 accepts and its promise settles only when another event wakes the loop, which stopped the first nightly from starting. The snapshot is a compacted copy in rollback-journal mode; the server sets WAL again when it opens a restored one. A database with no history, or with nothing pending, is not copied. The newest three snapshots are kept (`MIGRATION_SNAPSHOTS_KEPT`) and older ones deleted. This is the roll-forward policy's emergency exit (issue #507): J5 adds no refusal to start on a database newer than the build, as upstream adds none for that case. Upstream refuses only a history that would skip one of V2's own migrations (`assertV2MigrationsCanRun` in `Migrations.ts`), and a second server on the same home (`apps/server/src/serverOwnership.ts`, exit 78), whose lock `layerMakeServer` takes before anything opens the database, so before the snapshot. A failed copy dies there, so the server does not start and nothing migrates. It dies rather than fails so the layer's error type, which upstream's tests name, stays upstream's. `MigrationSnapshot.test.ts` covers it. The `j5_run_observability_migrations` lane (one index) is not consulted. J5 tooling (`fleet-load.ts`, `devDeliverySeed.ts`, `dogfood-snapshot.sh`, `dogfood-local.sh`) targets `statev2.sqlite`; `apps/server/src/j5/persistence/StateV2Cutover.test.ts` covers the copy, no-recopy and failed-first-boot retry. Case 31 defines the compatibility wrapper; J5's own migration IDs remain in separate tracking tables and run after upstream migration completion. 2. The authenticated J5 MCP registration seam: the `layer` of `apps/server/src/mcp/McpHttpServer.ts` calls `layerJ5Toolkits(toolkitRegistration)` (`apps/server/src/j5/a2a/mcp/registration.ts`) in place of upstream's orchestrator, thread, attachment, project and environment registrations. Upstream's preview, preview-controls, worktree, pull-request, device and html toolkits are registered whole, as upstream registers them. Upstream's lint rule `no-raw-mcp-registration` allows MCP registration only in `McpHttpServer.ts`, so J5 registers through the `toolkitRegistration` function that file passes in. `layerJ5Toolkits` registers J5's own tools and the admitted part of those five upstream toolkits. `upstreamCatalog.ts` selects the admitted tools one by one and runs them on upstream's own handlers through `handlersFor`, which is one documented cast. Upstream's `McpServer.toolkit` asks for every tool's declared dependencies at registration, so J5's environment toolkit registration (`registration.ts`) provides `ThreadCommandExecutor.layer`, as upstream's own does. `apps/server/src/mcp/McpInvocationContext.ts` adds the `artifacts` capability that case 33's tools check. @@ -529,6 +529,8 @@ migrations after upstream migrations. 106. 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. A seat's thread also keeps what it was told (register D43): after the provider accepts a prompt that carried the introduction or a roster change, `CrewTurnContext.ts` dispatches the server-only `platform-message.record` command with that text, ids derived from the conversation and the text so a retry records once, and a failure to post is logged without failing the turn. `packages/contracts/src/orchestrationV2.ts` appends the command to the internal command union; `orchestration-v2/Orchestrator.ts` adds one `commandThreadId` case, one `dispatch` case and `dispatchPlatformMessageRecord`, which emits the existing `message.updated` and `turn-item.updated` events for the named run with no run created or queued; `ProviderTurnStartService.ts` adds `runId: run.id` to the delivery it already hands the seat service; and `runtimeLayer.ts` builds the orchestrator layers above the two turn services so `CrewTurnContext.layer` can depend on the orchestrator. The client side is J5-owned: `presentCrewContext` in `packages/client-runtime/src/j5/crewNotices.ts`, `CrewNoticeRenderer.tsx` on web and `timeline.tsx` on mobile. `Orchestrator.platform-message.test.ts` proves the command, and `CrewDeliveryContext.test.ts` and its integration test prove the posting. On an advance, retain the hooks at actual delivery and steering after queue selection, shared by every provider and transport, and the internal command with its one decision function. +107. Models for custom members ([#744](https://github.com/Jacksondr5/j5code/issues/744), register D42, 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, and `packages/shared/src/projectSettings.test.ts` gains one case for the key's whole-list replace and project override. On an advance, keep the one call after the target resolves and before anything is created. + ## Pin and upstream advance runbook Current pin: `d2c440312e5f39d59827ed466838a623516454d6`, upstream's stable release tag `v0.1.3` on `main` (frozen 2026-10-27). The previous pin was `70d60e03a7a35c6fa131825bbfa05ec893e69912`, upstream's nightly tag `v0.1.1-nightly.20261017.3238`. @@ -823,7 +825,7 @@ explicitly marked. | `apps/server/src/environment/ServerEnvironmentLabel.ts` | N | 67 | | `apps/server/src/httpCors.ts` | N | B | | `apps/server/src/mcp/McpHttpServer.ts` | R | 2 | -| `apps/server/src/mcp/OrchestratorMcpService.ts` | A | Saved-agent mentions | +| `apps/server/src/mcp/OrchestratorMcpService.ts` | A | Saved-agent mentions, 107 | | `packages/contracts/src/previewAutomation.ts` | N | 74 | | `apps/server/src/preview/ServerBrowserStream.ts` | N | Preview stream session invalidation (#798) | | `apps/server/src/preview/ServerBrowserStream.test.ts` | N | Preview stream session invalidation (#798) | @@ -928,7 +930,7 @@ explicitly marked. | `packages/contracts/src/server.test.ts` | N | 43 | | `packages/contracts/src/server.ts` | N | 42, 43 | | `packages/contracts/src/settings.test.ts` | N | 42 | -| `packages/contracts/src/settings.ts` | N | 42, B, 105 | +| `packages/contracts/src/settings.ts` | N | 42, B, 105, 107 | | `packages/shared/package.json` | N | 43, 46, 49, 52 | | `packages/shared/src/devHome.test.ts` | R | H | | `packages/shared/src/paletteSearch.test.ts` | N | B | @@ -1028,6 +1030,7 @@ explicitly marked. | `packages/shared/src/cliRelease.ts` | N | 40 | | `packages/shared/src/promptLinks.test.ts` | N | 76 | | `packages/shared/src/promptLinks.ts` | N | B, 76 | +| `packages/shared/src/projectSettings.test.ts` | N | 107 | | `apps/web/src/components/chat/TimelineUserMessageRow.tsx` | N | 7, 80, B | | `apps/web/src/components/chat/timelineRowContext.ts` | N | 24 | | `apps/web/src/components/chat/TimelineWorkEntryRow.tsx` | N | 80 | diff --git a/apps/server/src/j5/a2a/CrewLaunchService.test.ts b/apps/server/src/j5/a2a/CrewLaunchService.test.ts index 021896ba7d0a5..3bba281f006ac 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( @@ -2202,3 +2210,311 @@ 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), +); + +it.effect( + "a persona seat frozen on its fallback route is unchanged while the primary is back", + () => + Effect.gen(function* () { + const claudeModels = provider("claudeAgent", "claudeAgent", [ + { slug: "claude-opus-5", options: ["high"] }, + { slug: "claude-sonnet-5", options: ["high"] }, + ]); + const { layer, captain } = yield* eligibilityFixture({ + providers: [codexModels("gpt-5.6-sol"), claudeModels], + settings: { crewMemberModels: [] }, + }); + yield* Effect.gen(function* () { + const launcher = yield* CrewLaunchService; + const persona = { + workspace: { type: "shared" as const }, + name: "builder", + agentId: "builder", + reason: "Builds", + runtimeMode: "approval-required" as const, + }; + const claude = (model: string) => ({ + instanceId: ProviderInstanceId.make("claudeAgent"), + model, + options: [{ id: "effort", value: "high" }], + }); + // The primary (Codex) resolves again, but the card froze the fallback (Claude) route. + const [fallback] = yield* launcher.resolveSeats(captain, [ + { ...persona, modelSelection: claude("claude-opus-5") }, + ]); + assert.equal(fallback!.modelSelection.model, "claude-opus-5"); + const refused = yield* launcher + .resolveSeats(captain, [{ ...persona, modelSelection: claude("claude-sonnet-5") }]) + .pipe(Effect.flip); + assert.equal(refused._tag, "CrewLaunchModelNotEligibleError"); + }).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 d73163f6dc2c3..831df5ce5ab1f 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 { @@ -186,6 +187,16 @@ class CrewLaunchSeatUnavailableError extends Data.TaggedError("CrewLaunchSeatUna } } +/** A custom seat's model is not on the project's "Models for custom members" list. */ +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. */ class CrewLaunchCapError extends Data.TaggedError("CrewLaunchCapError")<{ readonly crewInstanceId: string; @@ -223,6 +234,7 @@ export class CrewLaunchOperationError extends Data.TaggedError("CrewLaunchOperat export type CrewLaunchError = | CrewLaunchSeatUnavailableError + | CrewLaunchModelNotEligibleError | CrewLaunchCapError | CrewLaunchSeatConflictError | CrewLaunchOperationError @@ -270,6 +282,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* ( @@ -306,9 +319,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, @@ -346,13 +362,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. The person sees and can change it on the roster card. @@ -396,13 +424,30 @@ 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); const catalog = yield* agents.catalog(); const definition = catalog.definitions.find(({ id }) => id === agentId); + // Editing any field on the roster card freezes the model it showed into the seat, and + // that is the fallback route when the primary's provider was signed out at proposal + // time. A seat counts as keeping the persona's model by matching either route, never by + // its absence. + const frozen = seat.modelSelection; + const frozenDriver = providers.find( + (candidate) => candidate.instanceId === frozen.instanceId, + )?.driver; + const keepsPersonaModel = + definition?.modelRoute.some( + (target) => target.driver === frozenDriver && target.model === frozen.model, + ) ?? false; + const { modelSelection, provider } = yield* resolveSelection( + seat, + seat.modelSelection, + !keepsPersonaModel, + ); if (definition === undefined || catalog.disabledIds.includes(agentId)) return yield* new CrewLaunchSeatUnavailableError({ seatName: seat.name, @@ -435,13 +480,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 bb7621970ba5a..9cd8dbbdff66f 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"; @@ -1768,9 +1769,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 })), @@ -3401,6 +3411,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 ff6fe1c7ba4ca..16906fe9b1426 100644 --- a/apps/server/src/j5/a2a/CrewProposalService.ts +++ b/apps/server/src/j5/a2a/CrewProposalService.ts @@ -1027,6 +1027,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 2fa5ec1d18057..549fb547c35c5 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 1ce4d64fb483c..747301f292772 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 25d2f28b4323c..774619ee348b2 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.test.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.test.ts @@ -46,6 +46,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)({}), @@ -1457,6 +1459,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)({}), @@ -1660,6 +1663,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 }), @@ -1984,6 +1988,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)({}), @@ -2121,6 +2126,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 }), @@ -2250,6 +2256,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 8eec8eb7e7dc2..b14e6a10c1286 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 86d28cbf8cb6d..c883df4149df0 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, @@ -104,6 +105,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/registration.test.ts b/apps/server/src/j5/a2a/mcp/registration.test.ts index e14b3212d54e3..d633b7510f31e 100644 --- a/apps/server/src/j5/a2a/mcp/registration.test.ts +++ b/apps/server/src/j5/a2a/mcp/registration.test.ts @@ -27,6 +27,7 @@ import { A2AHomeRegistrar } from "../HomeRegistrar.ts"; import { AgentCrewInstanceService } from "../AgentCrewInstanceService.ts"; import { ArchiveCrewService } from "../ArchiveCrewService.ts"; import { CrewProposalService } from "../CrewProposalService.ts"; +import { CrewMemberModels } from "../../agents/crewMemberModels.ts"; import { CrewStopService } from "../CrewStopService.ts"; import { PeerRegistryService } from "../PeerRegistryService.ts"; import { PlaybookCrewRelay } from "../../playbooks/PlaybookCrewRelay.ts"; @@ -100,6 +101,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/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index 68909c9aed710..0bb759c336fcc 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -30,6 +30,7 @@ import { OrchestratorV2 } from "../../../orchestration-v2/Orchestrator.ts"; import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts"; import { DocumentText } from "../../../provider/DocumentText.ts"; import { ProviderRegistry } from "../../../provider/ProviderRegistry.ts"; +import { CrewMemberModels } from "../../agents/crewMemberModels.ts"; import { AgentCrewInstanceService } from "../AgentCrewInstanceService.ts"; import { ArchiveCrewService } from "../ArchiveCrewService.ts"; import { @@ -575,16 +576,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."; 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."; @@ -642,6 +643,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 a47be9b054e02..222505c1b9833 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"; @@ -175,6 +176,7 @@ 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 a745d71dc31a8..fbbeb397111df 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"; import { noDocumentTextLayer } from "../test-support/documentText.ts"; const checkout = ( @@ -188,6 +194,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>([]); @@ -214,6 +222,7 @@ const spawnHarness = (input: { acceptsUrgency: false, } satisfies ParticipantDirectoryRow; const dependencies = Layer.mergeAll( + input.memberModels ?? permissiveCrewMemberModels, noDocumentTextLayer, Layer.mock(A2ASendService)({ listParticipants: () => Effect.succeed([callerRow]) }), Layer.mock(A2AHomeRegistrar)({ @@ -576,6 +585,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 fa789acda6ad7..dd3a029671112 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 @@ -37,7 +38,7 @@ export type J5DelegateTaskInput = typeof J5DelegateTaskInput.Type; * fallback. */ export const J5_DELEGATE_TASK_DESCRIPTION = - "Start one child agent with only `task`. No parent history. 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, for same-provider work the native subagent tool cannot run, or for work the user wants tracked as a J5 task; for an ordinary subagent request, use your provider's native subagent mechanism instead. Separate checkout or PR per child: `isolation:'worktree'`. Keep `taskId` for `task_status` and `task_cancel`."; + "Start one child agent with only `task`. No parent history. 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, for same-provider work the native subagent tool cannot run, or for work the user wants tracked as a J5 task; for an ordinary subagent request, use your provider's native subagent mechanism instead. 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`. Separate checkout or PR per child: `isolation:'worktree'`. Keep `taskId` for `task_status` and `task_cancel`."; /** J5's delegate_task: the upstream tool with the persona extension, registered in place of it. */ export const J5DelegateTaskTool = Tool.make("delegate_task", { @@ -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..bfd06d906a7f0 --- /dev/null +++ b/apps/server/src/j5/test-support/crewMemberModels.ts @@ -0,0 +1,38 @@ +import type { ServerProvider } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +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.succeedSome({ 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 3ac3fe99f7e09..7922b033a03a3 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -149,6 +149,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: ( @@ -2165,6 +2170,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/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..745ed94acc5c3 --- /dev/null +++ b/apps/web/src/j5/crew/CrewMemberModelsSettings.tsx @@ -0,0 +1,234 @@ +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 { 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 { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../../components/ui/collapsible"; +import { deriveProviderInstanceEntries } from "../../providerInstances"; +import { serverEnvironment } from "../../state/server"; +import { useEnvironmentQuery } from "../../state/query"; +import { agentPersonaEnvironment } from "../agents/agentPersonaAtoms"; +import { + crewMemberModelLabel, + crewMemberModelsSummary, + personasOffCrewMemberModels, + setCrewMemberModelChecked, + setCrewMemberProviderChecked, +} from "./crewMemberModels.logic"; + +const NO_ENVIRONMENT = "" as EnvironmentId; + +/** One model: solid when allowed. Every chip fills its grid cell, so they all match in size. */ +function ModelChip(props: { + readonly name: string; + readonly checked: boolean; + readonly onChange: (checked: boolean) => void; +}) { + return ( + + ); +} + +function ProviderModels(props: { + readonly provider: ServerProvider; + 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 ( +
+ +
+ + + + {checked} of {total} + + +
+ +
    + {provider.models.map((model) => { + const pair = { instanceId: provider.instanceId, model: model.slug }; + return ( +
  • + + props.onChange(setCrewMemberModelChecked(list, props.providers, pair, next)) + } + /> +
  • + ); + })} +
+
+
+
+ ); +} + +/** + * 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 [openProvider, setOpenProvider] = useState(null); + const providers = useAtomValue( + serverEnvironment.providersValueAtom(environmentId ?? NO_ENVIRONMENT), + ); + const catalog = useEnvironmentQuery( + environmentId === null ? null : agentPersonaEnvironment.catalog({ environmentId, input: {} }), + ); + const entries = deriveProviderInstanceEntries(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 }); + const Chevron = open ? ChevronDownIcon : ChevronRightIcon; + + return ( + + + ); +} diff --git a/apps/web/src/j5/crew/CrewProposalCard.browser.test.tsx b/apps/web/src/j5/crew/CrewProposalCard.browser.test.tsx index 1985acf73afbd..5cd60339c1f92 100644 --- a/apps/web/src/j5/crew/CrewProposalCard.browser.test.tsx +++ b/apps/web/src/j5/crew/CrewProposalCard.browser.test.tsx @@ -11,7 +11,12 @@ import type { } from "@t3tools/contracts/j5"; import { 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(import("@effect/atom-react"), async (importOriginal) => ({ ...(await importOriginal()), useAtomValue: ((atom: unknown) => atom) as never, @@ -24,6 +29,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] : {} }), })); @@ -127,6 +133,7 @@ const preview = ( const resolve = vi.fn(); function setup() { state.permitted = true; + state.memberModels = null; state.preview.mockReset().mockImplementation(preview); state.read.mockReset().mockImplementation(({ input }: { input: { personaId: string } }) => Promise.resolve({ @@ -615,3 +622,27 @@ 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 () => { + setup(); + state.memberModels = [{ instanceId: "codex", model: "gpt-6" }]; + await using _screen = await render(card(), { router: false }); + 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 () => { + setup(); + state.memberModels = [{ instanceId: "codex", model: "gpt-6" }]; + await using _screen = await render(card(), { router: false }); + 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 e306c1cbf4104..50a8915c4ced6 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) ?? @@ -329,6 +334,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 3a4c3a1ecd248..612b81a149635 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, 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; @@ -142,6 +143,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 9af351395ae59..bc0e56b4f914c 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 { getProviderOptionCurrentValue } from "@t3tools/shared/model"; import { Input } from "../../components/ui/input"; @@ -38,6 +43,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; @@ -213,19 +220,34 @@ function CrewSeatWorkspaceField(props: CrewSeatEditorProps) { function CrewSeatRuntimeFields(props: CrewSeatEditorProps & { environmentId: EnvironmentId }) { const providers = useAtomValue(serverEnvironment.providersValueAtom(props.environmentId)) ?? []; - const choices = providers.filter( - (provider) => - provider.enabled && - provider.installed && - provider.status === "ready" && - provider.availability !== "unavailable" && - provider.models.length > 0, - ); + // 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 = 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 }]; + }); const entries = deriveProviderInstanceEntries(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 ?? @@ -307,9 +329,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)); }} > @@ -318,7 +339,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..ff519412aac03 --- /dev/null +++ b/apps/web/src/j5/crew/crewMemberModels.logic.test.ts @@ -0,0 +1,104 @@ +import { + ProviderInstanceId, + type OrchestrationV2AgentPersonaCatalog, + type ServerProvider, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + crewMemberModelLabel, + 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("drops the Claude prefix on the Claude provider only", () => { + const stock = provider(claude, [], { driver: "claudeAgent" } as Partial); + const viaCursor = provider(ProviderInstanceId.make("cursor"), [], { + driver: "cursor", + } as Partial); + expect(crewMemberModelLabel(stock, "Claude Opus 5.5")).toBe("Opus 5.5"); + expect(crewMemberModelLabel(stock, "Haiku 5.5")).toBe("Haiku 5.5"); + expect(crewMemberModelLabel(viaCursor, "Claude Opus 5.5")).toBe("Claude Opus 5.5"); + }); + + 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..8a804e3615e1c --- /dev/null +++ b/apps/web/src/j5/crew/crewMemberModels.logic.ts @@ -0,0 +1,88 @@ +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; + +/** + * A model's chip label. The Claude card is already named Claude, so its models drop the prefix; the + * same models under Cursor keep it, since that is what tells them apart there. + */ +export const crewMemberModelLabel = (provider: ServerProvider, name: string): string => + provider.driver === "claudeAgent" ? name.replace(/^Claude\s+/u, "") : name; + +/** 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; +} diff --git a/docs/j5/product/a2a/agent-tools.md b/docs/j5/product/a2a/agent-tools.md index 337f98248e80d..f54ab7c599cbc 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. T 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` (which also updates a task since upstream folded `update_scheduled_task` into it at v0.1.3), `list_scheduled_tasks`, `delete_scheduled_task`, `run_scheduled_task_now` — 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_act`, `watch_pull_request`, `unwatch_pull_request` — consumed as-is. `preview_act` is upstream's one browser-control tool since v0.1.3, in place of `preview_click`, `preview_drag`, `preview_hover`, `preview_press`, `preview_scroll`, `preview_select`, `preview_type` and `preview_upload`. @@ -441,6 +445,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 @@ -493,3 +498,4 @@ run; `j5_stop_crew` doesn't, and unarchiving doesn't restart it. - 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 — the advance onto upstream's stable v0.1.3, which merged 18 tools into action tools: the kept tools name `t3_queue` (J5's edit rule on its `edit` action), `t3_thread_transfer` (J5's fork error), `t3_pending_request`, `preview_act` and `schedule_task`'s updates in place of the tools they replaced, and `t3_background_wait` joins (Jackson, 2026-10-27) ([register of divergences](../upstream.md), D2). +- 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 f593993d96082..2dd75b07821c5 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 37f562cbe52ad..80c82122213b1 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 (Jackson, 2026-10-31), 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. The list applies when the agent is created, not afterwards: a later model change, for example an agent setting a thread's model with `t3_thread_configure`, is not limited. 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 as one card per set-up provider (one open at a time, a same-size chip for each model, solid when checked) and sends the others to Providers in one line, 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 @@ -143,4 +154,5 @@ 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, 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)). - 2026-10-31 — a member's introduction and roster changes are visible in its own thread, as a collapsed card that opens to what the model read, where they had been sent to the model only (Jackson, 2026-10-31; register D43). diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index 5585c1801c23c..5f0563c26a0e6 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. +#### D42. 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 107), 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. The list holds when an agent is created and not afterwards: `t3_thread_configure` sets any thread's model with only a thread-write check, so a later model change is not limited. + +**Decided:** Bryant, 2026-10-27 ([#744](https://github.com/Jacksondr5/j5code/issues/744)). Recorded in FORK.md case 107. + #### D43. A thread can keep a message the platform wrote without a run **Upstream:** a message in a thread's history is a turn: dispatching one always starts a run, queues one behind the running turn, or steers the running one. There is no way to add something to the history that the agent is not asked to answer. @@ -638,6 +650,7 @@ J5 kept a run from resuming after a usage-limit reset when the person had presse - 2026-10-26 — D33: a Viewer, or a Collaborator on one thread, isn't offered a new thread, a fork or a new project where their level refuses it (Jackson's 2026-10-25 approval; [#640](https://github.com/Jacksondr5/j5code/issues/640), [#641](https://github.com/Jacksondr5/j5code/issues/641)). - 2026-10-27 — `j5/main`'s changes merged into the 2026-10-24 advance: the completion-sound decision, added as D38 on `j5/main`, is D39, because the advance took D38; D4 records that upstream now refuses a steer to a stopping run, so a J5 peer steer to GPT 6 or Claude joins the queue instead. - 2026-10-27 — the 2026-10-24 advance moved forward to upstream's stable v0.1.3: D40 added, upstream's guest links hidden because they need T3 Connect (Jackson, 2026-10-25; [#725](https://github.com/Jacksondr5/j5code/issues/725)); D1 takes upstream's shorter instructions and relaxed settings rule; D2 takes upstream's merged action tools (82 tools) and admits `t3_background_wait` (Jackson, 2026-10-27); D4 and D6 re-checked, with upstream's new steer default for a person's follow-ups leaving agent deliveries alone; D27's dev servers follow upstream's opt-in. +- 2026-10-27 — D42 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-31 — D33: the preview stream closes when its session is revoked, replaced or expires, as the RPC socket already did, so a lowered level stops a preview at once ([#798](https://github.com/Jacksondr5/j5code/issues/798)). - 2026-10-31 — D33: "Merge back" is disabled for someone who can't start a thread in the fork's project, which the server already refused (Jackson's 2026-10-31 approval; [#730](https://github.com/Jacksondr5/j5code/issues/730)). - 2026-11-01 — D33: the mobile client reads shared conversations as web does, with each message's author and avatar, who answered each prompt, and another person's message held until its author is known; sharing itself stays on web and desktop (the mobile catch-up; [#832](https://github.com/Jacksondr5/j5code/issues/832), [#871](https://github.com/Jacksondr5/j5code/issues/871), [#869](https://github.com/Jacksondr5/j5code/issues/869)). diff --git a/docs/j5/user/personas.md b/docs/j5/user/personas.md index 71fdddcbb49ae..a5ad24152dd1e 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: diff --git a/packages/contracts/src/j5.ts b/packages/contracts/src/j5.ts index 79a04b5fd1be2..8f06bb5334e88 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..38957dffc9016 --- /dev/null +++ b/packages/contracts/src/j5/crewMemberModels.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from "vite-plus/test"; + +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..12317b1c2ad6e --- /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; + +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 095bfcddf2655..a6d7fe77d048f 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -28,6 +28,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"; @@ -970,6 +971,7 @@ export const PROJECT_SCOPED_SERVER_SETTING_KEYS = [ "newWorktreesStartFromOrigin", "worktreeSubmodules", "crewAutoApprove", + "crewMemberModels", "defaultAutoPull", "defaultProjectScripts", "enableAgentBrowserAccess", @@ -1008,6 +1010,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), @@ -1048,6 +1051,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("honours the aggregate's own fields only until the server has folded them", () => { const aggregateModel = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5"); const project = {