diff --git a/FORK.md b/FORK.md index 92fac016ab9c7..59ff06b668909 100644 --- a/FORK.md +++ b/FORK.md @@ -83,9 +83,9 @@ Against upstream pin `322f6544dfad0a3c8a0c8cbecf2c7f7874b14268`, the inventory h Every tool J5 owns is named with a `j5_` prefix, so none reads as a harness's native tool ([#508](https://github.com/Jacksondr5/j5code/issues/508)); upstream's names stay as upstream's, including the ones J5 re-declares (`delegate_task`, `orchestrator_capabilities`, `t3_thread_transfer`, `t3_thread_organize`, `t3_queue`, `t3_attachment_prepare_upload`). The rule for which name a tool carries: a J5 name when J5 changes what it takes, returns or means, and upstream's name when J5 only adds a refusal, an error message or a corrected description (Jackson, 2026-10-11, [#519](https://github.com/Jacksondr5/j5code/issues/519)). The pre-prefix names are not registered; `apps/web/src/j5/a2a/ThreadA2ARenderer.tsx` still reads them in recorded history, and the ledger command ids for a send and a clear keep their original `send_message` and `clear_own_ask` segments (`commandIdForRequest`). - Every tool carries one of upstream's `McpToolAccess` declarations. J5's tools that need a calling thread are declared through J5-owned `actsAsThreadCaller` or `readsAsThreadCaller` (`apps/server/src/j5/a2a/mcp/outsideAgent.ts`), which are upstream's `writes` and `reads` with a check that refuses an outside agent with the move it can make instead: the Crew, clear, playbook and artifact tools; the send, spawn and stop tools take an outside agent and are `j5Writes`. Every J5 `writes` goes through `j5Writes`, which passes the one option this case adds to upstream's `apps/server/src/mcp/McpToolAccess.ts`: `writes` takes an optional `linkedRefusal`, the words a caller from a fenced link is told it may not do, because upstream's refusal always says it cannot "change this environment's scheduled tasks". J5's says it cannot "message, start or stop agents here, which only this environment's own work may" (Jackson's decision 3 of 2026-11-07, the fence wording). Upstream's tools pass nothing and keep upstream's words. `j5_list_personas` and `orchestrator_capabilities` are `reads`. `t3_thread_organize` is `writesThreads`, and `t3_thread_transfer` and `t3_queue` are upstream's `either` of `reads` for their read actions (`status`; `list` and `read`) and `writesThreads` for the rest, as upstream's are. Upstream's sign-in for outside agents (`McpOAuth.layerMcpClientAuthenticator`) is provided as upstream ships it. An outside client has no calling thread, so upstream's own check refuses J5's caller tools (Jackson's 2026-10-08 decision 5; a ledger identity for outside agents is [#498](https://github.com/Jacksondr5/j5code/issues/498)). + Every tool carries one of upstream's `McpToolAccess` declarations. J5's tools that need a calling thread are declared through J5-owned `actsAsThreadCaller` or `readsAsThreadCaller` (`apps/server/src/j5/a2a/mcp/outsideAgent.ts`), which are upstream's `writes` and `reads` with a check that refuses an outside agent with the move it can make instead: the Crew, clear, playbook and artifact tools; the send, spawn and stop tools take an outside agent and are `j5Writes`. Every J5 `writes` goes through `j5Writes`, which passes the one option this case adds to upstream's `apps/server/src/mcp/McpToolAccess.ts`: `writes` takes an optional `linkedRefusal`, the words a caller from a fenced link is told it may not do, because upstream's refusal always says it cannot "change this environment's scheduled tasks". J5's says it cannot "message, start or stop agents here, which only this environment's own work may" (Jackson's decision 3 of 2026-11-07, the fence wording). Upstream's tools pass nothing and keep upstream's words. The case also adds `eitherBy` to that file: upstream's `either`, picked by an effect instead of a plain test of the parameters, because a declaration can only be built there; J5's `t3_thread_interrupt` uses it to pick the Captain's rule, and a call bound for a linked environment takes the second declaration's check. `j5_list_personas` and `orchestrator_capabilities` are `reads`. `t3_thread_organize` is `writesThreads`, and `t3_thread_transfer` and `t3_queue` are upstream's `either` of `reads` for their read actions (`status`; `list` and `read`) and `writesThreads` for the rest, as upstream's are. Upstream's sign-in for outside agents (`McpOAuth.layerMcpClientAuthenticator`) is provided as upstream ships it. An outside client has no calling thread, so upstream's own check refuses J5's caller tools (Jackson's 2026-10-08 decision 5; a ledger identity for outside agents is [#498](https://github.com/Jacksondr5/j5code/issues/498)). - J5 declares six tools itself. `orchestratorSurface.ts` holds `orchestrator_capabilities`, because upstream's description points at tools J5 hides, and `delegate_task`, which takes a persona. `threadTools.ts` holds `t3_thread_transfer`, whose `fork` action reports a lineage failure in J5's words, `t3_thread_organize`, which applies the Crew-seat archive guard and settles through upstream's `settleThread`, and `t3_queue`, whose `edit` action lets an agent edit only a queued message it sent and puts the new text of a J5 message inside that message's envelope; all three keep upstream's parameters and reach, and their other actions (`merge_back` and `status`; `list`, `read`, `cancel`, `reorder` and `promote_to_steer`) follow upstream's handlers in `toolkits/thread/handlers.ts`. Upstream merged 18 of its tools into action tools at v0.1.3 (pingdotgg/t3code#25423): `t3_thread_fork`, `t3_thread_merge_back` and `t3_thread_transfers` into `t3_thread_transfer`, the six `t3_queue_*` tools into `t3_queue`, the three `t3_pending_request_*` tools into `t3_pending_request`, `t3_thread_configuration` into `t3_thread_configure`, `update_scheduled_task` into `schedule_task`, and eight browser controls (`preview_click`, `preview_drag`, `preview_hover`, `preview_press`, `preview_scroll`, `preview_select`, `preview_type`, `preview_upload`) into `preview_act`. J5 re-declared the merged transfer and queue tools and admits the merged pending-request and configure tools in `upstreamCatalog.ts`; cancel, reorder and promote work on any queued message, as upstream ships them (Jackson, 2026-10-24, [#136](https://github.com/Jacksondr5/j5code/issues/136)). `attachments.ts` holds `t3_attachment_prepare_upload`, whose description points at `j5_send_message` where upstream's points at `t3_thread_send_attachments`; it runs on upstream's handler. Upstream's `t3_thread_send_attachments` is not registered: `j5_send_message` takes `attachments`, claimed into the receiver's thread by `sendClaimingAttachments` in the same file. `t3_thread_read` is upstream's tool again, and merging back is upstream's behavior in `t3_thread_transfer` (decision 6): thread tools reach any thread in the environment, writes included. Upstream's raw send and bulk-create tools and `t3_project_delete` stay unregistered, and `t3_thread_launch` is listed only to a link session (case 111). `t3_project_create`, `t3_project_update` and `t3_environment_preferences_update` are admitted as upstream ships them (Jackson, 2026-10-11, [#519](https://github.com/Jacksondr5/j5code/issues/519)); `t3_project_delete` waits on [#552](https://github.com/Jacksondr5/j5code/issues/552). Upstream removed `t3_thread_start`; it stays in the exclusion assertions as a regression guard. `t3_thread_wait` and `t3_thread_interrupt` are upstream's and admitted to every caller since the advance onto stable v0.1.7 (Jackson's decision 3 of 2026-11-07, register D2): waiting, stopping, thread housekeeping, scheduling and links are upstream's, and J5 owns participants, the ledger, Exchanges, Peer Agents, peering, Crews and personas. That retires the 2026-09-14 rule that kept `t3_thread_wait` off because a blocked turn cannot take the notices queued behind it; upstream's wait is bounded. `j5_stop_agent` stays until [#955](https://github.com/Jacksondr5/j5code/issues/955) retires it for a J5 re-declaration of `t3_thread_interrupt` that keeps the Captain's exemption. `j5_spawn_agent` takes what upstream's `t3_thread_launch` offers and J5's lacked ([#519](https://github.com/Jacksondr5/j5code/issues/519)): another project, upstream's "No project" project with a folder claimed through upstream's `ManagedProjectFolders.folderForThread`, a permission choice checked with upstream's `exceededDispatchModeLimit`, attachments on the brief, and the project's main checkout as a workspace. A spawner in another project is recorded as provenance and is no placement parent (`PlacementService.ts`), and `spawnedChildrenRead.ts` keeps such an agent at the sidebar's top level. `j5_list_participants` lists one project a page at a time with the cursor, limit and filters of upstream's `t3_thread_list` ([#519](https://github.com/Jacksondr5/j5code/issues/519)), and exposes every result field in snake_case at every depth, including nested agent `thread_id`, provenance `spawned_by_participant_id` / `source_participant_id`, `placement_parent_id`, and `display_name`; never restore any upstream camelCase directory or provenance field during a rebase. One admitted upstream tool keeps upstream's Tool object with one sentence of its description edited in place, because the original named a tool J5 hides: `t3_worktree_handoff` (`apps/server/src/mcp/toolkits/worktree/tools.ts`) points at `j5_spawn_agent` where upstream says `t3_thread_launch`. On an advance, re-read every admitted tool's description for names missing from the production inventory. Later J5 verbs extend the fork-owned toolkit without another protected-file registration or runtime provider. + J5 declares seven tools itself. `orchestratorSurface.ts` holds `orchestrator_capabilities`, because upstream's description points at tools J5 hides, `delegate_task`, which takes a persona, and `t3_thread_interrupt`, which keeps upstream's description and parameters and adds the Captain's rule (`threadInterrupt.ts`, below). `threadTools.ts` holds `t3_thread_transfer`, whose `fork` action reports a lineage failure in J5's words, `t3_thread_organize`, which applies the Crew-seat archive guard and settles through upstream's `settleThread`, and `t3_queue`, whose `edit` action lets an agent edit only a queued message it sent and puts the new text of a J5 message inside that message's envelope; all three keep upstream's parameters and reach, and their other actions (`merge_back` and `status`; `list`, `read`, `cancel`, `reorder` and `promote_to_steer`) follow upstream's handlers in `toolkits/thread/handlers.ts`. Upstream merged 18 of its tools into action tools at v0.1.3 (pingdotgg/t3code#25423): `t3_thread_fork`, `t3_thread_merge_back` and `t3_thread_transfers` into `t3_thread_transfer`, the six `t3_queue_*` tools into `t3_queue`, the three `t3_pending_request_*` tools into `t3_pending_request`, `t3_thread_configuration` into `t3_thread_configure`, `update_scheduled_task` into `schedule_task`, and eight browser controls (`preview_click`, `preview_drag`, `preview_hover`, `preview_press`, `preview_scroll`, `preview_select`, `preview_type`, `preview_upload`) into `preview_act`. J5 re-declared the merged transfer and queue tools and admits the merged pending-request and configure tools in `upstreamCatalog.ts`; cancel, reorder and promote work on any queued message, as upstream ships them (Jackson, 2026-10-24, [#136](https://github.com/Jacksondr5/j5code/issues/136)). `attachments.ts` holds `t3_attachment_prepare_upload`, whose description points at `j5_send_message` where upstream's points at `t3_thread_send_attachments`; it runs on upstream's handler. Upstream's `t3_thread_send_attachments` is not registered: `j5_send_message` takes `attachments`, claimed into the receiver's thread by `sendClaimingAttachments` in the same file. `t3_thread_read` is upstream's tool again, and merging back is upstream's behavior in `t3_thread_transfer` (decision 6): thread tools reach any thread in the environment, writes included. Upstream's raw send and bulk-create tools and `t3_project_delete` stay unregistered, and `t3_thread_launch` is listed only to a link session (case 111). `t3_project_create`, `t3_project_update` and `t3_environment_preferences_update` are admitted as upstream ships them (Jackson, 2026-10-11, [#519](https://github.com/Jacksondr5/j5code/issues/519)); `t3_project_delete` waits on [#552](https://github.com/Jacksondr5/j5code/issues/552). Upstream removed `t3_thread_start`; it stays in the exclusion assertions as a regression guard. `t3_thread_wait` and `t3_thread_interrupt` are upstream's and admitted to every caller since the advance onto stable v0.1.7 (Jackson's decision 3 of 2026-11-07, register D2): waiting, stopping, thread housekeeping, scheduling and links are upstream's, and J5 owns participants, the ledger, Exchanges, Peer Agents, peering, Crews and personas. That retires the 2026-09-14 rule that kept `t3_thread_wait` off because a blocked turn cannot take the notices queued behind it; upstream's wait is bounded. `j5_stop_agent` is retired for that re-declaration ([#955](https://github.com/Jacksondr5/j5code/issues/955)). `j5_spawn_agent` takes what upstream's `t3_thread_launch` offers and J5's lacked ([#519](https://github.com/Jacksondr5/j5code/issues/519)): another project, upstream's "No project" project with a folder claimed through upstream's `ManagedProjectFolders.folderForThread`, a permission choice checked with upstream's `exceededDispatchModeLimit`, attachments on the brief, and the project's main checkout as a workspace. A spawner in another project is recorded as provenance and is no placement parent (`PlacementService.ts`), and `spawnedChildrenRead.ts` keeps such an agent at the sidebar's top level. `j5_list_participants` lists one project a page at a time with the cursor, limit and filters of upstream's `t3_thread_list` ([#519](https://github.com/Jacksondr5/j5code/issues/519)), and exposes every result field in snake_case at every depth, including nested agent `thread_id`, provenance `spawned_by_participant_id` / `source_participant_id`, `placement_parent_id`, and `display_name`; never restore any upstream camelCase directory or provenance field during a rebase. One admitted upstream tool keeps upstream's Tool object with one sentence of its description edited in place, because the original named a tool J5 hides: `t3_worktree_handoff` (`apps/server/src/mcp/toolkits/worktree/tools.ts`) points at `j5_spawn_agent` where upstream says `t3_thread_launch`. On an advance, re-read every admitted tool's description for names missing from the production inventory. Later J5 verbs extend the fork-owned toolkit without another protected-file registration or runtime provider. At every advance, review each new upstream tool and decide whether to admit it. A tool in a toolkit registered whole arrives exposed, and the case 4 test fails until its name is added; a tool in one of the five selected toolkits stays hidden until `upstreamCatalog.ts` names it. The 2026-10-17 advance admitted three (Jackson's decision that day): `t3_workflow_stop`, which `upstreamCatalog.ts` adds to `J5OrchestratorToolkit`, and the pull-request toolkit's `write_pull_request_guides` and `read_pull_request_guide`. Upstream's new `McpToolAccess.writesWithCapability` changes none of J5's declarations. The advance onto stable v0.1.3 brought one new tool, `t3_background_wait` (pingdotgg/t3code#24610: a Claude thread stays Working while background work it names runs), which `upstreamCatalog.ts` adds to `J5OrchestratorToolkit`. Jackson admitted it on 2026-10-27; upstream's Claude system prompt tells agents to call it. The advance onto stable v0.1.7 brought five new tools. `link_pull_requests` and `unlink_pull_requests`, in the pull-request toolkit, arrive exposed and are admitted as shipped. The three link tools, `t3_environment_links`, `t3_environment_link` and `t3_environment_unlink`, are added to `J5OrchestratorToolkit` (Jackson's decision 1 of 2026-11-05, linked environments as shipped) and are listed only while Settings › Labs turns linked environments on. With them `t3_thread_wait` and `t3_thread_interrupt` join `J5OrchestratorToolkit`, and `t3_thread_launch` joins `J5ProjectToolkit` behind `McpSchema.EnabledWhen` (case 111). About 32 admitted upstream tools gained an optional `environmentId`, which forwards the call to a linked machine; J5's re-declared transfer, organize and queue tools inherit it through upstream's parameter schemas, so their J5 rules run on the machine that receives the call. @@ -199,8 +199,7 @@ includes the self-messaging law at `48037fadd6929e8b7f79c697a0031958a9ae416c`. I MCP toolkit and runtime composition: `j5_spawn_agent` creates an ordinary root-lineage thread, atomically records immutable home plus placement/provenance facts through the existing A6 services, and then dispatches one stable first-turn brief; -`j5_stop_agent` resolves exactly one participant with `listParticipants` and stops -its thread with upstream's Stop (below). `PlacementCascadeService` and +`PlacementCascadeService` and `listSubtree` have no A2 consumer. The authoritative total lifecycle lock order is `drainPermit ≺ appendPermit ≺ @@ -235,7 +234,7 @@ storage and names `j5_list_participants` and `schedule_task` as the shipped alte and the one replay-stable spawn turn carries committed `participant_id` plus project facts in platform context beside the byte-preserved spawner brief. -`j5_stop_agent` finds its target among every agent on this server by participant id, in any project, archived ones included ([#519](https://github.com/Jacksondr5/j5code/issues/519)). The authorization is upstream's rule for a write to another thread, checked with upstream's `loadCaller` and `assertTargetWithinLimits` (`apps/server/src/mcp/threadAccess.ts`): the target may not run with broader modes than the caller. The caller's limit also goes with the Stop as upstream's `DispatchModeLimit`, so the orchestrator checks it again under the target's lock. A Captain stopping a seat of its own Crew is exempt from both. The stop itself is upstream's `thread.stop`, sent through J5-owned `apps/server/src/j5/a2a/stopThread.ts` (Jackson's 2026-10-08 decision 11). It interrupts the running turn, holds the thread's queue, ends its pull request watches and, since the 2026-10-24 advance, stops the thread's delegated tasks itself (pingdotgg/t3code#23886), so `stopThread` only dispatches `thread.stop`. It is sent to an idle target too, so that target's queue is held (the implementer's call at the 2026-10-08 advance). `j5_stop_agent` and a Captain's Crew stop pass `AGENT_STOP_REASON` ("Stopped by an agent"), where upstream's thread would say the user stopped it; a person's Crew stop passes none. A held queue means an A2A delivery to a stopped agent waits until someone resumes the thread (case 26). The tool reads its result from the target's runs. Crew stop and Crew retirement stop each seat the same way. +Agents stop an agent with upstream's `t3_thread_interrupt`, re-declared by J5 with one rule (register D2, [#955](https://github.com/Jacksondr5/j5code/issues/955)). `apps/server/src/j5/a2a/mcp/threadInterrupt.ts` declares it with `eitherBy`: when the caller is the Captain of the live Crew seat the target holds, the call is `actsAsCaller` and stops or interrupts with no mode check and no `DispatchModeLimit`; every other caller, outside agents included, gets upstream's `writesThreads` declaration and `OrchestratorMcpService.interruptThread`, so the target may not run with broader modes than the caller and the orchestrator checks again under the target's lock. A Captain's `stop: true` is upstream's `thread.stop`, sent through J5-owned `apps/server/src/j5/a2a/stopThread.ts` (Jackson's 2026-10-08 decision 11). It interrupts the running turn, holds the thread's queue and ends its pull request watches. Since the 2026-10-24 advance it also stops the thread's delegated tasks (pingdotgg/t3code#23886), but only when one of them has a thread here. So the Captain's path then calls `stopDelegatedTasks` with the same command, as upstream's handler does, which also ends delegates on a linked machine and lets a retry repeat a failed stop. Crew stop and Crew retirement call `stopThread` alone. Upstream's `stop: true` passes the caller's reason as given, so a Stop without one reads as the user's; J5 words every agent's Stop as upstream words an interrupt, with `agentStopReason` ("Stopped by an agent"), and a Captain's Crew stop passes `AGENT_STOP_REASON`; a person's Crew stop passes none. A held queue means an A2A delivery to a stopped agent waits until someone resumes the thread (case 26). Crew stop and Crew retirement stop each seat the same way. `t3_thread_organize` replaces `archive_agent`. The J5 handler adds no archive authorization of its own: upstream's access check applies, which since the 2026-10-08 advance reaches any thread in the environment. Closure is performed once by the existing PR132 lifecycle reactor for every command door. The internal `ArchiveAgentService` remains for crew confirmation and interruption; only its MCP tool is retired. Crew-seat archive is refused by organize, and Captain archives retain the existing crew cascade. Ordinary non-crew agent archive adopts upstream self-archive and active-run semantics and has no token exchange. Human UI warnings remain. The obsolete standalone archive MCP handler and tool schemas are removed; archive/unarchive lifecycle, terminal notices and identity retention are covered through the replacement command path. diff --git a/apps/server/src/j5/a2a/CrewStopService.ts b/apps/server/src/j5/a2a/CrewStopService.ts index 690f71888fdc9..073b79d68a739 100644 --- a/apps/server/src/j5/a2a/CrewStopService.ts +++ b/apps/server/src/j5/a2a/CrewStopService.ts @@ -138,7 +138,7 @@ export const layer = Layer.effect( return yield* new CrewStopRequestError({ detail: `Crew ${instance.id} is commanded by ${instance.captainParticipantId}; only its Captain or the human may stop it.`, nextStep: - "Ask the Captain with j5_send_message, or stop one agent you command with j5_stop_agent.", + "Ask the Captain with j5_send_message, or stop one agent with t3_thread_interrupt and stop: true.", }); if (instance.archivedAt !== null) return yield* new CrewStopRequestError({ diff --git a/apps/server/src/j5/a2a/README.md b/apps/server/src/j5/a2a/README.md index 8bbdfedfd955e..15fc20bffd755 100644 --- a/apps/server/src/j5/a2a/README.md +++ b/apps/server/src/j5/a2a/README.md @@ -20,7 +20,7 @@ A3 requires every sent-message event and delivery row to declare an explicit env The silence detector checkpoints its global v2 event sequence in the J5 migration lane. A new installation first reconciles only open delivered exchanges against current thread projections, records the existing v2 high-water mark, and then tails from that durable cursor; retries replay at most the uncheckpointed tail instead of scanning the event store from genesis on every boot. A broken v2 subscription uses capped exponential backoff without re-running the reconciliation scan on every attempt. -Archive closure is a separate platform lifecycle write authority in `LifecycleService.ts`; it is never an A3 silence action and is not exposed through the agent MCP toolkit. Participant archive appends `participant.archived`, retaining identity, immutable home, and provenance while disabling addressability. It terminates affected open Exchanges with `exchange.dropped` and stable system notices, and cancels pending deliveries. Accepted queue entries are withdrawn before recording cancellation, including outgoing work queued in another thread. A delivery that already reached a run or a successful provider steer remains delivered; this records delivery, not processing completion. Thread archive, including `t3_thread_organize`, can leave an active run executing; `j5_stop_agent` remains the explicit interruption tool. Human notices require a durable terminal inbox row. `j5_list_participants` hides archived agents unless `include_archived` is true; those rows explicitly remain unaddressable. +Archive closure is a separate platform lifecycle write authority in `LifecycleService.ts`; it is never an A3 silence action and is not exposed through the agent MCP toolkit. Participant archive appends `participant.archived`, retaining identity, immutable home, and provenance while disabling addressability. It terminates affected open Exchanges with `exchange.dropped` and stable system notices, and cancels pending deliveries. Accepted queue entries are withdrawn before recording cancellation, including outgoing work queued in another thread. A delivery that already reached a run or a successful provider steer remains delivered; this records delivery, not processing completion. Thread archive, including `t3_thread_organize`, can leave an active run executing; `t3_thread_interrupt` is the explicit interruption tool. Human notices require a durable terminal inbox row. `j5_list_participants` hides archived agents unless `include_archived` is true; those rows explicitly remain unaddressable. The lifecycle reactor consumes committed archive, unarchive, and delete events from a durable cursor. Unarchive restores the same membership without reopening Exchanges, replaying cancelled messages, or starting a turn. Delete removes membership and live placement while retaining peer history and provenance events; surviving children display as roots when their placement parent is absent. Historical `participant.left` facts remain permanently retired, including after migration, membership rebuild, or thread unarchive. Threads that are not participants (provider Subagents) remain no-ops. diff --git a/apps/server/src/j5/a2a/mcp/handlers.test.ts b/apps/server/src/j5/a2a/mcp/handlers.test.ts index 5a983ce8d7790..dbc7114b9b1e6 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.test.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.test.ts @@ -28,7 +28,6 @@ import { ProviderDriverKind, ProviderInstanceId, ThreadId, - type OrchestrationV2Run, type OrchestrationV2ServerCommand, type OrchestrationV2ThreadProjection, type ServerProvider, @@ -54,11 +53,10 @@ import { OrchestratorProjectionError, OrchestratorV2, } from "../../../orchestration-v2/Orchestrator.ts"; -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 { AgentCrewInstanceService } from "../AgentCrewInstanceService.ts"; import { ArchiveCrewConfirmationRequiredError, ArchiveCrewService, @@ -107,7 +105,6 @@ import { type J5ProposeCrewInput, type J5RequestCrewMemberInput, type J5SpawnAgentInput, - type J5StopAgentInput, } from "./tools.ts"; import { noDocumentTextLayer } from "../../test-support/documentText.ts"; @@ -278,7 +275,6 @@ it.effect("namespaces mutating-tool idempotency and sender identity from authent "j5_request_crew_member", "j5_send_message", "j5_spawn_agent", - "j5_stop_agent", "j5_stop_crew", ]); const sends = yield* Ref.make>([]); @@ -3041,213 +3037,6 @@ it.effect("routes crew proposals through a captain that is not itself a crew mem }), ); -it.effect( - "stops exactly one agent as upstream's Stop, in any project, within the caller's modes", - () => - Effect.gen(function* () { - const ledgerProjectId = LedgerProjectId.make("project:j5:mcp-stop"); - const callerParticipantId = ParticipantId.make("agent:j5:mcp-stop-caller"); - const targetParticipantId = ParticipantId.make("agent:j5:mcp-stop-target"); - const siblingParticipantId = ParticipantId.make("agent:j5:mcp-stop-sibling"); - const childParticipantId = ParticipantId.make("agent:j5:mcp-stop-child"); - const targetThreadId = ThreadId.make("thread:j5:mcp-stop-target"); - const siblingThreadId = ThreadId.make("thread:j5:mcp-stop-sibling"); - const childThreadId = ThreadId.make("thread:j5:mcp-stop-child"); - const targetProjectId = ProjectId.make("project:j5:mcp-stop-target"); - const stopped = yield* Ref.make< - ReadonlyArray<{ - readonly commandId: string; - readonly threadId: ThreadId; - readonly reason: string | undefined; - }> - >([]); - const targetRunning = yield* Ref.make(true); - const callerRuntimeMode = yield* Ref.make("full-access"); - const targetIsCallersSeat = yield* Ref.make(false); - const stopLimits = yield* Ref.make>([]); - const callerRow = { - projectId: ledgerProjectId, - participantId: callerParticipantId, - participant: { - kind: "agent" as const, - id: callerParticipantId, - threadId: invocation.threadId, - }, - archived: false, - canReceiveMessage: true, - canOpenExchange: true, - acceptsUrgency: false, - } satisfies ParticipantDirectoryRow; - // The target lives in another project: a stop reaches any agent on this server. - const agentRow = (participantId: ParticipantId, threadId: ThreadId) => - ({ - projectId: LedgerProjectId.make("project:j5:mcp-stop-elsewhere"), - participantId, - participant: { kind: "agent" as const, id: participantId, threadId }, - archived: false, - canReceiveMessage: true, - canOpenExchange: true, - acceptsUrgency: false, - }) satisfies ParticipantDirectoryRow; - const dependencies = Layer.mergeAll( - Layer.succeed( - A2ASendService, - A2ASendService.of({ - ...unusedOutsideAgentSends, - send: () => Effect.die("j5_send_message is outside this stop test"), - clearOwnAsk: () => Effect.die("j5_clear_own_ask is outside this stop test"), - sendAsMachine: () => Effect.die("unused"), - listParticipants: () => - Effect.succeed([ - callerRow, - agentRow(targetParticipantId, targetThreadId), - agentRow(siblingParticipantId, siblingThreadId), - agentRow(childParticipantId, childThreadId), - ]), - }), - ), - Layer.mock(ParticipantPlacementService)({ - listParticipants: () => Effect.die("j5_stop_agent finds its target in the directory"), - listSubtree: () => Effect.die("j5_stop_agent must never resolve placement descendants"), - }), - threadManagementMock({ - getThreadShell: (threadId) => - Ref.get(callerRuntimeMode).pipe( - Effect.map((runtimeMode) => - threadId === invocation.threadId - ? liveThreadShell(threadId, { runtimeMode }) - : null, - ), - ), - getThreadRecords: (threadId) => - Ref.get(targetRunning).pipe( - Effect.map((running) => ({ - ...projection(threadId), - thread: { - ...projection(threadId).thread, - projectId: threadId === targetThreadId ? targetProjectId : projectId, - }, - runs: running ? [{ status: "running" } as OrchestrationV2Run] : [], - })), - ), - dispatch: (command) => - command.type === "thread.stop" - ? Ref.update(stopped, (items) => [ - ...items, - { - commandId: command.commandId, - threadId: command.threadId, - reason: command.reason, - }, - ]).pipe( - // The limit upstream re-checks under the target's lock rides with the Stop. - Effect.andThen(DispatchModeLimit), - Effect.tap((limit) => - Ref.update(stopLimits, (items) => [...items, limit?.runtimeMode]), - ), - Effect.as({ sequence: 1, storedEvents: [] }), - ) - : Effect.die(`j5_stop_agent must only dispatch thread.stop, not ${command.type}`), - // Upstream's thread.stop stops the target's delegated tasks itself. - stopDelegatedTasks: () => - Effect.die("j5_stop_agent leaves delegated tasks to thread.stop"), - interruptThread: () => - Effect.die("j5_stop_agent sends upstream's Stop, not an interrupt"), - }), - Layer.mock(A2AHomeRegistrar)({}), - Layer.mock(A2ALedger)({}), - Layer.mock(SpawnCompositionService)({}), - Layer.mock(OrchestratorMcpService)({}), - peerDirectoryNoneLayer, - Layer.mock(A2ADeliveryWorker)({ notify: Effect.void }), - Layer.mock(AgentCrewInstanceService)({ - findMembership: () => - Ref.get(targetIsCallersSeat).pipe( - Effect.map((seat) => - seat ? { crewInstanceId: "crew:stop", seatName: "builder" } : null, - ), - ), - read: () => - Effect.succeed({ captainParticipantId: callerParticipantId } as AgentCrewInstance), - listForCaptain: () => Effect.succeed([]), - }), - Layer.mock(ArchiveCrewService)({}), - Layer.mock(CrewStopService)({}), - Layer.mock(CrewProposalService)({}), - - Layer.mock(ThreadRegistration)({}), - Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), - ); - const layer = J5ToolkitHandlersLive.pipe( - Layer.provideMerge(fakeSpawnWorkspaceLayer({ checkout: noRepository })), - Layer.provideMerge(dependencies), - ); - - yield* Effect.gen(function* () { - const toolkit = yield* J5Toolkit; - const call = (args: J5StopAgentInput) => - toolkit - .handle("j5_stop_agent", args) - .pipe( - Stream.unwrap, - Stream.run(Sink.last()), - Effect.flatMap(Effect.fromOption), - Effect.provideService(McpInvocationContext, scope), - ); - const args = { - participant_id: targetParticipantId, - client_request_id: "stop-one-1", - } satisfies J5StopAgentInput; - const first = yield* call(args); - const replay = yield* call(args); - assert.equal(first.result, "interrupt_requested"); - assert.deepStrictEqual(replay.result, first.result); - // An idle target is still stopped: Stop also holds its queue and ends its watches. - yield* Ref.set(targetRunning, false); - const idle = yield* call({ - ...args, - client_request_id: "stop-idle-1", - }); - assert.equal(idle.result, "already_idle"); - const calls = yield* Ref.get(stopped); - assert.lengthOf(calls, 3); - assert.isTrue(calls.every((call) => call.threadId === targetThreadId)); - // An agent's Stop says so; without a reason the timeline reads "Stopped by user". - assert.isTrue(calls.every((call) => call.reason === "Stopped by an agent")); - // A replay reuses the command id. - assert.equal(calls[1]?.commandId, calls[0]?.commandId); - assert.notEqual(calls[2]?.commandId, calls[0]?.commandId); - assert.notInclude( - calls.map((call) => call.threadId), - siblingThreadId, - ); - assert.notInclude( - calls.map((call) => call.threadId), - childThreadId, - ); - - // The target runs in full access. A caller in a narrower mode may not stop it. - yield* Ref.set(callerRuntimeMode, "approval-required"); - const refused = yield* call({ ...args, client_request_id: "stop-narrow-1" }); - assert.isTrue(refused.isFailure); - assert.include(JSON.stringify(refused.encodedResult), "broader permissions than you do"); - assert.lengthOf(yield* Ref.get(stopped), calls.length, "a refused stop dispatches nothing"); - // Unless the target is a seat of a Crew the caller commands. - yield* Ref.set(targetIsCallersSeat, true); - const commanded = yield* call({ ...args, client_request_id: "stop-seat-1" }); - assert.equal(commanded.result, "already_idle"); - assert.lengthOf(yield* Ref.get(stopped), calls.length + 1); - // Each Stop carries its caller's limit, except the Captain's, which has none. - assert.deepStrictEqual(yield* Ref.get(stopLimits), [ - "full-access", - "full-access", - "full-access", - undefined, - ]); - }).pipe(Effect.provide(layer)); - }), -); - it.effect( "lists a peer server's agents when it is named and reports the peers it could not read", () => diff --git a/apps/server/src/j5/a2a/mcp/handlers.ts b/apps/server/src/j5/a2a/mcp/handlers.ts index c36be5fafe95b..da57d44fba469 100644 --- a/apps/server/src/j5/a2a/mcp/handlers.ts +++ b/apps/server/src/j5/a2a/mcp/handlers.ts @@ -30,10 +30,7 @@ import { } from "../../../mcp/threadAccess.ts"; import { OrchestratorV2 } from "../../../orchestration-v2/Orchestrator.ts"; -import { - ThreadManagementService, - latestActiveRun, -} from "../../../orchestration-v2/ThreadManagementService.ts"; +import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts"; import { ProjectService } from "../../../project/ProjectService.ts"; import { ProviderRegistry } from "../../../provider/ProviderRegistry.ts"; @@ -67,7 +64,6 @@ import { PeerRegistryService } from "../PeerRegistryService.ts"; import { ParticipantPlacementService } from "../PlacementService.ts"; import { withDeliveryNotice } from "../receiverBacklog.ts"; import { A2ASendService } from "../SendService.ts"; -import { AGENT_STOP_REASON, stopThread } from "../stopThread.ts"; import { sendClaimingAttachments } from "./attachments.ts"; import { outsideAgentCaller, @@ -85,7 +81,6 @@ import { isHumanParticipantId, LedgerProjectId, type ParticipantDirectoryRow, - type ParticipantId, } from "../contracts.ts"; import { AgentPersonaEscalations } from "../../agents/agentPersonaEscalation.ts"; import { @@ -1059,104 +1054,9 @@ const handlers = { }; }).pipe(Effect.mapError(failure)), ), - j5_stop_agent: j5Writes((input) => - Effect.gen(function* () { - const invocation = yield* McpInvocationContext; - const outside = yield* outsideAgentCaller; - const scope = outside === undefined ? yield* callerScope : undefined; - const crypto = yield* SecureRandom.SecureRandom; - // An outside agent has no membership, and is never a Captain. - const callerParticipantId: ParticipantId | undefined = - scope === undefined ? undefined : (yield* resolveCallerMembership(scope)).participantId; - const service = yield* A2ASendService; - // Any agent on this server, archived ones included: archiving can leave a run executing. - const matches = (yield* ( - scope === undefined - ? service.listParticipantsWithoutCaller({ includeArchived: true }) - : service.listParticipants(scope.thread.threadId, true) - ).pipe( - Effect.mapError((error) => - stateError( - `This server's participants cannot be read for j5_stop_agent: ${error.message}.`, - "Retry j5_stop_agent with the same client_request_id.", - ), - ), - )).filter((row) => row.participantId === input.participant_id); - if (matches.length !== 1) { - return yield* stateError( - `This server has ${matches.length === 0 ? "no" : "an ambiguous"} participant ${input.participant_id}.`, - "Call j5_list_participants and retry j5_stop_agent with exactly one listed agent participant_id.", - ); - } - const target = matches[0]!.participant; - if (target.kind !== "agent") { - return yield* stateError( - `Participant ${input.participant_id} is not an agent with a thread and cannot be stopped.`, - "Call j5_list_participants and retry j5_stop_agent with an agent participant_id.", - ); - } - const threadManagement = yield* ThreadManagementService; - const targetProjection = yield* threadManagement - .getThreadRecords(target.threadId, ["runs"]) - .pipe( - Effect.mapError((error) => - stateError( - `Peer Agent thread ${target.threadId} cannot be read for j5_stop_agent: ${error.message}.`, - "Call j5_list_participants to confirm the target thread, then retry j5_stop_agent.", - ), - ), - ); - // Upstream's rule for a write to another thread: it must run within the caller's modes. - // A Captain commands its own seats whatever their modes. - const crews = yield* AgentCrewInstanceService; - const seat = yield* crews.findMembership(input.participant_id); - const crew = seat === null ? null : yield* crews.read(seat.crewInstanceId); - const limits = - callerParticipantId !== undefined && - crew !== null && - crew.captainParticipantId === callerParticipantId - ? undefined - : (yield* loadCaller()).limits; - if (limits !== undefined) { - yield* assertTargetWithinLimits(limits, targetProjection.thread).pipe( - Effect.mapError((error) => - stateError( - `Peer Agent ${input.participant_id} runs with broader permissions than you do: ${error.message}`, - "Ask its Captain or the user to stop it; j5_stop_agent reaches only agents within your own permission modes.", - ), - ), - ); - } - const requestKey = input.client_request_id ?? (yield* crypto.uuidV4().pipe(Effect.orDie)); - const commandId = lifecycleCommandId({ - // An outside agent's retry keys are namespaced by its client session. - providerSessionId: scope?.thread.providerSessionId ?? invocation.requestNamespace, - requestKey, - operation: "stop-agent", - }); - // Upstream's Stop, delegated tasks included (see stopThread.ts). The limit goes with it: - // the target's modes can be raised after the check above, and upstream checks again under - // the thread's lock. - yield* stopThread( - threadManagement, - { commandId, threadId: target.threadId, reason: AGENT_STOP_REASON }, - limits, - ).pipe( - Effect.mapError((error) => - stateError( - `Peer Agent ${input.participant_id} on thread ${target.threadId} could not be stopped: ${error.message}.`, - "Call j5_list_participants to confirm the target, then retry j5_stop_agent with the same client_request_id.", - ), - ), - ); - return latestActiveRun(targetProjection) === undefined - ? ("already_idle" as const) - : ("interrupt_requested" as const); - }).pipe(Effect.mapError(failure)), - ), j5_stop_crew: actsAsThreadCaller( "j5_stop_crew", - "Only a Crew's Captain stops it: message the Captain with j5_send_message, or stop one agent with j5_stop_agent.", + "Only a Crew's Captain stops it: message the Captain with j5_send_message, or stop one agent with t3_thread_interrupt and stop: true.", (input, scope) => Effect.gen(function* () { const crypto = yield* SecureRandom.SecureRandom; diff --git a/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.test.ts b/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.test.ts index 71f5a83d242cc..e788443d27fe6 100644 --- a/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.test.ts +++ b/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.test.ts @@ -37,7 +37,7 @@ it("recognizes policies that need the full J5 set to avoid outright rejection", // Pinned by name: a server-wide default would also wave through worktree // handoff, browser preview, and scheduling for a read-only persona (Sentry S-1, 2026-09-14). -it("names exactly the J5 verbs plus the artifact and Subagent verbs", () => { +it("names exactly the J5 verbs plus the artifact, Subagent and interrupt verbs", () => { assert.sameMembers( [...J5_PREAPPROVED_TOOLS], [ @@ -47,6 +47,8 @@ it("names exactly the J5 verbs plus the artifact and Subagent verbs", () => { "delegate_task", "task_status", "task_cancel", + // Upstream's tool with the Captain's rule, standing in for the retired j5_stop_agent. + "t3_thread_interrupt", ], ); assert.sameMembers( @@ -79,7 +81,7 @@ it("pre-approves the full set only under never, coordination otherwise", () => { if (!never) for (const name of [ "j5_spawn_agent", - "j5_stop_agent", + "t3_thread_interrupt", "j5_stop_crew", "j5_archive_crew", "delegate_task", diff --git a/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts b/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts index 6162299a8e469..6a0116aaedca4 100644 --- a/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts +++ b/apps/server/src/j5/a2a/mcp/j5ToolPreapproval.ts @@ -12,8 +12,8 @@ const J5_DEFINITION_WRITE_TOOLS: ReadonlyArray = ["j5_playbook_save"]; /** * The t3-code tools Codex and Claude pre-approve, so the roster gate stays the only human step. * Harnesses prompt for MCP tools not annotated read-only, and approval policy `never` (full access, - * every saved-agent policy) rejects them. Pre-approved: the J5 verbs, whose handlers authorize each - * call, `j5_write_artifact` for requested files, and the Subagent verbs Crew members use. + * every saved-agent policy) rejects them. Pre-approved: the J5 verbs and `t3_thread_interrupt`, + * whose handlers authorize each call, `j5_write_artifact`, and the Subagent verbs. */ export const J5_PREAPPROVED_TOOLS: ReadonlyArray = [ ...J5_DEFINITION_WRITE_TOOLS, @@ -32,7 +32,7 @@ export const J5_PREAPPROVED_TOOLS: ReadonlyArray = [ "delegate_task", "task_status", "task_cancel", - "j5_stop_agent", + "t3_thread_interrupt", "j5_stop_crew", "j5_archive_crew", "j5_clear_own_ask", diff --git a/apps/server/src/j5/a2a/mcp/orchestratorSurface.test.ts b/apps/server/src/j5/a2a/mcp/orchestratorSurface.test.ts index af2fb55877113..57f7052b62306 100644 --- a/apps/server/src/j5/a2a/mcp/orchestratorSurface.test.ts +++ b/apps/server/src/j5/a2a/mcp/orchestratorSurface.test.ts @@ -1,14 +1,20 @@ +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { expect, it } from "@effect/vitest"; import { agentPersonaDraftsTestLayer } from "../../test-support/agentPersonaDrafts.ts"; import { agentPersonaEscalationsTestLayer } from "../../test-support/agentPersonaEscalations.ts"; import { EnvironmentId, + type OrchestratorMcpThreadInterruptInput, ProviderDriverKind, ProviderInstanceId, + RunId, + type RuntimeMode, ThreadId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Ref from "effect/Ref"; import { McpSchema, McpServer } from "effect/ai"; import * as McpHttpServer from "../../../mcp/McpHttpServer.ts"; @@ -16,10 +22,16 @@ import { McpInvocationContext, type McpInvocationScope, } from "../../../mcp/McpInvocationContext.ts"; +import { liveThreadShell } from "../../../mcp/McpToolAccess.testkit.ts"; import { OrchestratorMcpService } from "../../../mcp/OrchestratorMcpService.ts"; +import { OrchestratorToolkit } from "../../../mcp/toolkits/orchestrator/tools.ts"; +import { DispatchModeLimit } from "../../../orchestration-v2/DispatchModeLimit.ts"; +import { OrchestratorDispatchError } from "../../../orchestration-v2/Orchestrator.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 { participantIdForThread } from "../HomeRegistrar.ts"; import { J5OrchestratorSurface, J5_ORCHESTRATOR_CAPABILITIES_DESCRIPTION, @@ -106,6 +118,8 @@ const TestLayer = McpHttpServer.toolkitRegistration( }, }), Layer.mock(ThreadManagementService)({}), + Layer.mock(AgentCrewInstanceService)({}), + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), Layer.mock(ProviderRegistry)({}), permissiveCrewMemberModels, agentPersonaEscalationsTestLayer(), @@ -122,13 +136,21 @@ const hasKey = (value: unknown, key: string): boolean => { return Object.values(value).some((item) => hasKey(item, key)); }; -it.effect("registers the two orchestrator tools J5 declares, with a factual description", () => +it.effect("registers the orchestrator tools J5 declares, with factual descriptions", () => Effect.gen(function* () { const server = yield* McpServer.McpServer; expect(server.tools.map(({ tool }) => tool.name).sort()).toEqual([ "delegate_task", "orchestrator_capabilities", + "t3_thread_interrupt", ]); + // J5's interrupt adds only a rule, so agents see upstream's tool as shipped. + const interrupt = server.tools.find(({ tool }) => tool.name === "t3_thread_interrupt")?.tool; + const upstream = OrchestratorToolkit.tools.t3_thread_interrupt; + expect(interrupt?.description).toBe(upstream.description); + const j5 = J5OrchestratorSurface.tools.t3_thread_interrupt; + expect(j5.parametersSchema).toBe(upstream.parametersSchema); + expect(j5.successSchema).toBe(upstream.successSchema); const description = server.tools.find(({ tool }) => tool.name === "orchestrator_capabilities") ?.tool.description; @@ -190,3 +212,190 @@ it.effect("maps capabilities with the inherited model and without delegation cla } }).pipe(Effect.provide(TestLayer)), ); + +const captainThreadId = ThreadId.make("thread:j5:interrupt-captain"); +const seatThreadId = ThreadId.make("thread:j5:interrupt-seat"); +const seatRunId = RunId.make("run:j5:interrupt-seat"); +const captainInvocation: McpInvocationScope = { + ...invocation, + thread: { + threadId: captainThreadId, + providerSessionId: "provider-session:j5:interrupt-captain", + // liveThreadShell's instance, so the caller counts as live. + providerInstanceId: ProviderInstanceId.make("codex"), + }, +}; + +it.effect( + "t3_thread_interrupt lets a Captain stop its own seat whatever its modes, and no one else", + () => + Effect.gen(function* () { + const callerMode = yield* Ref.make("approval-required"); + const isSeat = yield* Ref.make(false); + const dispatched = yield* Ref.make< + ReadonlyArray<{ commandId: string; reason: string | undefined; limited: boolean }> + >([]); + const interrupted = yield* Ref.make>([]); + const delegatedStops = yield* Ref.make>([]); + const delegatedStopFails = yield* Ref.make(false); + const upstreamCalls = yield* Ref.make>([]); + const layer = McpHttpServer.toolkitRegistration( + J5OrchestratorSurface, + J5OrchestratorSurfaceHandlers.layer, + ).pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(OrchestratorMcpService)({ + interruptThread: (_scope, input) => + Ref.update(upstreamCalls, (calls) => [...calls, input]).pipe( + Effect.as({ + threadId: input.threadId, + runId: null, + status: "no_active_run" as const, + }), + ), + }), + Layer.mock(ThreadManagementService)({ + getThreadShell: (id) => + id === captainThreadId + ? Effect.map(Ref.get(callerMode), (runtimeMode) => + liveThreadShell(id, { runtimeMode }), + ) + : Effect.succeed(liveThreadShell(id, { runtimeMode: "full-access" })), + dispatch: (command) => + Effect.serviceOption(DispatchModeLimit).pipe( + Effect.flatMap((limit) => + Ref.update(dispatched, (items) => [ + ...items, + { + commandId: command.commandId, + reason: command.type === "thread.stop" ? command.reason : undefined, + limited: limit._tag === "Some" && limit.value !== undefined, + }, + ]), + ), + Effect.as({ + sequence: 1, + storedEvents: [ + { + event: { + type: "run.updated", + runId: seatRunId, + payload: { status: "interrupted" }, + }, + }, + ] as never, + }), + ), + // Delegates on a linked machine have no thread here, so thread.stop leaves them. + stopDelegatedTasks: (input) => + Effect.flatMap(Ref.getAndSet(delegatedStopFails, false), (fails) => + fails + ? Effect.fail( + new OrchestratorDispatchError({ + commandId: input.commandId, + commandType: "delegated_task.remote.complete", + cause: "the stop of a remote delegate failed", + }), + ) + : Ref.update(delegatedStops, (ids) => [...ids, input.commandId]), + ), + interruptThread: (input) => + Ref.update(interrupted, (items) => [...items, { reason: input.reason }]).pipe( + Effect.as({ type: "no_active_run" as const }), + ), + }), + Layer.mock(AgentCrewInstanceService)({ + findMembership: (participantId) => + Effect.map(Ref.get(isSeat), (seat) => + seat && participantId === participantIdForThread(seatThreadId) + ? { crewInstanceId: "crew:j5:interrupt", seatName: "builder" } + : null, + ), + read: () => + Effect.succeed({ + captainParticipantId: participantIdForThread(captainThreadId), + } as AgentCrewInstance), + }), + Layer.mergeAll(NodeServices.layer, NodeCrypto.layer), + Layer.mock(ProviderRegistry)({}), + permissiveCrewMemberModels, + agentPersonaEscalationsTestLayer(), + agentPersonaDraftsTestLayer(), + ), + ), + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + ); + + yield* Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const call = (args: Omit) => + server + .callTool({ name: "t3_thread_interrupt", arguments: args }) + .pipe( + Effect.provideService(McpInvocationContext, captainInvocation), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + // Not its Captain, and the seat runs in broader modes: upstream refuses it. + const refused = yield* call({ threadId: seatThreadId, stop: true }); + expect(refused.isError).toBe(true); + expect(yield* Ref.get(upstreamCalls)).toEqual([]); + + // Within the caller's modes it is upstream's tool, and an agent's Stop says so. + yield* Ref.set(callerMode, "full-access"); + expect((yield* call({ threadId: seatThreadId, stop: true })).isError).toBe(false); + expect((yield* call({ threadId: seatThreadId })).isError).toBe(false); + expect((yield* Ref.get(upstreamCalls)).map((input) => input.reason)).toEqual([ + "Stopped by an agent", + // Upstream words an interrupt's reason itself. + undefined, + ]); + + // Its Captain stops it from a narrower mode, with no limit for upstream to recheck. + yield* Ref.set(callerMode, "approval-required"); + yield* Ref.set(isSeat, true); + const stop = { + threadId: seatThreadId, + stop: true, + reason: "replanning", + clientRequestId: "stop-1", + }; + const stopped = yield* call(stop); + expect(stopped.isError).toBe(false); + expect(stopped.structuredContent).toEqual({ + threadId: seatThreadId, + runId: seatRunId, + status: "interrupt_requested", + }); + yield* call(stop); + const stops = yield* Ref.get(dispatched); + expect(stops.map(({ reason, limited }) => ({ reason, limited }))).toEqual([ + { reason: "Stopped by an agent: replanning", limited: false }, + { reason: "Stopped by an agent: replanning", limited: false }, + ]); + // A retry repeats the same command. + expect(stops[1]?.commandId).toBe(stops[0]?.commandId); + // Each Stop also stops the seat's delegates under its command, as upstream's does. + expect(yield* Ref.get(delegatedStops)).toEqual([stops[0]?.commandId, stops[0]?.commandId]); + + // A delegate stop that fails fails the call, and the same request retries it. + const retried = { ...stop, clientRequestId: "stop-2" }; + yield* Ref.set(delegatedStopFails, true); + expect((yield* call(retried)).isError).toBe(true); + expect((yield* call(retried)).isError).toBe(false); + const retriedStops = yield* Ref.get(dispatched); + expect(retriedStops[3]?.commandId).toBe(retriedStops[2]?.commandId); + expect((yield* Ref.get(delegatedStops)).at(-1)).toBe(retriedStops[2]?.commandId); + + const turn = yield* call({ threadId: seatThreadId }); + expect(turn.structuredContent).toEqual({ + threadId: seatThreadId, + runId: null, + status: "no_active_run", + }); + expect(yield* Ref.get(interrupted)).toEqual([{ reason: "Stopped by an agent" }]); + expect(yield* Ref.get(upstreamCalls)).toHaveLength(2); + }).pipe(Effect.provide(layer)); + }), +); diff --git a/apps/server/src/j5/a2a/mcp/orchestratorSurface.ts b/apps/server/src/j5/a2a/mcp/orchestratorSurface.ts index a37df260ac784..f360860b440de 100644 --- a/apps/server/src/j5/a2a/mcp/orchestratorSurface.ts +++ b/apps/server/src/j5/a2a/mcp/orchestratorSurface.ts @@ -12,11 +12,15 @@ import { ThreadId, type OrchestratorMcpCapabilitiesResult, } from "@t3tools/contracts"; +import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Schema from "effect/Schema"; import { Tool, Toolkit } from "effect/ai"; import * as McpInvocationContext from "../../../mcp/McpInvocationContext.ts"; import { OrchestratorMcpService } from "../../../mcp/OrchestratorMcpService.ts"; +import { OrchestratorToolkit } from "../../../mcp/toolkits/orchestrator/tools.ts"; +import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts"; +import { AgentCrewInstanceService } from "../AgentCrewInstanceService.ts"; const dependencies = [McpInvocationContext.McpInvocationContext, OrchestratorMcpService]; @@ -94,12 +98,33 @@ const J5OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", { .annotate(Tool.Destructive, false) .annotate(Tool.Idempotent, true); +const upstreamInterrupt = OrchestratorToolkit.tools.t3_thread_interrupt; + +/** Upstream's tool as shipped; its handler adds the Captain's rule (threadInterrupt.ts). */ +const J5ThreadInterruptTool = Tool.make("t3_thread_interrupt", { + description: upstreamInterrupt.description, + parameters: upstreamInterrupt.parametersSchema, + success: upstreamInterrupt.successSchema, + failure: OrchestratorMcpFailure, + failureMode: "return", + dependencies: [ + ...dependencies, + ThreadManagementService, + AgentCrewInstanceService, + SecureRandom.SecureRandom, + ], +}) + .annotate(Tool.Title, "Interrupt a J5 thread") + .annotate(Tool.Destructive, true); + /** - * The two orchestrator tools J5 declares itself: `delegate_task` takes a persona, and - * `orchestrator_capabilities` leaves out upstream's claims about tools J5 does not expose. The - * upstream tools J5 registers unchanged are in upstreamCatalog.ts. + * The orchestrator tools J5 declares itself: `delegate_task` takes a persona, + * `orchestrator_capabilities` leaves out upstream's claims about tools J5 does not expose, and + * `t3_thread_interrupt` lets a Captain stop its own seats. The upstream tools J5 registers + * unchanged are in upstreamCatalog.ts. */ export const J5OrchestratorSurface = Toolkit.make( J5DelegateTaskTool, J5OrchestratorCapabilitiesTool, + J5ThreadInterruptTool, ); diff --git a/apps/server/src/j5/a2a/mcp/orchestratorSurfaceHandlers.ts b/apps/server/src/j5/a2a/mcp/orchestratorSurfaceHandlers.ts index 49ece0ac90b03..682057ec1ba8c 100644 --- a/apps/server/src/j5/a2a/mcp/orchestratorSurfaceHandlers.ts +++ b/apps/server/src/j5/a2a/mcp/orchestratorSurfaceHandlers.ts @@ -6,6 +6,7 @@ import * as McpToolAccess from "../../../mcp/McpToolAccess.ts"; import { OrchestratorMcpService } from "../../../mcp/OrchestratorMcpService.ts"; import { actsAsThreadCaller, spawnAndBrief } from "./outsideAgent.ts"; import { J5OrchestratorSurface, mapJ5OrchestratorCapabilities } from "./orchestratorSurface.ts"; +import { threadInterrupt } from "./threadInterrupt.ts"; const handlers = { // A delegated task reports back to the thread that asked for it, and an outside agent has none. @@ -24,6 +25,7 @@ const handlers = { .pipe(Effect.map(mapJ5OrchestratorCapabilities)); }), ), + t3_thread_interrupt: threadInterrupt, } satisfies McpToolAccess.Handlers; export const layer = McpToolAccess.toLayer(J5OrchestratorSurface, handlers); diff --git a/apps/server/src/j5/a2a/mcp/orchestratorVerbs.live.test.ts b/apps/server/src/j5/a2a/mcp/orchestratorVerbs.live.test.ts index 58dd6a176ae51..d11eb2ee0da0e 100644 --- a/apps/server/src/j5/a2a/mcp/orchestratorVerbs.live.test.ts +++ b/apps/server/src/j5/a2a/mcp/orchestratorVerbs.live.test.ts @@ -80,13 +80,7 @@ import { PlacementCommandId } from "../placementContracts.ts"; import { J5A2ARuntimeLayer, J5ThreadRegistrationLayer } from "../runtimeLayer.ts"; import { spawnThreadId } from "../spawnIds.ts"; import { J5ToolkitHandlersLive } from "./handlers.ts"; -import { - type J5SpawnAgentInput, - J5SpawnAgentResult, - type J5StopAgentInput, - J5StopAgentResult, - J5Toolkit, -} from "./tools.ts"; +import { type J5SpawnAgentInput, J5SpawnAgentResult, J5Toolkit } from "./tools.ts"; import { noDocumentTextLayer } from "../../test-support/documentText.ts"; const orchestrationLayer = RuntimeLayer.layer.pipe(Layer.provideMerge(J5ThreadRegistrationLayer)); @@ -113,7 +107,6 @@ const scope: McpInvocationScope = { client: undefined, }; const decodeSpawnResult = Schema.decodeUnknownEffect(J5SpawnAgentResult); -const decodeStopResult = Schema.decodeUnknownEffect(J5StopAgentResult); const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "t3-j5-luna-verb-live-", @@ -334,23 +327,6 @@ const callSpawn = (input: J5SpawnAgentInput) => return yield* decodeSpawnResult(response.result); }); -const callStop = (input: J5StopAgentInput) => - Effect.gen(function* () { - const toolkit = yield* J5Toolkit; - const response = yield* toolkit - .handle("j5_stop_agent", input) - .pipe( - Stream.unwrap, - Stream.run(Sink.last()), - Effect.flatMap(Effect.fromOption), - Effect.provideService(McpInvocationContext, scope), - ); - if (response.isFailure) { - return yield* Effect.die(new Error(`Tool j5_stop_agent failed: ${String(response.result)}`)); - } - return yield* decodeStopResult(response.result); - }); - describe.runIf(process.env.T3_J5_LUNA_LIVE_ORCHESTRATOR === "1")( "J5 orchestrator verbs with Codex Luna", () => { @@ -437,11 +413,13 @@ describe.runIf(process.env.T3_J5_LUNA_LIVE_ORCHESTRATOR === "1")( assert.equal(spawned.project_id, ledgerProjectId); yield* Fiber.join(runningFiber); - const stopped = yield* callStop({ - participant_id: spawned.participant_id, - client_request_id: "j5-luna-verb-e2e-stop", - }); - assert.equal(stopped, "interrupt_requested"); + const stopped = + yield* (yield* OrchestratorMcpService.OrchestratorMcpService).interruptThread(scope, { + threadId: spawned.thread_id, + stop: true, + clientRequestId: "j5-luna-verb-e2e-stop", + }); + assert.equal(stopped.status, "interrupt_requested"); const terminal = yield* Fiber.join(terminalFiber); assert.equal(terminal.status, "interrupted"); diff --git a/apps/server/src/j5/a2a/mcp/outsideAgent.test.ts b/apps/server/src/j5/a2a/mcp/outsideAgent.test.ts index 929b8035f21d6..8a9b2c3465b46 100644 --- a/apps/server/src/j5/a2a/mcp/outsideAgent.test.ts +++ b/apps/server/src/j5/a2a/mcp/outsideAgent.test.ts @@ -15,7 +15,6 @@ import { import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; -import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; @@ -98,13 +97,8 @@ const serverConfigLayer = ServerConfig.layerTest(process.cwd(), { prefix: "j5-mcp-outside-", }).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); -interface Stop { - readonly commandId: string; - readonly threadId: ThreadId; -} - /** The real ledger and send service on an in-memory database; everything else is a stand-in. */ -const makeLayer = (stops: Ref.Ref>) => { +const makeLayer = () => { const database = NodeSqliteClient.layer({ filename: ":memory:" }); const ledger = ledgerLayer.pipe(Layer.provide(database)); const send = sendLayer.pipe( @@ -139,14 +133,6 @@ const makeLayer = (stops: Ref.Ref>) => { : null, ), getThreadRecords: (threadId) => Effect.succeed(idle(threadId)), - dispatch: (command) => - command.type === "thread.stop" - ? Ref.update(stops, (items) => [ - ...items, - { commandId: command.commandId, threadId: command.threadId }, - ]).pipe(Effect.as({ sequence: 1, storedEvents: [] })) - : Effect.die(`unexpected dispatch ${command.type}`), - stopDelegatedTasks: () => Effect.void, }), Layer.mock(OrchestratorV2)({ getShellSnapshot: () => Effect.succeed({ threads: [], archivedThreads: [] } as never), @@ -261,269 +247,227 @@ it.effect( "sends an outside agent's plain message into the receiver's project, capped by its approved level", () => Effect.gen(function* () { - const stops = yield* Ref.make>([]); - yield* Effect.gen(function* () { - yield* setup(); - const sql = yield* SqlClient.SqlClient; - const args = { - to: careful.id, - message: "The deploy is red.", - client_request_id: "deploy-red-1", - }; + yield* setup(); + const sql = yield* SqlClient.SqlClient; + const args = { + to: careful.id, + message: "The deploy is red.", + client_request_id: "deploy-red-1", + }; - const sent = yield* callAs("auto-accept-edits", "j5_send_message", args); - assert.isFalse(sent.isFailure, sent.text); - const replay = yield* callAs("auto-accept-edits", "j5_send_message", args); - assert.deepStrictEqual(replay.encoded, sent.encoded); - const events = yield* sql<{ - readonly project_id: string; - readonly command_id: string; - readonly sender: string; - readonly receiver: string; - }>`SELECT project_id, command_id, sender, receiver + const sent = yield* callAs("auto-accept-edits", "j5_send_message", args); + assert.isFalse(sent.isFailure, sent.text); + const replay = yield* callAs("auto-accept-edits", "j5_send_message", args); + assert.deepStrictEqual(replay.encoded, sent.encoded); + const events = yield* sql<{ + readonly project_id: string; + readonly command_id: string; + readonly sender: string; + readonly receiver: string; + }>`SELECT project_id, command_id, sender, receiver FROM j5_a2a_comm_event WHERE kind = 'message.sent'`; - // One message, in the receiver's project, under the client session's retry namespace. - assert.deepStrictEqual(events, [ - { - project_id: projectId, - command_id: "command:j5:a2a:mcp:client%3Asession-1:send_message:deploy-red-1", - sender: outsideId, - receiver: careful.id, - }, - ]); - assert.deepStrictEqual(yield* sql`SELECT participant_id, name FROM j5_a2a_outside_agent`, [ - { participant_id: outsideId, name: "Claude Code (laptop)" }, - ]); + // One message, in the receiver's project, under the client session's retry namespace. + assert.deepStrictEqual(events, [ + { + project_id: projectId, + command_id: "command:j5:a2a:mcp:client%3Asession-1:send_message:deploy-red-1", + sender: outsideId, + receiver: careful.id, + }, + ]); + assert.deepStrictEqual(yield* sql`SELECT participant_id, name FROM j5_a2a_outside_agent`, [ + { participant_id: outsideId, name: "Claude Code (laptop)" }, + ]); - // A steer is allowed under the same cap and carries the limit to delivery. - const steer = yield* callAs("auto-accept-edits", "j5_send_message", { - to: careful.id, - message: "Stop the rollout now.", - mode: "steer", - }); - assert.isFalse(steer.isFailure, steer.text); - const payloads = yield* sql<{ readonly payload: string }>` + // A steer is allowed under the same cap and carries the limit to delivery. + const steer = yield* callAs("auto-accept-edits", "j5_send_message", { + to: careful.id, + message: "Stop the rollout now.", + mode: "steer", + }); + assert.isFalse(steer.isFailure, steer.text); + const payloads = yield* sql<{ readonly payload: string }>` SELECT payload FROM j5_a2a_comm_event WHERE kind = 'message.sent' ORDER BY seq `; - const steered = yield* decodeSent(payloads[1]?.payload); - assert.equal(steered.mode, "steer"); - assert.deepStrictEqual(steered.modeLimit, { - runtimeMode: "auto-accept-edits", - interactionMode: "default", - }); - assert.isUndefined((yield* decodeSent(payloads[0]?.payload)).modeLimit); + const steered = yield* decodeSent(payloads[1]?.payload); + assert.equal(steered.mode, "steer"); + assert.deepStrictEqual(steered.modeLimit, { + runtimeMode: "auto-accept-edits", + interactionMode: "default", + }); + assert.isUndefined((yield* decodeSent(payloads[0]?.payload)).modeLimit); - // The receiver runs above the approved level: refused, for a plain queued send too. - for (const mode of [undefined, "steer", "restart"] as const) { - const above = yield* callAs("auto-accept-edits", "j5_send_message", { - to: unrestricted.id, - message: "Above my level.", - ...(mode === undefined ? {} : { mode }), - }); - assert.isTrue(above.isFailure); - assert.include(above.text, "broader permissions than this MCP client was approved for"); - } - // A client approved for full access reaches it. - assert.isFalse( - (yield* callAs("full-access", "j5_send_message", { - to: unrestricted.id, - message: "Within my level.", - })).isFailure, - ); + // The receiver runs above the approved level: refused, for a plain queued send too. + for (const mode of [undefined, "steer", "restart"] as const) { + const above = yield* callAs("auto-accept-edits", "j5_send_message", { + to: unrestricted.id, + message: "Above my level.", + ...(mode === undefined ? {} : { mode }), + }); + assert.isTrue(above.isFailure); + assert.include(above.text, "broader permissions than this MCP client was approved for"); + } + // A client approved for full access reaches it. + assert.isFalse( + (yield* callAs("full-access", "j5_send_message", { + to: unrestricted.id, + message: "Within my level.", + })).isFailure, + ); - // A read-only client changes nothing. - const readOnly = yield* callAs("read-only", "j5_send_message", args); - assert.isTrue(readOnly.isFailure); - assert.include(readOnly.text, "read-only access"); + // A read-only client changes nothing. + const readOnly = yield* callAs("read-only", "j5_send_message", args); + assert.isTrue(readOnly.isFailure); + assert.include(readOnly.text, "read-only access"); - assert.lengthOf(yield* sql`SELECT 1 FROM j5_a2a_delivery`, 3); - }).pipe(Effect.provide(makeLayer(stops))); - }), + assert.lengthOf(yield* sql`SELECT 1 FROM j5_a2a_delivery`, 3); + }).pipe(Effect.provide(makeLayer())), ); it.effect("refuses what an outside agent cannot send, naming the legal move", () => Effect.gen(function* () { - const stops = yield* Ref.make>([]); - yield* Effect.gen(function* () { - yield* setup(); - const sql = yield* SqlClient.SqlClient; - const message = "Can you check this?"; + yield* setup(); + const sql = yield* SqlClient.SqlClient; + const message = "Can you check this?"; - // No reply can reach it, so every ask and reply field is refused. - for (const field of [ - { expect_reply: true, intent: "Check the deploy" }, - { exchange_id: "exchange:j5:a2a:some-ask" }, - { intent: "Check the deploy" }, - { urgency: "soon" }, - ]) { - const refused = yield* callAs("full-access", "j5_send_message", { - to: careful.id, - message, - ...field, - }); - assert.isTrue(refused.isFailure); - assert.include(refused.text, "cannot receive a reply"); - assert.include(refused.text, "Retry j5_send_message without them."); - } - - const toPerson = yield* callAs("full-access", "j5_send_message", { to: person, message }); - assert.isTrue(toPerson.isFailure); - assert.include(toPerson.text, "an outside agent cannot ask"); - - const toPeer = yield* callAs("full-access", "j5_send_message", { - to: "agent:j5:a2a:thread:on-a-peer", + // No reply can reach it, so every ask and reply field is refused. + for (const field of [ + { expect_reply: true, intent: "Check the deploy" }, + { exchange_id: "exchange:j5:a2a:some-ask" }, + { intent: "Check the deploy" }, + { urgency: "soon" }, + ]) { + const refused = yield* callAs("full-access", "j5_send_message", { + to: careful.id, message, + ...field, }); - assert.isTrue(toPeer.isFailure); - assert.include(toPeer.text, "sign in to that server's own MCP URL"); + assert.isTrue(refused.isFailure); + assert.include(refused.text, "cannot receive a reply"); + assert.include(refused.text, "Retry j5_send_message without them."); + } - const toOutside = yield* callAs("full-access", "j5_send_message", { - to: "outside:session-2", - message, - }); - assert.isTrue(toOutside.isFailure); - assert.include(toOutside.text, "nothing can be delivered to it"); + const toPerson = yield* callAs("full-access", "j5_send_message", { to: person, message }); + assert.isTrue(toPerson.isFailure); + assert.include(toPerson.text, "an outside agent cannot ask"); - assert.lengthOf(yield* sql`SELECT 1 FROM j5_a2a_delivery`, 0); - }).pipe(Effect.provide(makeLayer(stops))); - }), + const toPeer = yield* callAs("full-access", "j5_send_message", { + to: "agent:j5:a2a:thread:on-a-peer", + message, + }); + assert.isTrue(toPeer.isFailure); + assert.include(toPeer.text, "sign in to that server's own MCP URL"); + + const toOutside = yield* callAs("full-access", "j5_send_message", { + to: "outside:session-2", + message, + }); + assert.isTrue(toOutside.isFailure); + assert.include(toOutside.text, "nothing can be delivered to it"); + + assert.lengthOf(yield* sql`SELECT 1 FROM j5_a2a_delivery`, 0); + }).pipe(Effect.provide(makeLayer())), ); it.effect("lists one project for any outside agent, with no row of its own", () => Effect.gen(function* () { - const stops = yield* Ref.make>([]); - yield* Effect.gen(function* () { - yield* setup(); - // It has sent, so it has a name on record; it is still listed for nobody. - yield* callAs("full-access", "j5_send_message", { to: careful.id, message: "Hello." }); + yield* setup(); + // It has sent, so it has a name on record; it is still listed for nobody. + yield* callAs("full-access", "j5_send_message", { to: careful.id, message: "Hello." }); - const listed = yield* callAs("read-only", "j5_list_participants", { - project_id: projectId, - }); - assert.isFalse(listed.isFailure, listed.text); - const rows = (yield* decodeList(listed.encoded)).participants; - assert.sameMembers( - rows.map((row) => row.participant_id), - [person, careful.id, unrestricted.id], - ); - assert.isTrue(rows.every((row) => !row.self && row.project_id === projectId)); - assert.isTrue(rows.find((row) => row.participant_id === careful.id)?.can_receive_message); - // It sends plain messages only: nobody takes an Exchange or an urgency from it, and a - // person, who takes only asks, takes nothing. - assert.isTrue(rows.every((row) => !row.can_open_exchange && !row.accepts_urgency)); - assert.isFalse(rows.find((row) => row.participant_id === person)?.can_receive_message); - - // A project with no thread yet has no ledger. It lists the people and no agents. - const empty = yield* callAs("read-only", "j5_list_participants", { - project_id: emptyProjectId, - }); - assert.isFalse(empty.isFailure, empty.text); - assert.deepStrictEqual( - (yield* decodeList(empty.encoded)).participants.map((row) => row.participant_id), - [person], - ); - - const noProject = yield* callAs("read-only", "j5_list_participants", {}); - assert.isTrue(noProject.isFailure); - assert.include(noProject.text, "needs a project_id"); - assert.include(noProject.text, "t3_project_list"); - }).pipe(Effect.provide(makeLayer(stops))); - }), -); + const listed = yield* callAs("read-only", "j5_list_participants", { + project_id: projectId, + }); + assert.isFalse(listed.isFailure, listed.text); + const rows = (yield* decodeList(listed.encoded)).participants; + assert.sameMembers( + rows.map((row) => row.participant_id), + [person, careful.id, unrestricted.id], + ); + assert.isTrue(rows.every((row) => !row.self && row.project_id === projectId)); + assert.isTrue(rows.find((row) => row.participant_id === careful.id)?.can_receive_message); + // It sends plain messages only: nobody takes an Exchange or an urgency from it, and a + // person, who takes only asks, takes nothing. + assert.isTrue(rows.every((row) => !row.can_open_exchange && !row.accepts_urgency)); + assert.isFalse(rows.find((row) => row.participant_id === person)?.can_receive_message); -it.effect("stops an agent for an outside agent only within its approved level", () => - Effect.gen(function* () { - const stops = yield* Ref.make>([]); - yield* Effect.gen(function* () { - yield* setup(); - // The target is in another project than any the client has named: a stop reaches the server. - const args = { participant_id: elsewhere.id, client_request_id: "stop-1" }; - const stopped = yield* callAs("approval-required", "j5_stop_agent", args); - assert.equal(stopped.result, "already_idle", stopped.text); - yield* callAs("approval-required", "j5_stop_agent", args); - const dispatched = yield* Ref.get(stops); - assert.deepStrictEqual( - dispatched.map((stop) => stop.threadId), - [elsewhere.threadId, elsewhere.threadId], - ); - // A retry reuses the command, which is namespaced by the client session. - assert.equal(dispatched[0]?.commandId, dispatched[1]?.commandId); - assert.include(dispatched[0]?.commandId, "client%3Asession-1"); + // A project with no thread yet has no ledger. It lists the people and no agents. + const empty = yield* callAs("read-only", "j5_list_participants", { + project_id: emptyProjectId, + }); + assert.isFalse(empty.isFailure, empty.text); + assert.deepStrictEqual( + (yield* decodeList(empty.encoded)).participants.map((row) => row.participant_id), + [person], + ); - const above = yield* callAs("auto", "j5_stop_agent", { participant_id: unrestricted.id }); - assert.isTrue(above.isFailure); - assert.include(above.text, "broader permissions than you do"); - const readOnly = yield* callAs("read-only", "j5_stop_agent", args); - assert.isTrue(readOnly.isFailure); - assert.include(readOnly.text, "read-only access"); - assert.lengthOf(yield* Ref.get(stops), 2, "a refused stop dispatches nothing"); - }).pipe(Effect.provide(makeLayer(stops))); - }), + const noProject = yield* callAs("read-only", "j5_list_participants", {}); + assert.isTrue(noProject.isFailure); + assert.include(noProject.text, "needs a project_id"); + assert.include(noProject.text, "t3_project_list"); + }).pipe(Effect.provide(makeLayer())), ); it.effect("keeps thread-only tools refused for an outside agent, naming what it can do", () => Effect.gen(function* () { - const stops = yield* Ref.make>([]); - yield* Effect.gen(function* () { - const workspace = { type: "shared" } as const; - const refusals = [ - [ - "j5_propose_crew", - { - name: "Deploy crew", - brief: "Fix the deploy.", - seats: [{ seat: "builder", reason: "Builds", instructions: "Build.", workspace }], - }, - "j5_spawn_agent and brief it to propose the Crew", - ], - [ - "j5_request_crew_member", - { seat: "reviewer", reason: "Reviews", instructions: "Review.", workspace }, - "j5_spawn_agent and brief it to", - ], - ["j5_stop_crew", { crew_instance_id: "crew:1" }, "Only a Crew's Captain stops it"], - ["j5_archive_crew", { crew_instance_id: "crew:1" }, "Only a Crew's Captain archives it"], - [ - "j5_clear_own_ask", - { exchange_id: "exchange:j5:a2a:some-ask", client_request_id: "clear-1" }, - "has no ask to withdraw", - ], - // Saving a persona is the Owner's, on an ask only a thread agent can send. - [ - "j5_propose_persona", - { mode: "edit", persona_id: "reviewer", expected_digest: "0".repeat(64) }, - "cannot ask the person", - ], - [ - "j5_playbook_next", - { runId: "run:1", client_request_id: "next-1", expectedStepId: "step-1" }, - "j5_spawn_agent and brief it to run the playbook", - ], - [ - "j5_playbook_start", - { name: "release", client_request_id: "start-1" }, - "j5_spawn_agent and brief it to run the playbook", - ], - ] as const; - for (const [name, args, legalMove] of refusals) { - const refused = yield* callAs("full-access", name, args); - assert.isTrue(refused.isFailure, name); - assert.include(refused.text, "signed in from outside a thread", name); - assert.include(refused.text, legalMove, name); - // A read-only client is refused as one before anything else. - assert.include((yield* callAs("read-only", name, args)).text, "read-only access", name); - } - // The reads that need a calling thread name the legal move at every level, read-only too. - for (const [name, args] of [ - ["j5_playbook_list", {}], - ["j5_playbook_read", { name: "release" }], - ["j5_playbook_current", {}], - ] as const) { - const refused = yield* callAs("read-only", name, args); - assert.isTrue(refused.isFailure, name); - assert.include(refused.text, "signed in from outside a thread", name); - assert.include(refused.text, "j5_spawn_agent and brief it to read or run", name); - } - }).pipe(Effect.provide(makeLayer(stops))); - }), + const workspace = { type: "shared" } as const; + const refusals = [ + [ + "j5_propose_crew", + { + name: "Deploy crew", + brief: "Fix the deploy.", + seats: [{ seat: "builder", reason: "Builds", instructions: "Build.", workspace }], + }, + "j5_spawn_agent and brief it to propose the Crew", + ], + [ + "j5_request_crew_member", + { seat: "reviewer", reason: "Reviews", instructions: "Review.", workspace }, + "j5_spawn_agent and brief it to", + ], + ["j5_stop_crew", { crew_instance_id: "crew:1" }, "Only a Crew's Captain stops it"], + ["j5_archive_crew", { crew_instance_id: "crew:1" }, "Only a Crew's Captain archives it"], + [ + "j5_clear_own_ask", + { exchange_id: "exchange:j5:a2a:some-ask", client_request_id: "clear-1" }, + "has no ask to withdraw", + ], + // Saving a persona is the Owner's, on an ask only a thread agent can send. + [ + "j5_propose_persona", + { mode: "edit", persona_id: "reviewer", expected_digest: "0".repeat(64) }, + "cannot ask the person", + ], + [ + "j5_playbook_next", + { runId: "run:1", client_request_id: "next-1", expectedStepId: "step-1" }, + "j5_spawn_agent and brief it to run the playbook", + ], + [ + "j5_playbook_start", + { name: "release", client_request_id: "start-1" }, + "j5_spawn_agent and brief it to run the playbook", + ], + ] as const; + for (const [name, args, legalMove] of refusals) { + const refused = yield* callAs("full-access", name, args); + assert.isTrue(refused.isFailure, name); + assert.include(refused.text, "signed in from outside a thread", name); + assert.include(refused.text, legalMove, name); + // A read-only client is refused as one before anything else. + assert.include((yield* callAs("read-only", name, args)).text, "read-only access", name); + } + // The reads that need a calling thread name the legal move at every level, read-only too. + for (const [name, args] of [ + ["j5_playbook_list", {}], + ["j5_playbook_read", { name: "release" }], + ["j5_playbook_current", {}], + ] as const) { + const refused = yield* callAs("read-only", name, args); + assert.isTrue(refused.isFailure, name); + assert.include(refused.text, "signed in from outside a thread", name); + assert.include(refused.text, "j5_spawn_agent and brief it to read or run", name); + } + }).pipe(Effect.provide(makeLayer())), ); diff --git a/apps/server/src/j5/a2a/mcp/registration.test.ts b/apps/server/src/j5/a2a/mcp/registration.test.ts index 146d50dc81ca0..44db1fada9829 100644 --- a/apps/server/src/j5/a2a/mcp/registration.test.ts +++ b/apps/server/src/j5/a2a/mcp/registration.test.ts @@ -321,7 +321,6 @@ it.effect("production mcp layer lists worktree tools over http", () => "j5_request_crew_member", "j5_send_message", "j5_spawn_agent", - "j5_stop_agent", "j5_stop_crew", "j5_write_artifact", "link_pull_request", @@ -455,7 +454,7 @@ it.effect("production mcp layer lists worktree tools over http", () => // J5's tools were renamed with a `j5_` prefix and kept no aliases. An agent resumed from // before the rename may still call an old name; it gets the unknown-tool error by name. const j5ToolNames = toolNames.filter((name) => name.startsWith("j5_")); - expect(j5ToolNames).toHaveLength(25); + expect(j5ToolNames).toHaveLength(24); for (const [index, name] of j5ToolNames.map((name) => name.slice("j5_".length)).entries()) { expect(toolNames).not.toContain(name); const response = yield* httpClient.post("/mcp", { diff --git a/apps/server/src/j5/a2a/mcp/threadInterrupt.ts b/apps/server/src/j5/a2a/mcp/threadInterrupt.ts new file mode 100644 index 0000000000000..c2f3296dfb6e6 --- /dev/null +++ b/apps/server/src/j5/a2a/mcp/threadInterrupt.ts @@ -0,0 +1,136 @@ +import { + OrchestratorMcpFailure, + type OrchestratorMcpThreadInterruptInput, + type OrchestratorMcpThreadInterruptResult, +} from "@t3tools/contracts"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Effect from "effect/Effect"; + +import { McpInvocationContext, requireThreadScope } from "../../../mcp/McpInvocationContext.ts"; +import * as McpToolAccess from "../../../mcp/McpToolAccess.ts"; +import { OrchestratorMcpService } from "../../../mcp/OrchestratorMcpService.ts"; +import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts"; +import { AgentCrewInstanceService } from "../AgentCrewInstanceService.ts"; +import { participantIdForThread } from "../HomeRegistrar.ts"; +import { lifecycleCommandId } from "../spawnIds.ts"; +import { agentStopReason, stopThread } from "../stopThread.ts"; + +/** Whether the calling thread is the Captain of the live Crew seat the target thread holds. */ +const callerIsTargetsCaptain = Effect.fn("j5.mcp.callerIsTargetsCaptain")( + function* (input: OrchestratorMcpThreadInterruptInput) { + const scope = yield* McpInvocationContext; + if (scope.thread === undefined) return false; + const crews = yield* AgentCrewInstanceService; + const seat = yield* crews.findMembership(participantIdForThread(input.threadId)); + const crew = seat === null ? null : yield* crews.read(seat.crewInstanceId); + return crew?.captainParticipantId === participantIdForThread(scope.thread.threadId); + }, + Effect.mapError( + (error) => + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: `The Crews cannot be read to check who commands this thread: ${error.message}`, + }), + ), +); + +/** Upstream's interrupt with no mode check: a Captain commands its own seats whatever their modes. */ +const captainInterrupt = Effect.fn("j5.mcp.captainInterrupt")(function* ( + input: OrchestratorMcpThreadInterruptInput, +) { + const scope = yield* requireThreadScope(yield* McpInvocationContext, "t3_thread_interrupt"); + const threads = yield* ThreadManagementService; + const requestKey = + input.clientRequestId ?? + (yield* SecureRandom.SecureRandom.pipe( + Effect.flatMap((crypto) => crypto.uuidV4()), + Effect.orDie, + )); + const commandId = (operation: string) => + lifecycleCommandId({ + providerSessionId: scope.thread.providerSessionId, + requestKey, + operation, + }); + const failed = (error: { readonly message: string }) => + new OrchestratorMcpFailure({ + code: "orchestration_error", + message: `Unable to stop thread ${input.threadId}: ${error.message}`, + }); + const reason = agentStopReason(input.reason); + if (input.stop === true) { + const stopCommandId = commandId("thread-stop"); + const stopped = yield* stopThread(threads, { + commandId: stopCommandId, + threadId: input.threadId, + reason, + }).pipe(Effect.mapError(failed)); + // As upstream does: thread.stop queues this only for delegates with a thread here, and a + // retry with the same clientRequestId repeats only the stops that failed. + yield* threads + .stopDelegatedTasks({ threadId: input.threadId, commandId: stopCommandId, reason }) + .pipe(Effect.mapError(failed)); + // As upstream reads it: the run this Stop interrupted, from its own events. + const interrupted = stopped.storedEvents.find( + ({ event }) => + (event.type === "run.updated" && event.payload.status === "interrupted") || + (event.type === "turn-item.updated" && + event.payload.type === "run_interrupt_request" && + event.payload.providerTurnId !== null), + )?.event.runId; + return { + threadId: input.threadId, + runId: interrupted ?? null, + status: interrupted === undefined ? "no_active_run" : "interrupt_requested", + } satisfies OrchestratorMcpThreadInterruptResult; + } + const shell = yield* threads.getThreadShell(input.threadId).pipe(Effect.mapError(failed)); + if (shell === null) { + return yield* new OrchestratorMcpFailure({ + code: "thread_not_found", + message: `Thread ${input.threadId} was not found.`, + }); + } + const result = yield* threads + .interruptThread({ + projectId: shell.projectId, + commandId: commandId("thread-interrupt"), + threadId: input.threadId, + ...(input.runId === undefined ? {} : { runId: input.runId }), + reason, + }) + .pipe(Effect.mapError(failed)); + return { + threadId: input.threadId, + runId: result.type === "no_active_run" ? null : result.run.id, + status: + result.type === "no_active_run" + ? "no_active_run" + : result.type === "already_terminal" + ? result.run.status + : "interrupt_requested", + } satisfies OrchestratorMcpThreadInterruptResult; +}); + +/** + * Upstream's `t3_thread_interrupt` with J5's one rule (register D2): a Captain stopping a seat of + * its own Crew skips upstream's check that the target runs within the caller's modes. Every other + * caller gets upstream's declaration and handler. + */ +export const threadInterrupt = McpToolAccess.eitherBy( + callerIsTargetsCaptain, + McpToolAccess.actsAsCaller(captainInterrupt), + McpToolAccess.writesThreads( + (input: OrchestratorMcpThreadInterruptInput) => [input.threadId], + (input) => + Effect.gen(function* () { + const scope = yield* McpInvocationContext; + const service = yield* OrchestratorMcpService; + // Upstream's Stop passes the reason as given, so without one it reads as the user's. + return yield* service.interruptThread( + scope, + input.stop === true ? { ...input, reason: agentStopReason(input.reason) } : input, + ); + }), + ), +); diff --git a/apps/server/src/j5/a2a/mcp/tools.test.ts b/apps/server/src/j5/a2a/mcp/tools.test.ts index 115556d8b835c..542e8fbf738fd 100644 --- a/apps/server/src/j5/a2a/mcp/tools.test.ts +++ b/apps/server/src/j5/a2a/mcp/tools.test.ts @@ -29,12 +29,10 @@ import { J5SendMessageTool, J5SpawnAgentInput, J5SpawnAgentTool, - J5StopAgentTool, J5Toolkit, J5_PROPOSE_CREW_DESCRIPTION, J5_REQUEST_CREW_MEMBER_DESCRIPTION, J5_SPAWN_AGENT_DESCRIPTION, - J5_STOP_AGENT_DESCRIPTION, } from "./tools.ts"; const decodeProposeCrew = Schema.decodeUnknownSync(J5ProposeCrewInput); @@ -77,7 +75,6 @@ it("publishes the ratified single-target lifecycle contracts fail-closed", () => "To the human, only an ask: a plain send to a person is refused", ); assert.equal(J5SpawnAgentTool.description, J5_SPAWN_AGENT_DESCRIPTION); - assert.equal(J5StopAgentTool.description, J5_STOP_AGENT_DESCRIPTION); const sp4BriefSteering = "In your brief, tell the new agent what it should do first and whether it should reply to you."; assert.equal(J5SpawnAgentTool.description?.split(sp4BriefSteering).length, 2); @@ -88,18 +85,12 @@ it("publishes the ratified single-target lifecycle contracts fail-closed", () => readonly required?: ReadonlyArray; readonly properties?: Readonly>; }; - const stopSchema = Tool.getJsonSchema(J5StopAgentTool) as { - readonly required?: ReadonlyArray; - readonly properties?: Readonly>; - }; assert.sameMembers([...(spawnSchema.required ?? [])], ["brief", "title", "workspace"]); - assert.sameMembers([...(stopSchema.required ?? [])], ["participant_id"]); assert.property(spawnSchema.properties ?? {}, "client_request_id"); assert.property(spawnSchema.properties ?? {}, "persona"); // No pre-dogfood compatibility spelling: `persona` is the only name the model sees. assert.notProperty(spawnSchema.properties ?? {}, "agent"); assert.include(J5SpawnAgentTool.description ?? "", "set them only to pin one of those entries"); - assert.property(stopSchema.properties ?? {}, "client_request_id"); // Exact on purpose: no tool answers the Inbox's worktree cleanup approval; only a person can. assert.sameMembers(Object.keys(J5Toolkit.tools), [ "j5_playbook_back", @@ -120,7 +111,6 @@ it("publishes the ratified single-target lifecycle contracts fail-closed", () => "j5_propose_crew", "j5_request_crew_member", "j5_spawn_agent", - "j5_stop_agent", "j5_stop_crew", "j5_archive_crew", "j5_clear_own_ask", @@ -144,10 +134,10 @@ it("publishes the ratified single-target lifecycle contracts fail-closed", () => "mcp__t3-code__delegate_task", "mcp__t3-code__task_status", "mcp__t3-code__task_cancel", + "mcp__t3-code__t3_thread_interrupt", ], ); assert.isFalse(Context.get(J5SpawnAgentTool.annotations, Tool.Idempotent)); - assert.isFalse(Context.get(J5StopAgentTool.annotations, Tool.Idempotent)); }); // These are provider-facing safety hints, independent of J5's pre-approval list. This diff --git a/apps/server/src/j5/a2a/mcp/tools.ts b/apps/server/src/j5/a2a/mcp/tools.ts index f509363c6fc6d..1c96ff907b45c 100644 --- a/apps/server/src/j5/a2a/mcp/tools.ts +++ b/apps/server/src/j5/a2a/mcp/tools.ts @@ -596,14 +596,6 @@ export const J5CrewProposalResult = Schema.Struct({ ), }); -export const J5StopAgentInput = Schema.Struct({ - client_request_id: Schema.optional(NonEmptyString), - participant_id: ParticipantId, -}); -export type J5StopAgentInput = typeof J5StopAgentInput.Type; - -export const J5StopAgentResult = Schema.Literals(["interrupt_requested", "already_idle"]); - export const J5StopCrewInput = Schema.Struct({ client_request_id: Schema.optional(NonEmptyString), crew_instance_id: NonEmptyString, @@ -722,9 +714,6 @@ export const J5_REQUEST_CREW_MEMBER_DESCRIPTION = BLOCKED_PERSONA_TOOL_TEXT + " A persona marked independent_reviewer prefers a model none of the members it reviews runs on: every member that is not a reviewer, unless reviews names some. 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. To put a member's work on a different model, such as a reviewer whose model just wrote the work it will review, set replaces to that member's seat: the new member may reuse the seat name, and once it launches it takes over the seat's unfinished steps, gets any current step already handed to the old member, and is told where the old member's thread is. The replaced member is stopped and leaves the Crew, and its thread stays readable. If the new member fails to launch, nothing changes, except that an allow_once it used is spent. 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."; - const J5_ARCHIVE_CREW_DESCRIPTION = "Retire a whole Crew you command. Crews archive only as a unit; members are never retired one by one. A clean archive completes immediately; otherwise the call refuses with the facts and a confirmation_token. Before retrying with that token, check with the user. Archiving removes the worktrees J5 created for the Crew's seats when they are clean, committed, merged, used by no other thread or project, and have no open session or terminal, and keeps every branch and pull request. Anything else stays and is listed in the result's worktrees with its reason: uncommitted_changes, unmerged_commits, shared, in_use, unverified (a check could not run), or failed (the removal itself failed). Worktrees from before this existed, the Captain's checkout, and existing worktrees a seat was pointed at are never removed. Ledgers stay readable. Reuse client_request_id to retry safely."; @@ -818,15 +807,6 @@ const proposePersonaDependencies = [ AgentPersonaDrafts, ]; -const stopDependencies = [ - McpInvocationContext.McpInvocationContext, - A2ASendService, - SecureRandom.SecureRandom, - ThreadManagementService, - // A Captain stops its own seats whatever their permission modes. - AgentCrewInstanceService, -]; - const stopCrewDependencies = [ McpInvocationContext.McpInvocationContext, ThreadManagementService, @@ -956,20 +936,6 @@ const J5ProposePersonaTool = Tool.make("j5_propose_persona", { .annotate(Tool.Idempotent, false) .annotate(Tool.OpenWorld, false); -export const J5StopAgentTool = Tool.make("j5_stop_agent", { - description: J5_STOP_AGENT_DESCRIPTION, - parameters: J5StopAgentInput, - success: J5StopAgentResult, - failure: J5McpFailure, - failureMode: "return", - dependencies: stopDependencies, -}) - .annotate(Tool.Title, "Stop one Peer Agent") - .annotate(Tool.Readonly, false) - .annotate(Tool.Destructive, true) - .annotate(Tool.Idempotent, false) - .annotate(Tool.OpenWorld, false); - const J5StopCrewTool = Tool.make("j5_stop_crew", { description: J5_STOP_CREW_DESCRIPTION, parameters: J5StopCrewInput, @@ -1028,7 +994,6 @@ export const J5Toolkit = Toolkit.make( J5ProposePersonaTool, J5ProposeCrewTool, J5RequestCrewMemberTool, - J5StopAgentTool, J5StopCrewTool, J5ArchiveCrewTool, J5ClearOwnAskTool, diff --git a/apps/server/src/j5/a2a/mcp/upstreamCatalog.ts b/apps/server/src/j5/a2a/mcp/upstreamCatalog.ts index bc368a1ed6db2..b044f8b9a3d78 100644 --- a/apps/server/src/j5/a2a/mcp/upstreamCatalog.ts +++ b/apps/server/src/j5/a2a/mcp/upstreamCatalog.ts @@ -63,7 +63,8 @@ export const J5ProjectToolkit = Toolkit.make( // Raw send and bulk-create stay out: `j5_send_message` and `j5_spawn_agent` are their doors // (register D2). Waiting, interrupting and links are upstream's (D42). -// `orchestrator_capabilities` and `delegate_task` are J5's (orchestratorSurface.ts). +// `orchestrator_capabilities`, `delegate_task` and `t3_thread_interrupt` are J5's +// (orchestratorSurface.ts). export const J5OrchestratorToolkit = Toolkit.make( OrchestratorToolkit.tools.task_status, OrchestratorToolkit.tools.task_cancel, @@ -83,7 +84,6 @@ export const J5OrchestratorToolkit = Toolkit.make( OrchestratorToolkit.tools.t3_thread_wait .annotate(Tool.Destructive, false) .annotate(Tool.OpenWorld, false), - OrchestratorToolkit.tools.t3_thread_interrupt, OrchestratorToolkit.tools.t3_environment_links .annotate(Tool.Destructive, false) .annotate(Tool.OpenWorld, false), diff --git a/apps/server/src/j5/a2a/stopThread.ts b/apps/server/src/j5/a2a/stopThread.ts index ed235ad11b085..34e7014c768b6 100644 --- a/apps/server/src/j5/a2a/stopThread.ts +++ b/apps/server/src/j5/a2a/stopThread.ts @@ -11,11 +11,15 @@ import type { ThreadManagementService } from "../../orchestration-v2/ThreadManag */ export const AGENT_STOP_REASON = "Stopped by an agent"; +/** An agent's own reason, worded as upstream's MCP interrupt words it. */ +export const agentStopReason = (reason: string | undefined) => + reason === undefined ? AGENT_STOP_REASON : `${AGENT_STOP_REASON}: ${reason}`; + /** * Upstream's Stop for one thread, as its own senders issue it: `thread.stop` interrupts the * running turn, holds the queue, ends pull request watches, and stops the thread's delegated * tasks. Nothing to stop is an accepted no-op, and a retry with the same `commandId` repeats - * nothing. `j5_stop_agent`, Crew stop and Crew retirement all stop a thread this way. + * nothing. A Captain's `t3_thread_interrupt`, Crew stop and Crew retirement stop a thread this way. */ export const stopThread = ( threads: Pick, diff --git a/apps/server/src/mcp/McpToolAccess.ts b/apps/server/src/mcp/McpToolAccess.ts index dc8de339dac5f..ce5a4fbd5c62d 100644 --- a/apps/server/src/mcp/McpToolAccess.ts +++ b/apps/server/src/mcp/McpToolAccess.ts @@ -286,6 +286,21 @@ export const either = ( ); }; +// J5 (FORK.md case 2): `either` picked by reading state, such as whether the caller is the +// target's Captain. A call bound for a linked environment takes the second's check. +export const eitherBy = ( + useFirst: (params: P) => Effect.Effect, + first: Declaration<(params: P) => Effect.Effect>, + second: Declaration<(params: P) => Effect.Effect>, +) => + declare( + (params: P): Effect.Effect => + Effect.flatMap(useFirst(params), (yes): Effect.Effect => + yes ? checkedHandler(first)(params) : checkedHandler(second)(params), + ), + remoteCheckOf(second) as RemoteCheck

| undefined, + ); + const fullAccessRequired = "Changing projects or environment settings needs a live full-access/default calling thread or a full-access client."; diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index a8b9642f51946..e7b37d67bd5b2 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 19412, "codexAdditionalContextBytes": 21132, - "mcpToolListJsonBytes": 91673 + "mcpToolListJsonBytes": 90901 } diff --git a/docs/j5/product/upstream-convergence.md b/docs/j5/product/upstream-convergence.md index f3cc0c2b32aed..8e6d6c323e98f 100644 --- a/docs/j5/product/upstream-convergence.md +++ b/docs/j5/product/upstream-convergence.md @@ -13,7 +13,7 @@ Checked against `pingdotgg/t3code` stable `v0.1.7` @ `322f6544df` (1,466 commits - **Upstream:** the orchestrator MCP toolkit can send into another thread, wait on it, interrupt it and launch threads (`t3_thread_send`, `t3_thread_wait`, `t3_thread_interrupt`, `t3_thread_launch`, `create_threads`), answer another thread's questions (`t3_pending_request`) and reconfigure it (`t3_thread_configure`). Every tool declares who may call it. An agent outside the app can sign in with OAuth. Messages from agents carry `senderThreadId`, fold into one-line rows, and show their sender while queued too. A delegated child's question wakes its parent, steering into the running turn when the provider can steer without interrupting tools and otherwise queueing. A person can answer a delegated child's approvals from the parent thread on web, desktop and mobile; a child's questions no longer flag the parent. `t3_pending_request` still cannot approve a permission request; the change that let it was reverted and has not returned. - **Linked environments** (new, a Labs beta, off by default, on each machine): two servers link over any route that reaches them, and an agent then names another machine's `environmentId` on thread, project and queue tools, or delegates there. Work a link starts is fenced to that link below full access. `t3_thread_launch` takes `clientRequestId` so a retry is safe. Agents can propose a link with a card, and `@` mentions a machine. Tool calls over a link need a direct connection, and upstream plans no poll mode. Import, handoff and "Continue on…" are [still open](https://github.com/pingdotgg/t3code/pull/16731). -- **J5:** a ledger for each project, addressable participants, Exchanges, Inbox and delivery receipts. J5 follows upstream's access model and outside-agent sign-in ([divergence D2](upstream.md)). It hides upstream's send and bulk-create tools, admits wait and interrupt (giving interrupt J5's Captain rule and retiring `j5_stop_agent` for it are still to come), admits upstream's link tools as shipped, and admits launch only for link sessions, so a delegate another machine sends here can run, held to this machine's models for custom members ([divergence D42](upstream.md)). An agent in a side chat is refused J5 messaging, as a subagent is. A Crew seat asks its Captain. Native questions on J5-spawned Peer Agents or live seats notify their placement parent by queueing, and reach the Inbox as links; delegated children keep upstream's reactor and its approval roll-up. Pending-request answers follow upstream's checks. J5 peering stays the ledger's path between servers and sits beside linked environments in Settings → Connections. Peering polls for messages, which are not expected to answer at once, so a sleeping or firewalled machine still gets them later; tool calls are expected to answer at once and use the link's direct connection, so starting new work on a sleeping or firewalled machine fails visibly. +- **J5:** a ledger for each project, addressable participants, Exchanges, Inbox and delivery receipts. J5 follows upstream's access model and outside-agent sign-in ([divergence D2](upstream.md)). It hides upstream's send and bulk-create tools, admits wait, gives interrupt J5's Captain rule in place of `j5_stop_agent`, admits upstream's link tools as shipped, and admits launch only for link sessions, so a delegate another machine sends here can run, held to this machine's models for custom members ([divergence D42](upstream.md)). An agent in a side chat is refused J5 messaging, as a subagent is. A Crew seat asks its Captain. Native questions on J5-spawned Peer Agents or live seats notify their placement parent by queueing, and reach the Inbox as links; delegated children keep upstream's reactor and its approval roll-up. Pending-request answers follow upstream's checks. J5 peering stays the ledger's path between servers and sits beside linked environments in Settings → Connections. Peering polls for messages, which are not expected to answer at once, so a sleeping or firewalled machine still gets them later; tool calls are expected to answer at once and use the link's direct connection, so starting new work on a sleeping or firewalled machine fails visibly. - **Watch for:** reply or ask semantics, an inbox, or responder attribution upstream. Child question or approval routing extended to threads an agent started that aren't delegated children; J5's Crew-seat question rule and Exchanges could then sit on top of it. An outside client that can _receive_ messages. Approval answering by agents returning. Upstream's [handoff layers](https://github.com/pingdotgg/t3code/pull/16751) landing, which would overlap J5's delivery across servers and is the moment to reconsider peering. A poll mode for links, which would change where peering and links split. Delivery so far is idempotent launches and retried notices, not receipts; receipts would be the signal to rethink. ## Launch, workspaces and parallel agents diff --git a/docs/j5/runbooks/agent-migration.md b/docs/j5/runbooks/agent-migration.md index 334321fd0d544..7ea20f99cc048 100644 --- a/docs/j5/runbooks/agent-migration.md +++ b/docs/j5/runbooks/agent-migration.md @@ -142,7 +142,7 @@ prefix, and **outbound A2A** appears as `tool_use` blocks for `mcp__traycer_a2a_ - **None of that pre-transplant history renders in the J5 timeline** — it is model context only, per the honest line. The agent _remembers_ its A2A exchanges; J5 does not _display_ them. - **The history references tools that do not exist in J5's toolset.** J5 exposes `j5_send_message`, - `j5_list_participants`, `j5_spawn_agent`, `j5_stop_agent`, `j5_clear_own_ask` — not the + `j5_list_participants`, `j5_spawn_agent`, `t3_thread_interrupt`, `j5_clear_own_ask` — not the `mcp__traycer_a2a__*` or `traycer_*` tools the transcript is full of. **Resuming a session whose history contains those dead tool_use blocks works with no API error** — proven in the Stage-1 live run (the resumed session was dense with `mcp__traycer_a2a__traycer_send_message` blocks and @@ -161,7 +161,8 @@ before any real work, so the agent re-maps its tools before it acts. Template: > `traycer_create_agent`, `traycer_get_transcript`, every `mcp__traycer_a2a__*`) **no longer > exist**. Your A2A surface is now: `j5_list_participants` (your address book — call it first), > `j5_send_message` (plain send / ask with `expect_reply` / reply with `exchange_id`), `j5_spawn_agent`, -> `j5_stop_agent`, `j5_clear_own_ask`. Do not call any `traycer_*` tool. +> `t3_thread_interrupt` (with `stop: true` to stop an agent), `j5_clear_own_ask`. Do not call any +> `traycer_*` tool. > 3. **The human is reached through the inbox** — `j5_send_message` to the human participant (with > `urgency` when it is an ask), not a Traycer channel. **Until issue #44 lands, a message a person > must SEE is an ask (`expect_reply` + `urgency`); a plain message to a person is ledger-only and