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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions FORK.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion apps/server/src/j5/a2a/CrewStopService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/j5/a2a/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
213 changes: 1 addition & 212 deletions apps/server/src/j5/a2a/mcp/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import {
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
type OrchestrationV2Run,
type OrchestrationV2ServerCommand,
type OrchestrationV2ThreadProjection,
type ServerProvider,
Expand All @@ -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,
Expand Down Expand Up @@ -107,7 +105,6 @@ import {
type J5ProposeCrewInput,
type J5RequestCrewMemberInput,
type J5SpawnAgentInput,
type J5StopAgentInput,
} from "./tools.ts";
import { noDocumentTextLayer } from "../../test-support/documentText.ts";

Expand Down Expand Up @@ -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<ReadonlyArray<SendMessageInput>>([]);
Expand Down Expand Up @@ -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<RuntimeMode>("full-access");
const targetIsCallersSeat = yield* Ref.make(false);
const stopLimits = yield* Ref.make<ReadonlyArray<RuntimeMode | undefined>>([]);
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",
() =>
Expand Down
Loading
Loading