The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 18:30 UTC
fix(acp): let agents that advertise /compact compact their own context (#28822)
Co-authored-by: ParasN <25337333+ParasN@users.noreply.github.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
ParasN committed
Nov 13, 2026 at 04:14 UTC
ac7c7f66d985948d547b30ddd482957ae6343cc6
4 files changed
+236
-10
apps/server/scripts/acp-mock-agent.ts
+27
@@ -23,6 +23,12 @@ const copilotModesProfile = process.env.T3_ACP_COPILOT_MODES === "1";
23
const copilotModeId = (name: string) =>
24
`https://agentclientprotocol.com/protocol/session-modes#${name}`;
25
const modeOptionCategory = process.env.T3_ACP_MODE_OPTION_CATEGORY ?? "mode";
26
+// Comma-separated command names the mock advertises, so `/compact` support is testable.
27
+const advertisedCommandNames = (process.env.T3_ACP_AVAILABLE_COMMANDS ?? "")
28
+ .split(",")
29
+ .map((name) => name.trim())
30
+ .filter((name) => name.length > 0);
31
+const loadedCommandNames = process.env.T3_ACP_LOADED_COMMANDS?.split(",").filter(Boolean);
32
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
33
const emitInterleavedAssistantToolCalls =
34
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
@@ -610,6 +616,18 @@ const program = Effect.gen(function* () {
616
if (antigravityProfile) {
617
yield* publishAntigravityCommands(sessionId);
618
}
619
+ if (advertisedCommandNames.length > 0) {
620
+ yield* agent.client.sessionUpdate({
621
+ sessionId,
622
+ update: {
623
+ sessionUpdate: "available_commands_update",
624
+ availableCommands: advertisedCommandNames.map((name) => ({
625
+ name,
626
+ description: `${name} command`,
627
+ })),
628
+ },
629
+ });
630
+ }
631
return {
632
sessionId,
633
configOptions: configOptions(),
@@ -665,6 +683,15 @@ const program = Effect.gen(function* () {
683
yield* agent.handleLoadSession((request) =>
684
Effect.gen(function* () {
685
const requestedSessionId = String(request.sessionId ?? sessionId);
686
+ if (loadedCommandNames !== undefined) {
687
+ yield* agent.client.sessionUpdate({
688
+ sessionId: requestedSessionId,
689
+ update: {
690
+ sessionUpdate: "available_commands_update",
691
+ availableCommands: loadedCommandNames.map((name) => ({ name, description: name })),
692
+ },
693
+ });
694
+ }
695
if (failLoadSession) {
696
return yield* AcpError.AcpRequestError.internalError("Mock load session failure");
697
}
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+162
@@ -816,6 +816,94 @@ function assertReinjectedInstructions(
816
assert.include(text, `<user_request>\n${request}\n</user_request>`);
817
}
818
819
+const makeAdvertisedCompactionHarness = Effect.fnUntraced(function* (
820
+ environment: Readonly<Record<string, string>>,
821
+) {
822
+ const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
823
+ const path = yield* Path.Path;
824
+ const selfInvocation = yield* resolveSelfInvocation();
825
+ const mockAgentPath = yield* path.fromFileUrl(
826
+ new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
827
+ );
828
+ const protocolEvents = yield* Queue.unbounded<EffectAcpProtocol.AcpProtocolLogEvent>();
829
+ // Resolves after the adapter records what the agent advertised, so the refusal is deterministic.
830
+ const commandsPublished = yield* Deferred.make<void>();
831
+ const instanceId = ProviderInstanceId.make("acp-test-advertised-compaction");
832
+ const threadId = ThreadId.make("thread-acp-advertised-compaction");
833
+ const adapter = yield* makeAcpAdapterV2({
834
+ instanceId,
835
+ flavor: {
836
+ driver: ACP_TEST_DRIVER,
837
+ capabilities: AcpProviderCapabilitiesV2,
838
+ compactViaAdvertisedCommand: true,
839
+ onAvailableCommandsUpdate: () => Deferred.succeed(commandsPublished, undefined),
840
+ makeRuntime: makeMockRuntime({
841
+ childProcessSpawner,
842
+ mockAgentPath,
843
+ protocolEvents,
844
+ environment,
845
+ }),
846
+ },
847
+ selfInvocation,
848
+ });
849
+ const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
850
+ runtimeMode: "full-access",
851
+ interactionMode: "default",
852
+ cwd: process.cwd(),
853
+ });
854
+ const modelSelection = { instanceId, model: "default" } as const;
855
+ const runtime = yield* adapter.openSession({
856
+ threadId,
857
+ providerSessionId: ProviderSessionId.make("provider-session-acp-advertised-compaction"),
858
+ modelSelection,
859
+ runtimePolicy,
860
+ });
861
+ const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
862
+ yield* Deferred.await(commandsPublished);
863
+ const now = yield* DateTime.now;
864
+ let ordinal = 0;
865
+ const nextPromptTexts = () =>
866
+ Effect.gen(function* () {
867
+ while (true) {
868
+ const event = yield* Queue.take(protocolEvents);
869
+ if (event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt") {
870
+ return rawProtocolPromptTextBlocks(event);
871
+ }
872
+ }
873
+ });
874
+ return {
875
+ runtime,
876
+ compact: (otherSession = false) =>
877
+ Effect.gen(function* () {
878
+ const compactThread = runtime.compactThread;
879
+ assert.isDefined(compactThread, "compactThread must be wired for compactCommand");
880
+ return yield* Effect.exit(
881
+ compactThread!(
882
+ makeTurnInput({
883
+ threadId,
884
+ providerThread: otherSession
885
+ ? {
886
+ ...providerThread,
887
+ nativeThreadRef: {
888
+ driver: ACP_TEST_DRIVER,
889
+ nativeId: "other-session",
890
+ strength: "strong",
891
+ },
892
+ }
893
+ : { ...providerThread, contextUsage: { usedTokens: 1234 } },
894
+ instanceId,
895
+ runtimePolicy,
896
+ now,
897
+ ordinal: ++ordinal,
898
+ messageText: "Compact the conversation.",
899
+ }),
900
+ ),
901
+ );
902
+ }),
903
+ nextPromptTexts,
904
+ };
905
+});
906
+
907
const runFormElicitation = (input: {
908
readonly name: string;
909
readonly requestedSchema: unknown;
@@ -2124,6 +2212,80 @@ describe("AcpAdapterV2", () => {
2212
}).pipe(Effect.provide(layerTest), Effect.scoped),
2213
);
2214
2215
+ it.live.each([false, true])(
2216
+ "sends a bare /compact prompt with protocol compaction %s",
2217
+ (structured) =>
2218
+ Effect.gen(function* () {
2219
+ const harness = yield* makeAdvertisedCompactionHarness({
2220
+ T3_ACP_AVAILABLE_COMMANDS: "compact,plan",
2221
+ T3_ACP_COMPACTION_PROMPT_ORDINALS: structured ? "1" : "",
2222
+ });
2223
+ const compacted = yield* harness.compact();
2224
+ assert.isTrue(Exit.isSuccess(compacted));
2225
+ assert.deepEqual(yield* harness.nextPromptTexts(), [{ type: "text", text: "/compact" }]);
2226
+ const events = yield* harness.runtime.events.pipe(
2227
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
2228
+ Stream.runCollect,
2229
+ );
2230
+ assert.isTrue(
2231
+ events.some(
2232
+ (event) =>
2233
+ event.type === "provider_thread.updated" &&
2234
+ event.providerThread.contextUsage === null,
2235
+ ),
2236
+ );
2237
+ assert.isTrue(
2238
+ events.some(
2239
+ (event) =>
2240
+ event.type === "turn_item.updated" &&
2241
+ event.turnItem.type === "compaction" &&
2242
+ event.turnItem.status === "completed" &&
2243
+ event.turnItem.title === (structured ? "Compact context" : "Context compacted"),
2244
+ ),
2245
+ );
2246
+ assert.lengthOf(
2247
+ events.filter(
2248
+ (event) =>
2249
+ event.type === "turn_item.updated" &&
2250
+ event.turnItem.type === "compaction" &&
2251
+ event.turnItem.status === "completed",
2252
+ ),
2253
+ 1,
2254
+ );
2255
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
2256
+ );
2257
+
2258
+ it.live.each([
2259
+ { active: "plan", target: "compact", allowed: true },
2260
+ { active: "compact", target: "plan", allowed: false },
2261
+ { active: "compact", target: undefined, allowed: false },
2262
+ ])(
2263
+ "validates the target session's compact command ($active -> $target)",
2264
+ ({ active, target, allowed }) =>
2265
+ Effect.gen(function* () {
2266
+ const harness = yield* makeAdvertisedCompactionHarness({
2267
+ T3_ACP_AVAILABLE_COMMANDS: active,
2268
+ ...(target === undefined ? {} : { T3_ACP_LOADED_COMMANDS: target }),
2269
+ });
2270
+ const result = yield* harness.compact(true);
2271
+ assert.equal(Exit.isSuccess(result), allowed);
2272
+ if (allowed) {
2273
+ assert.deepEqual(yield* harness.nextPromptTexts(), [{ type: "text", text: "/compact" }]);
2274
+ yield* harness.runtime.events.pipe(
2275
+ Stream.takeUntil((event) => event.type === "turn.terminal"),
2276
+ Stream.runDrain,
2277
+ );
2278
+ } else {
2279
+ const error = Exit.isFailure(result) ? Cause.squash(result.cause) : undefined;
2280
+ assert.instanceOf(error, ProviderAdapter.ProviderAdapterTurnStartError);
2281
+ assert.instanceOf(
2282
+ (error as ProviderAdapter.ProviderAdapterTurnStartError).cause,
2283
+ ProviderAdapter.ProviderCompactionUnsupportedError,
2284
+ );
2285
+ }
2286
+ }).pipe(Effect.provide(layerTest), Effect.scoped),
2287
+ );
2288
+
2289
it.live("reapplies a selection after a switch away from it failed partway", () =>
2290
Effect.gen(function* () {
2291
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
packages/provider-acp-registry/src/server/adapter.ts
+1
@@ -227,6 +227,7 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu
227
}
228
: AcpProviderCapabilitiesV2,
229
customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug),
230
+ compactViaAdvertisedCommand: true,
231
promptFailure: (cause) => acpRegistryPromptFailure(registryAgentId, cause),
232
...(registryAgentId === "factory-droid"
233
? { extractElicitationForm: extractDroidElicitationForm }
packages/provider-acp/src/server/adapter.ts
+46
-10
@@ -478,6 +478,8 @@ export interface AcpAdapterV2Flavor {
478
) => Effect.Effect<void>;
479
readonly subagentsIdleOnTurnCompletion?: boolean;
480
readonly supportsCompaction?: boolean;
481
+ /** Sends `/compact` as a prompt, only to sessions whose advertised commands include `compact`. */
482
+ readonly compactViaAdvertisedCommand?: boolean;
483
/**
484
* Native steering: `send` queues a message into the running turn and returns the
485
* agent's id for it, which `injectedSteerId` reads from the update that delivers it.
@@ -2005,6 +2007,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
2007
const promptInstructionStates = yield* Ref.make(new Map<string, T3AcpInstructionState>());
2008
// Unique markers keep delayed prompt completions from clearing later compactions.
2009
const compactionMarkers = yield* Ref.make(new Map<string, symbol>());
2010
+ const advertisedCommandNames = yield* Ref.make(new Map<string, ReadonlySet<string>>());
2011
+ const compactsContext =
2012
+ flavor.supportsCompaction === true ||
2013
+ flavor.compactSession !== undefined ||
2014
+ flavor.compactViaAdvertisedCommand === true;
2015
const runtimeRestartRequired = yield* Ref.make(false);
2016
const runtimeTeardownState = yield* Ref.make<AcpRuntimeTeardownState>({ _tag: "Idle" });
2017
const runtimeCallbackGeneration = yield* Ref.make(0);
@@ -6397,10 +6404,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6404
clientTerminals.readOutputSnapshot,
6405
);
6406
if (notification.update.sessionUpdate === "available_commands_update") {
6400
- yield* (
6401
- flavor.onAvailableCommandsUpdate?.(notification.update.availableCommands) ??
6402
- Effect.void
6403
- );
6407
+ const sessionId = rawNotification.sessionId;
6408
+ const advertisedCommands = notification.update.availableCommands;
6409
+ yield* Ref.update(advertisedCommandNames, (current) => {
6410
+ const updated = new Map(current);
6411
+ updated.set(
6412
+ sessionId,
6413
+ new Set(advertisedCommands.map((command) => command.name.trim().toLowerCase())),
6414
+ );
6415
+ return updated;
6416
+ });
6417
+ yield* flavor.onAvailableCommandsUpdate?.(advertisedCommands) ?? Effect.void;
6418
}
6419
if (
6420
notification.update.sessionUpdate === "config_option_update" ||
@@ -7737,10 +7751,17 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7751
}
7752
const now = yield* DateTime.now;
7753
if (
7740
- (flavor.supportsCompaction === true || flavor.compactSession !== undefined) &&
7754
+ compactsContext &&
7755
isCompactionMessage(context.input.message) &&
7742
- settledStatus === "completed"
7756
+ settledStatus === "completed" &&
7757
+ !context.tools.keys().some((id) => id.startsWith("acp-compaction:"))
7758
) {
7759
+ context.contextUsage = null;
7760
+ yield* Ref.update(contextUsageBySessionId, (current) => {
7761
+ const updated = new Map(current);
7762
+ updated.delete(context.nativeThreadId);
7763
+ return updated;
7764
+ });
7765
const nativeItemId = `${context.nativeTurnId}:compaction`;
7766
yield* Ref.update(compactionMarkers, (current) => {
7767
const updated = new Map(current);
@@ -8195,6 +8216,18 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8216
yield* Ref.set(activeInteractionMode, turnInput.runtimePolicy.interactionMode);
8217
}
8218
}
8219
+ // Checked after activation: a loaded session advertises its own commands.
8220
+ if (
8221
+ flavor.compactViaAdvertisedCommand === true &&
8222
+ isCompactionMessage(turnInput.message) &&
8223
+ (yield* Ref.get(advertisedCommandNames)).get(requestedSessionId)?.has("compact") !==
8224
+ true
8225
+ ) {
8226
+ return yield* new ProviderAdapter.ProviderCompactionUnsupportedError({
8227
+ driver,
8228
+ providerThreadId: turnInput.providerThread.id,
8229
+ });
8230
+ }
8231
yield* validateModelSelection(turnInput.modelSelection);
8232
yield* Ref.set(lastTurnRoute, {
8233
threadId: turnInput.threadId,
@@ -8861,13 +8894,16 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8894
),
8895
),
8896
startTurn,
8864
- ...(flavor.supportsCompaction === true || flavor.compactSession !== undefined
8897
+ ...(compactsContext
8898
? {
8866
- compactThread: (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) =>
8867
- startTurn({
8899
+ compactThread: Effect.fn("AcpAdapterV2.compactThread")(function* (
8900
+ turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
8901
+ ) {
8902
+ return yield* startTurn({
8903
...turnInput,
8904
message: { ...turnInput.message, text: "/compact" },
8870
- }),
8905
+ });
8906
+ }),
8907
}
8908
: {}),
8909
steerTurn: Effect.fn("AcpAdapterV2.steerTurn")(