@agentclientprotocol/claude-agent-acp 0.111.0 → 0.111.1-preview.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -1
- package/dist/air-extension.d.ts +7 -0
- package/dist/air-extension.d.ts.map +1 -1
- package/dist/air-extension.js +7 -0
- package/dist/fork-session.d.ts.map +1 -1
- package/dist/fork-session.js +12 -6
- package/dist/mcp-servers.d.ts +6 -1
- package/dist/mcp-servers.d.ts.map +1 -1
- package/dist/mcp-servers.js +13 -4
- package/dist/session-cursors.d.ts +88 -4
- package/dist/session-cursors.d.ts.map +1 -1
- package/dist/session-cursors.js +128 -3
- package/dist/session-rewind.d.ts +160 -0
- package/dist/session-rewind.d.ts.map +1 -0
- package/dist/session-rewind.js +454 -0
- package/dist/v1/acp-agent.d.ts +39 -0
- package/dist/v1/acp-agent.d.ts.map +1 -1
- package/dist/v1/acp-agent.js +275 -13
- package/dist/v2/agent.d.ts.map +1 -1
- package/dist/v2/agent.js +9 -2
- package/package.json +2 -2
package/dist/v1/acp-agent.js
CHANGED
|
@@ -8,7 +8,7 @@ import { applyInitialConfigOptions, initialConfigOptions, SESSION_OPTIONS_CAPABI
|
|
|
8
8
|
import { sanitizeTitle, SessionTitles } from "../session-titles.js";
|
|
9
9
|
import { AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY, AnnouncedChildren, asSdkSessionNotification, clientSupportsSubagents, restrictedChild, subagentForm, } from "../acp-subagents.js";
|
|
10
10
|
import { childModelOption, isNativeSubagentControlTool, isNativeSubagentControlUpdate, NativeSubagentRuntime, nativeSubagentState, responseModelEntry, resumedNativeSubagentId, sameModelEntry, sendMessageResume, sendMessageResumePrompt, } from "../native-subagents.js";
|
|
11
|
-
import { AIR_ASYNC_TASKS_CAPABILITY, AIR_BACKGROUND_SUBAGENTS_CAPABILITY, AIR_CUSTOM_INSTRUCTIONS_CAPABILITY, airCustomInstructions, AIR_DIFF_PATCH_CAPABILITY, AIR_PLAN_FILE_CAPABILITY, AIR_GOAL_KEY, AIR_LOAD_REPLAY_END_CAPABILITY, AIR_LOAD_REPLAY_END_KEY, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, clientSupportsAirCapability, withAirMeta, } from "../air-extension.js";
|
|
11
|
+
import { AIR_ASYNC_TASKS_CAPABILITY, AIR_BACKGROUND_SUBAGENTS_CAPABILITY, AIR_CUSTOM_INSTRUCTIONS_CAPABILITY, airCustomInstructions, AIR_DIFF_PATCH_CAPABILITY, AIR_PLAN_FILE_CAPABILITY, AIR_SESSION_REWIND_CAPABILITY, AIR_GOAL_KEY, AIR_LOAD_REPLAY_END_CAPABILITY, AIR_LOAD_REPLAY_END_KEY, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, clientSupportsAirCapability, withAirMeta, } from "../air-extension.js";
|
|
12
12
|
import * as sessionIndex from "./session-index.js";
|
|
13
13
|
import { AsyncTaskRuntime, backgroundBashTaskFromToolResult, backgroundedBashToolCallIds, clientSupportsAsyncTasks, } from "../async-tasks.js";
|
|
14
14
|
import { SessionBackgroundWork } from "./background-work.js";
|
|
@@ -27,6 +27,8 @@ import packageJson from "../../package.json" with { type: "json" };
|
|
|
27
27
|
import { answerAskUserQuestion, answerMcpElicitation, answerUserDialog, elicitUnlessWithdrawn, isConfirmQuestion, REFUSAL_FALLBACK_DIALOG_KIND, } from "../elicitation.js";
|
|
28
28
|
import { startMcpServerAuthentication as startSharedMcpServerAuthentication, supportsMcpOAuth, } from "../mcp-oauth.js";
|
|
29
29
|
import { forkSession } from "../fork-session.js";
|
|
30
|
+
import { anchoredForkCursorUpdate, forkCursorUpdate, hasForkCursor, LastReportedEntity, promptGetsCursor, withRewindCapability, } from "../session-cursors.js";
|
|
31
|
+
import { cutAtRewindPoint, loadRewindableHistory, parseSessionRewindRequest, prepareRewoundResume, rewindSession, SESSION_REWIND_METHOD, } from "../session-rewind.js";
|
|
30
32
|
import { clientSystemPrompt, sessionSystemPrompt, SYSTEM_PROMPT_CAPABILITY, } from "../client-system-prompt.js";
|
|
31
33
|
import { readSubagentMessages, subagentHistory, subagentLaunchIds, subagentLaunchedBy, subagentLineage, } from "../subagent-history.js";
|
|
32
34
|
import { RfdSubagentReplay, ReplayTranscript, replaySubagentTerminalState, } from "../subagent-replay.js";
|
|
@@ -361,6 +363,10 @@ export class ClaudeAcpAgent {
|
|
|
361
363
|
providerUpdate = null;
|
|
362
364
|
/** Per session: queue that runs mode/config changes and query restarts one at a time. */
|
|
363
365
|
configurationChanges = new Map();
|
|
366
|
+
/** The `_session/rewind` of each session that one is running for. It never rejects. */
|
|
367
|
+
sessionRewinds = new Map();
|
|
368
|
+
/** The session a finished rewind left in place of the one it closed, so a prompt that still holds the old one can follow it. */
|
|
369
|
+
rewoundSessions = new WeakMap();
|
|
364
370
|
exitPlan;
|
|
365
371
|
/** The connection's `authStatus` state and pushes, connection-scoped like
|
|
366
372
|
* `authenticate`/`logout`. */
|
|
@@ -398,6 +404,8 @@ export class ClaudeAcpAgent {
|
|
|
398
404
|
* (see {@link endSession}) or the connection ends (see `AnnouncedChildren`).
|
|
399
405
|
*/
|
|
400
406
|
announcedChildren = new AnnouncedChildren();
|
|
407
|
+
/** What anchors a live cursor: the last entity that the client holds per session. */
|
|
408
|
+
lastEntities = new LastReportedEntity();
|
|
401
409
|
/**
|
|
402
410
|
* AIR's draft: the model that the last load of each session replayed to each
|
|
403
411
|
* child session, as the model id and the entry that went out. See
|
|
@@ -450,6 +458,7 @@ export class ClaudeAcpAgent {
|
|
|
450
458
|
// Before the client can name the child that a `subagent_update` announces.
|
|
451
459
|
this.announcedChildren.sending(update);
|
|
452
460
|
this.mcp.sending(update);
|
|
461
|
+
this.lastEntities.sending(update);
|
|
453
462
|
});
|
|
454
463
|
this.logger = logger ?? console;
|
|
455
464
|
this.exitPlan = new ExitPlanCoordinator({
|
|
@@ -612,7 +621,9 @@ export class ClaudeAcpAgent {
|
|
|
612
621
|
// `jetbrains.air`.
|
|
613
622
|
_meta: {
|
|
614
623
|
...(this.toolCallCapabilities.air.client
|
|
615
|
-
? withAirMeta(airSessionFailureCapabilityMeta(AGENT_FILE_CHANGE_REPORT_CAPABILITY, AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY, AIR_ASYNC_TASKS_CAPABILITY, AIR_CUSTOM_INSTRUCTIONS_CAPABILITY, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, AIR_DIFF_PATCH_CAPABILITY, AIR_PLAN_FILE_CAPABILITY, AIR_BACKGROUND_SUBAGENTS_CAPABILITY, ...this.sessionIndex.capabilities()
|
|
624
|
+
? withAirMeta(airSessionFailureCapabilityMeta(AGENT_FILE_CHANGE_REPORT_CAPABILITY, AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY, AIR_ASYNC_TASKS_CAPABILITY, AIR_CUSTOM_INSTRUCTIONS_CAPABILITY, AIR_RECOMMENDED_CONFIG_VALUE_CAPABILITY, AIR_DIFF_PATCH_CAPABILITY, AIR_PLAN_FILE_CAPABILITY, AIR_BACKGROUND_SUBAGENTS_CAPABILITY, ...this.sessionIndex.capabilities(), ...(clientSupportsAirCapability(request.clientCapabilities, AIR_SESSION_REWIND_CAPABILITY)
|
|
625
|
+
? [AIR_SESSION_REWIND_CAPABILITY]
|
|
626
|
+
: [])), AIR_GOAL_KEY, {
|
|
616
627
|
version: GOAL_EXTENSION_VERSION,
|
|
617
628
|
controlMethod: GOAL_CONTROL_METHOD,
|
|
618
629
|
actions: [...GOAL_ACTIONS],
|
|
@@ -780,6 +791,83 @@ export class ClaudeAcpAgent {
|
|
|
780
791
|
forking(sourceId, fork) {
|
|
781
792
|
return this.sessionIndex.forking(sourceId, fork);
|
|
782
793
|
}
|
|
794
|
+
/**
|
|
795
|
+
* `_session/rewind` (see `session-rewind.ts`). Queued with the session's
|
|
796
|
+
* configuration changes, so a mode or model change sent meanwhile lands on
|
|
797
|
+
* the resumed query. A prompt sent meanwhile waits for it in `startTurn`:
|
|
798
|
+
* the rewind closes the query the prompt would otherwise run on.
|
|
799
|
+
*/
|
|
800
|
+
rewindSession(params) {
|
|
801
|
+
// Only AIR knows the method, and only when it declared `sessionRewind`.
|
|
802
|
+
if (!this.supportsSessionRewind()) {
|
|
803
|
+
return Promise.reject(RequestError.methodNotFound(SESSION_REWIND_METHOD));
|
|
804
|
+
}
|
|
805
|
+
const { sessionId } = params;
|
|
806
|
+
const rewind = (async () => {
|
|
807
|
+
// Outside the queue: a provider update queues its own restart there.
|
|
808
|
+
while (this.providerUpdate)
|
|
809
|
+
await this.providerUpdate;
|
|
810
|
+
return this.serializeConfigurationChange(sessionId, () => this.rewindLiveSession(params));
|
|
811
|
+
})();
|
|
812
|
+
const settled = rewind.then(() => undefined, () => undefined);
|
|
813
|
+
this.sessionRewinds.set(sessionId, settled);
|
|
814
|
+
void settled.then(() => {
|
|
815
|
+
if (this.sessionRewinds.get(sessionId) === settled)
|
|
816
|
+
this.sessionRewinds.delete(sessionId);
|
|
817
|
+
});
|
|
818
|
+
return rewind;
|
|
819
|
+
}
|
|
820
|
+
rewindLiveSession(params) {
|
|
821
|
+
const { sessionId } = params;
|
|
822
|
+
const session = this.sessions[sessionId];
|
|
823
|
+
if (!session)
|
|
824
|
+
throw RequestError.sessionNotFound(sessionId);
|
|
825
|
+
const creationParams = session.creationParams;
|
|
826
|
+
if (!creationParams || session.queryClosed) {
|
|
827
|
+
throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
|
|
828
|
+
}
|
|
829
|
+
return rewindSession(params, {
|
|
830
|
+
logger: this.logger,
|
|
831
|
+
clearedContext: session.claudeSessionId !== undefined,
|
|
832
|
+
// A `/remote-control` command in flight answers into the session's output
|
|
833
|
+
// after the query that the rewind closes was asked for it.
|
|
834
|
+
claudeIsWorking: () => this.claudeIsWorking(sessionId, session) || session.remoteControlCommand !== undefined,
|
|
835
|
+
// A closed query also ends the background tasks and subagents.
|
|
836
|
+
hasBackgroundWork: () => [...session.liveBackgroundTasks.values()].some((task) => !task.endedPerLevel),
|
|
837
|
+
loadHistory: () => loadRewindableHistory(sessionId, this.logger),
|
|
838
|
+
// The task list and the published failures outlive the dropped turns (and
|
|
839
|
+
// a failed cut): their entries carry ids of their own, which the transcript
|
|
840
|
+
// does not attribute to a turn. The ACP message ids are not carried: they
|
|
841
|
+
// may name a dropped message, and a fork then reads the stored history.
|
|
842
|
+
replaceQuery: async (resumeAt) => {
|
|
843
|
+
await this.replaceSessionQuery(sessionId, session, creationParams, resumeAt, {
|
|
844
|
+
cwd: session.cwd,
|
|
845
|
+
taskState: session.taskState,
|
|
846
|
+
subagentChecklists: session.subagentChecklists,
|
|
847
|
+
forwardSubagentText: session.forwardSubagentText,
|
|
848
|
+
sessionFailureState: session.sessionFailureState,
|
|
849
|
+
messageIdToUuid: new Map(),
|
|
850
|
+
});
|
|
851
|
+
const recreated = this.sessions[sessionId];
|
|
852
|
+
if (recreated && recreated !== session)
|
|
853
|
+
this.rewoundSessions.set(session, recreated);
|
|
854
|
+
},
|
|
855
|
+
// The client drops the entities after the cut, which the anchor may name.
|
|
856
|
+
// The edited message's cursor lies where the dropped one did.
|
|
857
|
+
rewound: (cursorId) => this.lastEntities.rewind(sessionId, cursorId),
|
|
858
|
+
abandon: async (error) => {
|
|
859
|
+
if (error instanceof RequestError && error.code === AUTH_REQUIRED_CODE) {
|
|
860
|
+
// As after a sign-out: keep the husk, so the prompt after a sign-in
|
|
861
|
+
// recreates its query instead of meeting "Session not found".
|
|
862
|
+
session.needsSignOutRespawn = true;
|
|
863
|
+
return error;
|
|
864
|
+
}
|
|
865
|
+
// Not a closed husk: a `session/load` resumes the conversation again.
|
|
866
|
+
await this.teardownSession(sessionId);
|
|
867
|
+
return RequestError.internalError(undefined, `The rewind failed and the session could not be resumed: ${error}. Load the session again.`);
|
|
868
|
+
},
|
|
869
|
+
});
|
|
870
|
+
}
|
|
783
871
|
async resumeSession(params) {
|
|
784
872
|
const initial = initialConfigOptions(params.configOptions);
|
|
785
873
|
while (this.providerUpdate)
|
|
@@ -1082,6 +1170,10 @@ export class ClaudeAcpAgent {
|
|
|
1082
1170
|
const received = ++this.promptsReceived;
|
|
1083
1171
|
while (this.providerUpdate)
|
|
1084
1172
|
await this.providerUpdate;
|
|
1173
|
+
// A rewind closes the session's query and resumes a new one.
|
|
1174
|
+
const rewinding = this.sessionRewinds.get(params.sessionId);
|
|
1175
|
+
if (rewinding)
|
|
1176
|
+
await rewinding;
|
|
1085
1177
|
let session = this.sessions[params.sessionId];
|
|
1086
1178
|
if (!session) {
|
|
1087
1179
|
throw RequestError.sessionNotFound(params.sessionId);
|
|
@@ -1115,9 +1207,16 @@ export class ClaudeAcpAgent {
|
|
|
1115
1207
|
}
|
|
1116
1208
|
// Only a prompt that is the command awaits here: an await on every prompt
|
|
1117
1209
|
// would let other work run between its checks and its turn's enqueue.
|
|
1118
|
-
const
|
|
1119
|
-
|
|
1120
|
-
|
|
1210
|
+
const isRemoteControl = parseRemoteControlCommand(params.prompt) !== null;
|
|
1211
|
+
const askRemoteControl = () => adapterRemoteControlCommand(params.prompt, session.query, session.terminalSlashCommands);
|
|
1212
|
+
let remoteControl = isRemoteControl ? await askRemoteControl() : null;
|
|
1213
|
+
// A rewind that closed the query during that await did not see the command
|
|
1214
|
+
// (`remoteControlCommand` is not set yet). It goes on with the session the
|
|
1215
|
+
// rewind leaves, and is asked again of its query.
|
|
1216
|
+
while (isRemoteControl && this.rewindToFollow(params.sessionId, session)) {
|
|
1217
|
+
session = await this.followRewind(params.sessionId, session);
|
|
1218
|
+
remoteControl = await askRemoteControl();
|
|
1219
|
+
}
|
|
1121
1220
|
if (remoteControl) {
|
|
1122
1221
|
// The reply bypasses the turn queue, so it would land inside the output of
|
|
1123
1222
|
// a turn that is still running. Refuse instead of interleaving.
|
|
@@ -1162,6 +1261,16 @@ export class ClaudeAcpAgent {
|
|
|
1162
1261
|
if (Array.from(session.taskState.values()).some((task) => task.status !== "completed")) {
|
|
1163
1262
|
await this.publishTaskPlan(params.sessionId, session.taskState);
|
|
1164
1263
|
}
|
|
1264
|
+
// A rewind that started during the awaits above did not see this prompt,
|
|
1265
|
+
// which is not queued yet, and closes the query it was set up on. The
|
|
1266
|
+
// prompt goes on with the session the rewind leaves, also when the rewind
|
|
1267
|
+
// finished before this point. Only the subscription guard runs again: it is
|
|
1268
|
+
// per query.
|
|
1269
|
+
if (this.rewindToFollow(params.sessionId, session)) {
|
|
1270
|
+
session = await this.followRewind(params.sessionId, session);
|
|
1271
|
+
if (origin === "client")
|
|
1272
|
+
session.idleCompaction?.disarm("prompt");
|
|
1273
|
+
}
|
|
1165
1274
|
const userMessage = promptToClaude(params);
|
|
1166
1275
|
const promptUuid = randomUUID();
|
|
1167
1276
|
userMessage.uuid = promptUuid;
|
|
@@ -1169,7 +1278,7 @@ export class ClaudeAcpAgent {
|
|
|
1169
1278
|
// user message, so the consumer can't promote the turn from the echo.
|
|
1170
1279
|
const firstText = params.prompt[0]?.type === "text" ? params.prompt[0].text : "";
|
|
1171
1280
|
const isLocalOnlyCommand = firstText.startsWith("/") && LOCAL_ONLY_COMMANDS.has(firstText.split(" ", 1)[0]);
|
|
1172
|
-
|
|
1281
|
+
let fileChangeReport = session.fileChangeReporter?.request(params._meta);
|
|
1173
1282
|
const localCommand = this.localCommandMarkdown(params);
|
|
1174
1283
|
const localCommandAbort = localCommand ? new AbortController() : undefined;
|
|
1175
1284
|
// An idle compaction is not something the user sent: it must not title the
|
|
@@ -1187,11 +1296,38 @@ export class ClaudeAcpAgent {
|
|
|
1187
1296
|
await this.publishPromptSuggestions(params.sessionId, cleared);
|
|
1188
1297
|
}
|
|
1189
1298
|
// A `/remote-control` command still in flight answers into the session's
|
|
1190
|
-
// output; wait for its reply before this prompt's turn can begin.
|
|
1191
|
-
//
|
|
1299
|
+
// output; wait for its reply before this prompt's turn can begin. A rewind
|
|
1300
|
+
// may have replaced the session during the awaits above, including the
|
|
1301
|
+
// command's network call, and a command may be in flight on the successor
|
|
1302
|
+
// too (a `/remote-control` prompt that the same rewind held). So wait for
|
|
1303
|
+
// the current session's command, follow a rewind, and look again, until
|
|
1304
|
+
// neither is pending. The check that ends the loop and the turn's enqueue
|
|
1305
|
+
// below have no await between them, so no command can start in between.
|
|
1192
1306
|
// A failure of the command's reply is reported to the command's own prompt.
|
|
1193
|
-
|
|
1194
|
-
|
|
1307
|
+
// A command that was waited for is done: its prompt clears the field in a
|
|
1308
|
+
// `finally` that may run after this wait resumes, so it is not waited for twice.
|
|
1309
|
+
let waited;
|
|
1310
|
+
for (;;) {
|
|
1311
|
+
if (session.remoteControlCommand && session.remoteControlCommand !== waited) {
|
|
1312
|
+
waited = session.remoteControlCommand;
|
|
1313
|
+
await waited.catch(() => { });
|
|
1314
|
+
continue;
|
|
1315
|
+
}
|
|
1316
|
+
if (!this.rewindToFollow(params.sessionId, session))
|
|
1317
|
+
break;
|
|
1318
|
+
const followed = await this.followRewind(params.sessionId, session);
|
|
1319
|
+
if (followed === session)
|
|
1320
|
+
continue;
|
|
1321
|
+
// What the prompt took from the old session (the file change report, the
|
|
1322
|
+
// title context and the idle compaction's disarm) is taken again from
|
|
1323
|
+
// the new one.
|
|
1324
|
+
session = followed;
|
|
1325
|
+
fileChangeReport = session.fileChangeReporter?.request(params._meta);
|
|
1326
|
+
if (origin === "client") {
|
|
1327
|
+
session.titles.onPrompt(params.prompt);
|
|
1328
|
+
session.idleCompaction?.disarm("prompt");
|
|
1329
|
+
}
|
|
1330
|
+
}
|
|
1195
1331
|
// A `session/close` during the awaits above tore the session down, and
|
|
1196
1332
|
// its consumer is gone, so the prompt would never be inserted. End it
|
|
1197
1333
|
// `cancelled`, as the close ends a queued turn. A stream
|
|
@@ -1216,6 +1352,7 @@ export class ClaudeAcpAgent {
|
|
|
1216
1352
|
promptUuid,
|
|
1217
1353
|
events,
|
|
1218
1354
|
isLocalOnlyCommand,
|
|
1355
|
+
getsCursor: promptGetsCursor(params.prompt),
|
|
1219
1356
|
...(localCommand ? { localCommand } : {}),
|
|
1220
1357
|
...(localCommandAbort ? { localCommandAbort } : {}),
|
|
1221
1358
|
...(fileChangeReport ? { fileChangeReport } : {}),
|
|
@@ -1245,6 +1382,72 @@ export class ClaudeAcpAgent {
|
|
|
1245
1382
|
// the goal it sets; the turn's events report the outcome.
|
|
1246
1383
|
await this.publishGoalFromPrompt(params.sessionId, firstText, promptUuid).catch((error) => this.logger.error(`Session ${params.sessionId}: failed to publish the prompt's goal:`, error));
|
|
1247
1384
|
}
|
|
1385
|
+
/** Checked before `followRewind` so that a prompt which has nothing to follow does not yield. */
|
|
1386
|
+
rewindToFollow(sessionId, session) {
|
|
1387
|
+
return this.sessionRewinds.has(sessionId) || this.rewoundSessions.has(session);
|
|
1388
|
+
}
|
|
1389
|
+
/** Waits for a running rewind of the session and returns the session the rewinds left in place of `session`; a session that ended otherwise is returned as it is. */
|
|
1390
|
+
async followRewind(sessionId, session) {
|
|
1391
|
+
let moved = false;
|
|
1392
|
+
for (;;) {
|
|
1393
|
+
const running = this.sessionRewinds.get(sessionId);
|
|
1394
|
+
if (running) {
|
|
1395
|
+
await running;
|
|
1396
|
+
if (!this.sessions[sessionId])
|
|
1397
|
+
throw RequestError.sessionNotFound(sessionId);
|
|
1398
|
+
}
|
|
1399
|
+
const next = this.rewoundSessions.get(session);
|
|
1400
|
+
if (next) {
|
|
1401
|
+
session = next;
|
|
1402
|
+
moved = true;
|
|
1403
|
+
continue;
|
|
1404
|
+
}
|
|
1405
|
+
if (running)
|
|
1406
|
+
continue;
|
|
1407
|
+
if (!moved)
|
|
1408
|
+
return session;
|
|
1409
|
+
// Only the end of the chain must be alive: an intermediate session of two
|
|
1410
|
+
// rewinds in one await is closed by the second rewind.
|
|
1411
|
+
if (session.queryClosed)
|
|
1412
|
+
throw RequestError.internalError(undefined, SESSION_ENDED_MESSAGE);
|
|
1413
|
+
const guard = this.runClaudeSubscriptionGuard(sessionId, session);
|
|
1414
|
+
if (guard)
|
|
1415
|
+
await guard;
|
|
1416
|
+
if (!this.rewoundSessions.has(session) && !this.sessionRewinds.has(sessionId)) {
|
|
1417
|
+
return session;
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
/** Whether the client is AIR and declared `sessionRewind`: only it knows `_session/rewind`. */
|
|
1422
|
+
supportsSessionRewind() {
|
|
1423
|
+
return (this.toolCallCapabilities.air.client &&
|
|
1424
|
+
clientSupportsAirCapability(this.clientCapabilities, AIR_SESSION_REWIND_CAPABILITY));
|
|
1425
|
+
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Sends a `cursor_update` to a client that declared `session.cursors`, and to
|
|
1428
|
+
* no other: its `SessionUpdate` union is closed. A failed send is logged only,
|
|
1429
|
+
* as the cursor is announced again by the next replay.
|
|
1430
|
+
*
|
|
1431
|
+
* `before` is the entity that this client holds right before the cursor.
|
|
1432
|
+
*
|
|
1433
|
+
* It carries `rewind` only where `_session/rewind` can act: not for a cursor
|
|
1434
|
+
* that is `beforeCompaction` (`rewindable` false), and not in a session whose
|
|
1435
|
+
* context was cleared (`clearedContext`).
|
|
1436
|
+
*/
|
|
1437
|
+
announceCursor(sessionId, update, before, { rewindable: inChain = true } = {}) {
|
|
1438
|
+
if (this.clientCapabilities?.session?.cursors == null)
|
|
1439
|
+
return;
|
|
1440
|
+
this.lastEntities.recordCursor(sessionId, update.cursorId, before);
|
|
1441
|
+
const rewindable = inChain &&
|
|
1442
|
+
this.supportsSessionRewind() &&
|
|
1443
|
+
this.sessions[sessionId]?.claudeSessionId === undefined;
|
|
1444
|
+
this.client
|
|
1445
|
+
.sessionUpdate({
|
|
1446
|
+
sessionId,
|
|
1447
|
+
update: rewindable ? withRewindCapability(update) : update,
|
|
1448
|
+
})
|
|
1449
|
+
.catch((error) => this.logger.error(`Session ${sessionId}: cursor_update failed:`, error));
|
|
1450
|
+
}
|
|
1248
1451
|
/** Runs the command, and sends its reply (see `runRemoteControlCommand`). */
|
|
1249
1452
|
async runRemoteControlCommand(sessionId, { query, command }) {
|
|
1250
1453
|
const text = await runRemoteControlCommand(query, command, (message) => this.logger.error(message));
|
|
@@ -2043,6 +2246,13 @@ export class ClaudeAcpAgent {
|
|
|
2043
2246
|
turn.insertedReported = true;
|
|
2044
2247
|
turn.events.inserted(turn.promptUuid);
|
|
2045
2248
|
this.startForeground(params.sessionId, turn);
|
|
2249
|
+
// v1 does not report the prompt the client sent, so the cursor lies after
|
|
2250
|
+
// the entity before it. The first prompt has none, and a session that was
|
|
2251
|
+
// resumed without a replay holds none (no anchor, no cursor).
|
|
2252
|
+
const anchor = this.lastEntities.after(params.sessionId);
|
|
2253
|
+
if (turn.getsCursor && anchor) {
|
|
2254
|
+
this.announceCursor(params.sessionId, anchoredForkCursorUpdate(turn.promptUuid, anchor), this.lastEntities.last(params.sessionId));
|
|
2255
|
+
}
|
|
2046
2256
|
};
|
|
2047
2257
|
/** Ensure there is an active turn before a user-turn result that carries no
|
|
2048
2258
|
* echo to activate it, by promoting the queue head. Most turns are
|
|
@@ -4818,6 +5028,9 @@ export class ClaudeAcpAgent {
|
|
|
4818
5028
|
? stripLocalCommandMetadata(message.message.content)
|
|
4819
5029
|
: null;
|
|
4820
5030
|
if (remoteContent !== null) {
|
|
5031
|
+
// Before the message itself is reported below.
|
|
5032
|
+
const before = this.lastEntities.last(params.sessionId);
|
|
5033
|
+
const hasHistory = before !== undefined;
|
|
4821
5034
|
for (const notification of toAcpNotifications(remoteContent, "user", params.sessionId, session.toolUseCache, routedNotificationClient, this.logger, {
|
|
4822
5035
|
clientCapabilities: this.clientCapabilities,
|
|
4823
5036
|
toolCallCapabilities: this.toolCallCapabilities,
|
|
@@ -4826,6 +5039,14 @@ export class ClaudeAcpAgent {
|
|
|
4826
5039
|
})) {
|
|
4827
5040
|
await sendUpdate(notification);
|
|
4828
5041
|
}
|
|
5042
|
+
// This client reported the message with its `messageId`: the
|
|
5043
|
+
// cursor lies before it, as in a replay.
|
|
5044
|
+
if (hasHistory &&
|
|
5045
|
+
promptGetsCursor(typeof remoteContent === "string"
|
|
5046
|
+
? [{ type: "text", text: remoteContent }]
|
|
5047
|
+
: remoteContent)) {
|
|
5048
|
+
this.announceCursor(params.sessionId, forkCursorUpdate(message.uuid), before);
|
|
5049
|
+
}
|
|
4829
5050
|
}
|
|
4830
5051
|
// Otherwise an unrelated replay (e.g. the echo of an already-settled turn).
|
|
4831
5052
|
break;
|
|
@@ -5844,6 +6065,7 @@ export class ClaudeAcpAgent {
|
|
|
5844
6065
|
// After the teardown's last updates, which name the children.
|
|
5845
6066
|
this.announcedChildren.rootClosed(sessionId);
|
|
5846
6067
|
this.mcp.sessionClosed(sessionId);
|
|
6068
|
+
this.lastEntities.forget(sessionId);
|
|
5847
6069
|
}
|
|
5848
6070
|
/** Idempotent: a session that is not loaded here is already closed. */
|
|
5849
6071
|
async closeSession(params) {
|
|
@@ -5930,8 +6152,14 @@ export class ClaudeAcpAgent {
|
|
|
5930
6152
|
async replaySessionHistory(sessionId, resumedMessages, pending) {
|
|
5931
6153
|
const replayStartedAt = performance.now();
|
|
5932
6154
|
const toolUseCache = {};
|
|
6155
|
+
// A replay rebuilds the client's entities, and its cursors anchor to those.
|
|
6156
|
+
this.lastEntities.forget(sessionId);
|
|
5933
6157
|
// A load replays the messages before each compaction too, unless reading them fails.
|
|
5934
|
-
|
|
6158
|
+
// The rewind cut comes first: the dropped turns get no replay and no cursor.
|
|
6159
|
+
const current = await cutAtRewindPoint(sessionId, resumedMessages ?? (await getSessionMessages(sessionId)), this.logger);
|
|
6160
|
+
const messages = await readHistoryAcrossCompactions(sessionId, current, this.logger);
|
|
6161
|
+
// A cursor whose resume point a compaction left out cannot be rewound to.
|
|
6162
|
+
const currentUuids = new Set(current.map((message) => message.uuid));
|
|
5935
6163
|
const historyLoadedAt = performance.now();
|
|
5936
6164
|
this.logger.log(`[session/replay] sessionId=${sessionId} phase=read durationMs=${Math.round(historyLoadedAt - replayStartedAt)} messages=${messages.length}`);
|
|
5937
6165
|
// A pending replay has no session record yet. It uses the state that the record takes later.
|
|
@@ -6340,8 +6568,19 @@ export class ClaudeAcpAgent {
|
|
|
6340
6568
|
}
|
|
6341
6569
|
}
|
|
6342
6570
|
};
|
|
6343
|
-
for (const message of messages)
|
|
6571
|
+
for (const [index, message] of messages.entries()) {
|
|
6572
|
+
// Before the message's own chunk: the cursor lies before the message.
|
|
6573
|
+
const before = this.lastEntities.last(sessionId);
|
|
6344
6574
|
await replayMessage(message);
|
|
6575
|
+
// A task notification record is no user message to the client (see `replayMessage`).
|
|
6576
|
+
if (!pending?.stopped &&
|
|
6577
|
+
hasForkCursor(messages, index) &&
|
|
6578
|
+
!isTaskNotificationRecord(message)) {
|
|
6579
|
+
this.announceCursor(sessionId, forkCursorUpdate(message.uuid), before, {
|
|
6580
|
+
rewindable: currentUuids.has(messages[index - 1].uuid),
|
|
6581
|
+
});
|
|
6582
|
+
}
|
|
6583
|
+
}
|
|
6345
6584
|
if (rfdReplay && !pending?.stopped) {
|
|
6346
6585
|
await rfdReplay.finish(clientSupportsNotices(this.clientCapabilities), sessionId);
|
|
6347
6586
|
this.replayedSubagents.set(sessionId, rfdReplay);
|
|
@@ -7585,6 +7824,13 @@ export class ClaudeAcpAgent {
|
|
|
7585
7824
|
}
|
|
7586
7825
|
const timing = new SessionTiming(this.logger, "create", sessionId, createStartedAt);
|
|
7587
7826
|
timing.phase("validate-cwd");
|
|
7827
|
+
// A resume stops at a pending rewind point, or the dropped turns come back.
|
|
7828
|
+
// The `session/options` probe persists nothing, so it leaves the transcript
|
|
7829
|
+
// and `rewind.json` alone. A rewind passes its own point.
|
|
7830
|
+
const resumeSessionAt = creationOpts.resumeSessionAt ??
|
|
7831
|
+
(creationOpts.resume !== undefined && !creationOpts.optionsOnly
|
|
7832
|
+
? await prepareRewoundResume(creationOpts.resume, this.logger)
|
|
7833
|
+
: undefined);
|
|
7588
7834
|
// Most session/load calls already carry a transcript snapshot so history
|
|
7589
7835
|
// replay and model restoration share one local read. A few resume paths
|
|
7590
7836
|
// intentionally call createSession directly (legacy session/new metadata,
|
|
@@ -7939,6 +8185,13 @@ export class ClaudeAcpAgent {
|
|
|
7939
8185
|
],
|
|
7940
8186
|
},
|
|
7941
8187
|
...(creationOpts.resume !== undefined && { resume: creationOpts.resume }),
|
|
8188
|
+
...(creationOpts.resume !== undefined &&
|
|
8189
|
+
resumeSessionAt !== undefined && {
|
|
8190
|
+
resumeSessionAt,
|
|
8191
|
+
...(creationOpts.resumeDropsTurn !== undefined && {
|
|
8192
|
+
resumeDropsTurn: creationOpts.resumeDropsTurn,
|
|
8193
|
+
}),
|
|
8194
|
+
}),
|
|
7942
8195
|
...(creationOpts.forkSession !== undefined && { forkSession: creationOpts.forkSession }),
|
|
7943
8196
|
// The probe neither reports session updates through our hooks nor
|
|
7944
8197
|
// starts the MCP servers in the client's options or workspace settings.
|
|
@@ -8148,6 +8401,9 @@ export class ClaudeAcpAgent {
|
|
|
8148
8401
|
resumedFromHistory: creationOpts.resume !== undefined,
|
|
8149
8402
|
cwd: params.cwd,
|
|
8150
8403
|
sessionFingerprint: computeSessionFingerprint(params),
|
|
8404
|
+
...(creationOpts.publicSessionId && options.sessionId
|
|
8405
|
+
? { claudeSessionId: options.sessionId }
|
|
8406
|
+
: {}),
|
|
8151
8407
|
creationParams: params,
|
|
8152
8408
|
unservedMcpServers,
|
|
8153
8409
|
settingsManager,
|
|
@@ -8308,13 +8564,15 @@ export class ClaudeAcpAgent {
|
|
|
8308
8564
|
}
|
|
8309
8565
|
}
|
|
8310
8566
|
/** Recreates the session's query, restores its choices and reported MCP servers, and starts reading it, unless it was closed meanwhile. */
|
|
8311
|
-
async replaceSessionQuery(sessionId, session, creationParams) {
|
|
8567
|
+
async replaceSessionQuery(sessionId, session, creationParams, resumeAt, keepState) {
|
|
8312
8568
|
this.closeQueryStream(session);
|
|
8313
8569
|
// Keep the old record visible so closeSession and dispose can mark it torn down.
|
|
8314
8570
|
// Without the creation-time effort: restoreSessionChoices restores the current pin instead.
|
|
8315
8571
|
await this.recreateLiveSession(withoutEffort(creationParams), sessionId, {
|
|
8316
8572
|
permissionMode: session.modes.currentModeId,
|
|
8317
8573
|
replacingSession: session,
|
|
8574
|
+
...resumeAt,
|
|
8575
|
+
...(keepState ? { replayState: keepState } : {}),
|
|
8318
8576
|
});
|
|
8319
8577
|
const recreated = this.sessions[sessionId];
|
|
8320
8578
|
if (!recreated || recreated.tornDown)
|
|
@@ -8760,6 +9018,10 @@ export function v1AgentApp(logger, onAgent) {
|
|
|
8760
9018
|
.onRequest(methods.agent.providers.disable, (ctx) => agent.unstable_disableProvider(ctx.params))
|
|
8761
9019
|
.onRequest(methods.agent.logout, (ctx) => agent.logout(ctx.params))
|
|
8762
9020
|
.onRequest(methods.agent.auth.status, () => agent.authStatusResponse())
|
|
9021
|
+
.onRequest(SESSION_REWIND_METHOD, { parse: parseSessionRewindRequest },
|
|
9022
|
+
// Registered before `session/prompt`: the lock is taken in the same tick as the request,
|
|
9023
|
+
// so a prompt sent right after it waits in `startTurn`.
|
|
9024
|
+
ofRootSession("rewind", (ctx) => agent.rewindSession(ctx.params)))
|
|
8763
9025
|
.onRequest(methods.agent.session.prompt, ofRootSession("prompt", (ctx) => runPromptWithCancellation(agent, ctx.params, ctx.signal)))
|
|
8764
9026
|
.onNotification(methods.agent.session.cancel, (ctx) => agent.cancel(ctx.params))
|
|
8765
9027
|
.onRequest(STEER_METHOD, { parse: parseSteerRequest }, (ctx) => agent.steer(ctx.params))
|
package/dist/v2/agent.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/v2/agent.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAaxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/v2/agent.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAaxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AA8E3C,sEAAsE;AACtE,MAAM,WAAW,WAAW;IAC1B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED,8CAA8C;AAC9C,wBAAgB,UAAU,CACxB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,IAAI,GACpC,EAAE,CAAC,QAAQ,CA+Cb"}
|
package/dist/v2/agent.js
CHANGED
|
@@ -31,6 +31,7 @@ import { readHistoryAcrossCompactions, readResumedTail, resumedModelFromTranscri
|
|
|
31
31
|
import { mergeEffortSettings } from "../session-effort.js";
|
|
32
32
|
import { configuredSettings, resolveThinkingConfig } from "../session-env.js";
|
|
33
33
|
import { resolveInitialPermissionMode } from "../session-mode.js";
|
|
34
|
+
import { cutAtRewindPoint, prepareRewoundResume } from "../session-rewind.js";
|
|
34
35
|
import { sanitizeTitle } from "../session-titles.js";
|
|
35
36
|
import { renameSession } from "../session-index/rename.js";
|
|
36
37
|
import { parseRenameSessionRequest, transcriptWriter, } from "../session-index/service.js";
|
|
@@ -405,7 +406,8 @@ class V2Agent {
|
|
|
405
406
|
const { sessionId, replayFrom } = params;
|
|
406
407
|
// The replay: the messages before each compaction too, unless reading them fails.
|
|
407
408
|
const acrossCompactions = (chain, cwd) => {
|
|
408
|
-
|
|
409
|
+
// The rewind cut comes first: the dropped turns get no replay and no cursor.
|
|
410
|
+
const messages = chain.then(async (read) => readHistoryAcrossCompactions(sessionId, await cutAtRewindPoint(sessionId, read, this.logger), this.logger, cwd));
|
|
409
411
|
// A resume that fails before the replay leaves them unawaited.
|
|
410
412
|
chain.catch(() => { });
|
|
411
413
|
messages.catch(() => { });
|
|
@@ -930,6 +932,10 @@ class V2Agent {
|
|
|
930
932
|
async startQuery(sessionId, params, resume, history, persist, mcpServersRefused) {
|
|
931
933
|
const request = await validatedSetup(params);
|
|
932
934
|
const client = clientOptions(params._meta);
|
|
935
|
+
// A resume stops at a pending rewind point, or the dropped turns come back.
|
|
936
|
+
// The `session/options` probe (`persist: false`) leaves the transcript and
|
|
937
|
+
// `rewind.json` alone.
|
|
938
|
+
const resumeSessionAt = resume !== undefined && persist ? await prepareRewoundResume(resume, this.logger) : undefined;
|
|
933
939
|
const served = await this.mcpServersOf(sessionId, request, client, mcpServersRefused);
|
|
934
940
|
const mcpServers = served.configs;
|
|
935
941
|
// After a provider change that is still listing its models.
|
|
@@ -1080,6 +1086,7 @@ class V2Agent {
|
|
|
1080
1086
|
...STARTUP_FAILURE_RESULTS_ENV,
|
|
1081
1087
|
},
|
|
1082
1088
|
...(resume !== undefined ? { resume } : { sessionId }),
|
|
1089
|
+
...(resumeSessionAt !== undefined ? { resumeSessionAt } : {}),
|
|
1083
1090
|
...(persist ? {} : { persistSession: false }),
|
|
1084
1091
|
};
|
|
1085
1092
|
let q;
|
|
@@ -1207,7 +1214,7 @@ async function validatedSetup(params) {
|
|
|
1207
1214
|
* `sessionId`, as a replay reads it: the messages before each compaction too.
|
|
1208
1215
|
*/
|
|
1209
1216
|
async function storedPromptIds(sessionId, cwd, logger) {
|
|
1210
|
-
const messages = await readHistoryAcrossCompactions(sessionId, await getSessionMessages(sessionId, { dir: cwd }), logger, cwd);
|
|
1217
|
+
const messages = await readHistoryAcrossCompactions(sessionId, await cutAtRewindPoint(sessionId, await getSessionMessages(sessionId, { dir: cwd }), logger), logger, cwd);
|
|
1211
1218
|
return messages.flatMap((message) => message.type === "user" && message.uuid ? [message.uuid] : []);
|
|
1212
1219
|
}
|
|
1213
1220
|
/** A request of the active `session` names its `cwd`, as `session/resume` must. */
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "0.111.
|
|
6
|
+
"version": "0.111.1-preview.2",
|
|
7
7
|
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
|
|
8
8
|
"main": "dist/lib.js",
|
|
9
9
|
"types": "dist/lib.d.ts",
|
|
@@ -68,7 +68,7 @@
|
|
|
68
68
|
"node": ">=22"
|
|
69
69
|
},
|
|
70
70
|
"dependencies": {
|
|
71
|
-
"@agentclientprotocol/sdk": "2.
|
|
71
|
+
"@agentclientprotocol/sdk": "2.12.0",
|
|
72
72
|
"@anthropic-ai/claude-agent-sdk": "0.3.331",
|
|
73
73
|
"diff": "9.0.0",
|
|
74
74
|
"zod": "4.6.7"
|