@agentclientprotocol/claude-agent-acp 0.113.1-preview.9 → 0.114.0

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.
Files changed (61) hide show
  1. package/README.md +2 -0
  2. package/dist/query-settings.d.ts +42 -0
  3. package/dist/query-settings.d.ts.map +1 -0
  4. package/dist/query-settings.js +43 -0
  5. package/dist/resumed-session.d.ts +9 -2
  6. package/dist/resumed-session.d.ts.map +1 -1
  7. package/dist/resumed-session.js +51 -7
  8. package/dist/sdk-to-acp.js +4 -2
  9. package/dist/session-cursors.d.ts +1 -1
  10. package/dist/session-cursors.d.ts.map +1 -1
  11. package/dist/session-cursors.js +8 -2
  12. package/dist/session-index/transcript-scan.d.ts +13 -3
  13. package/dist/session-index/transcript-scan.d.ts.map +1 -1
  14. package/dist/session-index/transcript-scan.js +21 -5
  15. package/dist/session-mode.d.ts +31 -2
  16. package/dist/session-mode.d.ts.map +1 -1
  17. package/dist/session-mode.js +35 -5
  18. package/dist/session-model.d.ts +4 -1
  19. package/dist/session-model.d.ts.map +1 -1
  20. package/dist/session-model.js +26 -4
  21. package/dist/session-read.d.ts +45 -0
  22. package/dist/session-read.d.ts.map +1 -0
  23. package/dist/session-read.js +300 -0
  24. package/dist/session-rewind.d.ts +6 -2
  25. package/dist/session-rewind.d.ts.map +1 -1
  26. package/dist/session-rewind.js +13 -4
  27. package/dist/session-ultracode.d.ts +4 -1
  28. package/dist/session-ultracode.d.ts.map +1 -1
  29. package/dist/session-ultracode.js +14 -25
  30. package/dist/settings.d.ts +34 -0
  31. package/dist/settings.d.ts.map +1 -1
  32. package/dist/settings.js +55 -4
  33. package/dist/subagent-history.d.ts +9 -1
  34. package/dist/subagent-history.d.ts.map +1 -1
  35. package/dist/subagent-history.js +55 -13
  36. package/dist/v1/acp-agent.d.ts +6 -0
  37. package/dist/v1/acp-agent.d.ts.map +1 -1
  38. package/dist/v1/acp-agent.js +146 -72
  39. package/dist/v1/session-read.d.ts +31 -0
  40. package/dist/v1/session-read.d.ts.map +1 -0
  41. package/dist/v1/session-read.js +62 -0
  42. package/dist/v2/agent.d.ts.map +1 -1
  43. package/dist/v2/agent.js +62 -27
  44. package/dist/v2/config.d.ts +6 -5
  45. package/dist/v2/config.d.ts.map +1 -1
  46. package/dist/v2/config.js +4 -1
  47. package/dist/v2/session-read.d.ts +11 -0
  48. package/dist/v2/session-read.d.ts.map +1 -0
  49. package/dist/v2/session-read.js +28 -0
  50. package/dist/v2/setup.d.ts +4 -1
  51. package/dist/v2/setup.d.ts.map +1 -1
  52. package/dist/v2/setup.js +4 -2
  53. package/dist/v2/stream.d.ts +9 -13
  54. package/dist/v2/stream.d.ts.map +1 -1
  55. package/dist/v2/stream.js +10 -9
  56. package/dist/v2/subagent-replay.d.ts +16 -4
  57. package/dist/v2/subagent-replay.d.ts.map +1 -1
  58. package/dist/v2/subagent-replay.js +22 -10
  59. package/dist/v2/tasks.d.ts.map +1 -1
  60. package/dist/v2/tasks.js +5 -3
  61. package/package.json +1 -1
@@ -28,9 +28,10 @@ import { answerAskUserQuestion, answerMcpElicitation, answerUserDialog, elicitUn
28
28
  import { startMcpServerAuthentication as startSharedMcpServerAuthentication, supportsMcpOAuth, } from "../mcp-oauth.js";
29
29
  import { forkSession } from "../fork-session.js";
30
30
  import { anchoredForkCursorUpdate, forkCursorUpdate, hasForkCursor, LastReportedEntity, promptGetsCursor, withRewindCapability, } from "../session-cursors.js";
31
+ import { SESSION_READ_CAPABILITY, SESSION_READ_METHOD } from "../session-read.js";
31
32
  import { cutAtRewindPoint, loadRewindableHistory, parseSessionRewindRequest, prepareRewoundResume, rewindSession, SESSION_REWIND_METHOD, } from "../session-rewind.js";
32
33
  import { clientSystemPrompt, sessionSystemPrompt, SYSTEM_PROMPT_CAPABILITY, } from "../client-system-prompt.js";
33
- import { readSubagentMessages, subagentHistory, subagentLaunchIds, subagentLaunchedBy, subagentLineage, } from "../subagent-history.js";
34
+ import { readSubagentMessages, readSubagentMessagesOrFail, subagentHistory, subagentLaunchIds, subagentLaunchedBy, subagentLineage, } from "../subagent-history.js";
34
35
  import { RfdSubagentReplay, ReplayTranscript, replaySubagentTerminalState, } from "../subagent-replay.js";
35
36
  import { readHistoryAcrossCompactions, readResumedSession, readResumedTail, } from "../resumed-session.js";
36
37
  import { SessionTiming } from "../session-timing.js";
@@ -55,6 +56,7 @@ import { addModelUsage, getMatchingModelUsage, modelUsageIncrement, normalizeMod
55
56
  import { previewPatchContent } from "../diff.js";
56
57
  import { backgroundedBashToolCall, withRunningTerminal, withStreamedTerminal, } from "../tool-calls/background.js";
57
58
  import { ChangedMetaClient, ClientConnection } from "./client-connection.js";
59
+ import { V1SessionReads } from "./session-read.js";
58
60
  import { ToolCallFieldTracker } from "../tool-calls/field-tracker.js";
59
61
  import { RetractedToolCalls } from "../tool-calls/retracted.js";
60
62
  import { ClientCapabilities as ToolCallClientCapabilities } from "../tool-calls/client-capabilities.js";
@@ -67,11 +69,12 @@ import { taskNotificationsOf } from "../task-notifications.js";
67
69
  import { formatUsageResponse, isUsageCommandText, parseUsageResponse } from "../usage-markdown.js";
68
70
  import { parseMcpCommand, runMcpCommand } from "../mcp-command.js";
69
71
  import { configuredSettings, resolveThinkingConfig } from "../session-env.js";
70
- import { MODE_CONFIG_ID, resolveInitialPermissionMode, SessionModeManager, } from "../session-mode.js";
72
+ import { MODE_CONFIG_ID, resolveInitialPermissionMode, SessionModeManager, startModeUnderPolicy, } from "../session-mode.js";
71
73
  import { aliasResumedModelRow, applyAvailableModelsAllowlist, getAvailableModels, MODEL_CONFIG_ID, modelDisplayName, modelEntryFor, narrowToGatewayModels, resolveModelPreference, withCurrentModelInfo, } from "../session-model.js";
72
74
  import { applyProviderRoute, createEnvForProvider, defaultProviderConfig, gatewayRequestToProviderConfig, isGatewayAuthMethod, listProvidersResponse, loggableBaseUrl, PROVIDER_ID, providerConfigFromSetRequest, providerRouteSettings, validatedGatewayAuthRequest, withListedModels, } from "../providers.js";
73
75
  import { EFFORT_CONFIG_ID, effortFlagSettings, effortForModelSwitch, mergeEffortSettings, settleEffortAfterModelSwitch, settingsEffortForModel, withoutEffort, } from "../session-effort.js";
74
76
  import { createUltracodeConfigOption, readSettingsReport, ULTRACODE_CONFIG_ID, ultracodeSupported, ultracodeWorkflowsEnabled, } from "../session-ultracode.js";
77
+ import { followQueryPolicy } from "../query-settings.js";
75
78
  import { buildConfigOptions, clientSupportsBooleanConfigOptions, clientSupportsRecommendedConfigValue, configOptionValue, setSelectedModel, discoverCustomAgents, } from "../session-config-options.js";
76
79
  import { applyFastModeFlag, createFastModeConfigOption, FAST_MODE_CONFIG_ID, fastModeResultIsNews, fastModeStateChange, fastModeStateEnabled, normalizeFastModeDisabledReason, } from "../session-fast-mode.js";
77
80
  import { cacheResultContextWindow, clearContextWindowCache, immediateContextWindow, providerCacheKeyFor, readContextWindow, } from "../context-window.js";
@@ -409,6 +412,7 @@ export class ClaudeAcpAgent {
409
412
  announcedChildren = new AnnouncedChildren();
410
413
  /** What anchors a live cursor: the last entity that the client holds per session. */
411
414
  lastEntities = new LastReportedEntity();
415
+ sessionReads;
412
416
  /**
413
417
  * AIR's draft: the model that the last load of each session replayed to each
414
418
  * child session, as the model id and the entry that went out. See
@@ -457,6 +461,7 @@ export class ClaudeAcpAgent {
457
461
  mcp = new McpOverAcp()) {
458
462
  this.mcp = mcp;
459
463
  this.sessions = {};
464
+ this.sessionReads = new V1SessionReads(client);
460
465
  this.client = new ChangedMetaClient(client, () => this.toolCallCapabilities.air.client, (update) => {
461
466
  // Before the client can name the child that a `subagent_update` announces.
462
467
  this.announcedChildren.sending(update);
@@ -635,6 +640,7 @@ export class ClaudeAcpAgent {
635
640
  // Only AIR gets the AIR capabilities and the goal capability, under
636
641
  // `jetbrains.air`.
637
642
  _meta: {
643
+ sessionRead: SESSION_READ_CAPABILITY,
638
644
  ...(this.toolCallCapabilities.air.client
639
645
  ? 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)
640
646
  ? [AIR_SESSION_REWIND_CAPABILITY]
@@ -654,15 +660,15 @@ export class ClaudeAcpAgent {
654
660
  // Without `configOptions`: a restart of the query restores the session's choices itself.
655
661
  const { configOptions, ...request } = params;
656
662
  const initial = initialConfigOptions(configOptions);
657
- while (this.providerUpdate)
658
- await this.providerUpdate;
659
- const created = await this.createSession(request, {
660
- // Revisit these meta values once we support resume
661
- resume: params._meta?.claudeCode?.options?.resume,
663
+ const resume = params._meta?.claudeCode?.options?.resume;
664
+ return this.sessionReads.transition(resume, "open", async () => {
665
+ while (this.providerUpdate)
666
+ await this.providerUpdate;
667
+ const created = await this.createSession(request, { resume });
668
+ const response = await this.withInitialConfigOptions(created, initial);
669
+ this.afterSetupResponse(response.sessionId, params.mcpServers);
670
+ return response;
662
671
  });
663
- const response = await this.withInitialConfigOptions(created, initial);
664
- this.afterSetupResponse(response.sessionId, params.mcpServers);
665
- return response;
666
672
  }
667
673
  /**
668
674
  * `session/options`: the modes and config options that `session/new` with
@@ -719,17 +725,7 @@ export class ClaudeAcpAgent {
719
725
  async createSessionWhileReplaying(params, timing) {
720
726
  await this.validateCwd(params.cwd, params.additionalDirectories);
721
727
  clientSystemPrompt(params.systemPrompt);
722
- const pending = {
723
- state: {
724
- cwd: params.cwd,
725
- taskState: new Map(),
726
- subagentChecklists: new Set(),
727
- forwardSubagentText: this.forwardsSubagentText(params._meta),
728
- messageIdToUuid: new Map(),
729
- sessionFailureState: createSessionFailureState(),
730
- },
731
- stopped: false,
732
- };
728
+ const pending = this.pendingReplay(params.cwd, params._meta);
733
729
  const transcript = readResumedSession(params.sessionId, this.logger);
734
730
  const replay = transcript
735
731
  .then(({ messages }) => this.replaySessionHistory(params.sessionId, messages, pending))
@@ -790,16 +786,18 @@ export class ClaudeAcpAgent {
790
786
  // The fork row can lack `forkedFrom`: the scan reads it from the first
791
787
  // 64 KB of the transcript only. So the fork is held back by its id too.
792
788
  this.sessionIndex.onForkCreated(params.sessionId, sessionId);
793
- const { modes, configOptions } = await this.withInitialConfigOptions(await this.getOrCreateSession({
794
- sessionId,
795
- cwd: params.cwd,
796
- mcpServers: params.mcpServers,
797
- additionalDirectories: params.additionalDirectories,
798
- systemPrompt: params.systemPrompt,
799
- _meta: params._meta,
800
- }), initial);
801
- this.afterSetupResponse(sessionId, params.mcpServers ?? []);
802
- return { sessionId, modes, configOptions };
789
+ return this.sessionReads.transition(sessionId, "open", async () => {
790
+ const { modes, configOptions } = await this.withInitialConfigOptions(await this.getOrCreateSession({
791
+ sessionId,
792
+ cwd: params.cwd,
793
+ mcpServers: params.mcpServers,
794
+ additionalDirectories: params.additionalDirectories,
795
+ systemPrompt: params.systemPrompt,
796
+ _meta: params._meta,
797
+ }), initial);
798
+ this.afterSetupResponse(sessionId, params.mcpServers ?? []);
799
+ return { sessionId, modes, configOptions };
800
+ });
803
801
  }
804
802
  /** Runs `fork`, the handler of a `session/fork` request of `sourceId`,
805
803
  * with its forks held back from the session list (see
@@ -885,14 +883,19 @@ export class ClaudeAcpAgent {
885
883
  });
886
884
  }
887
885
  async resumeSession(params) {
888
- const initial = initialConfigOptions(params.configOptions);
889
- while (this.providerUpdate)
890
- await this.providerUpdate;
891
- const result = await this.withInitialConfigOptions(await this.getOrCreateSession(params), initial);
892
- this.afterSetupResponse(params.sessionId, params.mcpServers ?? []);
893
- return result;
886
+ return this.sessionReads.transition(params.sessionId, "open", async () => {
887
+ const initial = initialConfigOptions(params.configOptions);
888
+ while (this.providerUpdate)
889
+ await this.providerUpdate;
890
+ const result = await this.withInitialConfigOptions(await this.getOrCreateSession(params), initial);
891
+ this.afterSetupResponse(params.sessionId, params.mcpServers ?? []);
892
+ return result;
893
+ });
894
+ }
895
+ loadSession(params) {
896
+ return this.sessionReads.transition(params.sessionId, "open", () => this.loadAndReplay(params));
894
897
  }
895
- async loadSession(params) {
898
+ async loadAndReplay(params) {
896
899
  const timing = new SessionTiming(this.logger, "load", params.sessionId);
897
900
  const initial = initialConfigOptions(params.configOptions);
898
901
  while (this.providerUpdate)
@@ -913,6 +916,17 @@ export class ClaudeAcpAgent {
913
916
  this.afterSetupResponse(params.sessionId, params.mcpServers ?? []);
914
917
  return result;
915
918
  }
919
+ readSession(params, signal) {
920
+ return this.sessionReads.read(params, {
921
+ capabilities: this.clientCapabilities,
922
+ airClient: this.toolCallCapabilities.air.client,
923
+ signal,
924
+ isOpen: (sessionId) => Object.hasOwn(this.sessions, sessionId),
925
+ assertRoot: (sessionId) => this.assertNoChildSession(sessionId, "read"),
926
+ clientTitle: (title) => this.sessionIndex.clientTitle(title),
927
+ render: (sessionId, cwd, replay) => this.replaySessionHistory(sessionId, undefined, this.pendingReplay(cwd), replay),
928
+ });
929
+ }
916
930
  /**
917
931
  * One page of the sessions, newest first. The cursor is the offset of the
918
932
  * page. The SDK then orders the transcripts by their modification time and
@@ -6144,6 +6158,7 @@ export class ClaudeAcpAgent {
6144
6158
  }
6145
6159
  /** Tear down all active sessions. Called when the ACP connection closes. */
6146
6160
  async dispose() {
6161
+ this.sessionReads.dispose();
6147
6162
  this.sessionIndex.dispose();
6148
6163
  await Promise.all(Object.keys(this.sessions).map((id) => this.teardownSession(id)));
6149
6164
  }
@@ -6162,8 +6177,10 @@ export class ClaudeAcpAgent {
6162
6177
  }
6163
6178
  /** Idempotent: a session that is not loaded here is already closed. */
6164
6179
  async closeSession(params) {
6165
- await this.endSession(params.sessionId);
6166
- return {};
6180
+ return this.sessionReads.transition(params.sessionId, "close", async () => {
6181
+ await this.endSession(params.sessionId);
6182
+ return {};
6183
+ });
6167
6184
  }
6168
6185
  /**
6169
6186
  * `session/status`: `open` for a session that this connection holds. A held
@@ -6185,7 +6202,7 @@ export class ClaudeAcpAgent {
6185
6202
  }
6186
6203
  /** Per client: see {@link sessionIndex.SessionIndexConnection.deleteSession}. */
6187
6204
  async deleteSession(params) {
6188
- return this.sessionIndex.deleteSession(params);
6205
+ return this.sessionReads.transition(params.sessionId, "close", () => this.sessionIndex.deleteSession(params));
6189
6206
  }
6190
6207
  setSessionMode(params) {
6191
6208
  return this.serializeConfigurationChange(params.sessionId, () => this.sessionModes.setSessionMode(params));
@@ -6242,15 +6259,34 @@ export class ClaudeAcpAgent {
6242
6259
  await this.applyConfigOptionValue(params.sessionId, session, params.configId, effectiveValue, duringSetup);
6243
6260
  return { configOptions: session.configOptions };
6244
6261
  }
6245
- async replaySessionHistory(sessionId, resumedMessages, pending) {
6262
+ pendingReplay(cwd, meta) {
6263
+ return {
6264
+ state: {
6265
+ cwd,
6266
+ taskState: new Map(),
6267
+ subagentChecklists: new Set(),
6268
+ forwardSubagentText: this.forwardsSubagentText(meta),
6269
+ messageIdToUuid: new Map(),
6270
+ sessionFailureState: createSessionFailureState(),
6271
+ },
6272
+ stopped: false,
6273
+ };
6274
+ }
6275
+ async replaySessionHistory(sessionId, resumedMessages, pending, detached) {
6246
6276
  const replayStartedAt = performance.now();
6247
6277
  const toolUseCache = {};
6278
+ const publish = detached?.publish ??
6279
+ ((notification) => this.client.sessionUpdate(notification));
6248
6280
  // A replay rebuilds the client's entities, and its cursors anchor to those.
6249
- this.lastEntities.forget(sessionId);
6281
+ if (!detached)
6282
+ this.lastEntities.forget(sessionId);
6250
6283
  // A load replays the messages before each compaction too, unless reading them fails.
6251
6284
  // The rewind cut comes first: the dropped turns get no replay and no cursor.
6252
- const current = await cutAtRewindPoint(sessionId, resumedMessages ?? (await getSessionMessages(sessionId)), this.logger);
6253
- const messages = await readHistoryAcrossCompactions(sessionId, current, this.logger);
6285
+ const current = detached?.messages ??
6286
+ (await cutAtRewindPoint(sessionId, resumedMessages ?? (await getSessionMessages(sessionId)), this.logger));
6287
+ const messages = detached
6288
+ ? current
6289
+ : await readHistoryAcrossCompactions(sessionId, current, this.logger);
6254
6290
  // A cursor whose resume point a compaction left out cannot be rewound to.
6255
6291
  const currentUuids = new Set(current.map((message) => message.uuid));
6256
6292
  const historyLoadedAt = performance.now();
@@ -6276,12 +6312,14 @@ export class ClaudeAcpAgent {
6276
6312
  state: session.sessionFailureState,
6277
6313
  capabilities: this.clientCapabilities,
6278
6314
  isCurrent: () => {
6315
+ if (detached)
6316
+ return !detached.signal.aborted;
6279
6317
  const live = this.sessions[sessionId];
6280
6318
  if (!live)
6281
6319
  return pending !== undefined && !pending.stopped;
6282
6320
  return live.sessionFailureState === session.sessionFailureState;
6283
6321
  },
6284
- sendUpdate: (notification) => this.client.sessionUpdate(notification),
6322
+ sendUpdate: publish,
6285
6323
  logger: this.logger,
6286
6324
  })
6287
6325
  : undefined;
@@ -6299,6 +6337,12 @@ export class ClaudeAcpAgent {
6299
6337
  // no model to the list, and each child's model is its id until the load
6300
6338
  // response refines it (see `publishCurrentSubagentStates`).
6301
6339
  const replayModels = pending ? undefined : this.subagentModels(sessionId);
6340
+ const readSubagentHistory = () => detached
6341
+ ? subagentHistory(sessionId, { strict: true, transcript: detached.transcript })
6342
+ : subagentHistory(sessionId);
6343
+ const readChildMessages = (agentId, history, launchId) => detached
6344
+ ? readSubagentMessagesOrFail(sessionId, agentId, history, launchId)
6345
+ : readSubagentMessages(sessionId, agentId, history, this.logger);
6302
6346
  // Registers the Agent and Task launches of `list`, and the terminal state
6303
6347
  // of each launch from its tool_result.
6304
6348
  const registerLaunches = (list) => {
@@ -6381,7 +6425,7 @@ export class ClaudeAcpAgent {
6381
6425
  const parentSessionId = child.parentToolUseId
6382
6426
  ? (replayChildren.get(child.parentToolUseId)?.sessionId ?? sessionId)
6383
6427
  : sessionId;
6384
- await this.client.sessionUpdate(asSdkSessionNotification({
6428
+ await publish(asSdkSessionNotification({
6385
6429
  sessionId: parentSessionId,
6386
6430
  update: {
6387
6431
  sessionUpdate: "subagent_spawned",
@@ -6397,7 +6441,7 @@ export class ClaudeAcpAgent {
6397
6441
  };
6398
6442
  // Only a history with an Agent or Task launch has subagent transcripts to read.
6399
6443
  const subagents = nativeReplayEnabled && replayChildren.size > 0
6400
- ? await subagentHistory(sessionId)
6444
+ ? await readSubagentHistory()
6401
6445
  : { agents: new Map() };
6402
6446
  const airReplay = nativeReplayEnabled ? new ReplayTranscript(subagents) : undefined;
6403
6447
  airReplay?.scan(messages, sessionId);
@@ -6405,10 +6449,10 @@ export class ClaudeAcpAgent {
6405
6449
  const rfdHistory = form === "rfd" &&
6406
6450
  messages.some((message) => subagentLaunchIds(message.message?.content)
6407
6451
  .length > 0)
6408
- ? await subagentHistory(sessionId)
6452
+ ? await readSubagentHistory()
6409
6453
  : { agents: new Map() };
6410
6454
  const rfdReplay = form === "rfd"
6411
- ? new RfdSubagentReplay(rfdHistory, (notification) => this.client.sessionUpdate(asSdkSessionNotification(notification)), this.subagentModels(sessionId), session?.cwd)
6455
+ ? new RfdSubagentReplay(rfdHistory, publish, detached ? undefined : this.subagentModels(sessionId), session?.cwd)
6412
6456
  : undefined;
6413
6457
  rfdReplay?.scan(messages, sessionId);
6414
6458
  // History persists no task_started frame, so a background task gets its
@@ -6418,7 +6462,7 @@ export class ClaudeAcpAgent {
6418
6462
  // The tool cache forgets a tool use at its result, but a notification
6419
6463
  // comes later and needs the tool use that started the task.
6420
6464
  const replayToolUses = new Map();
6421
- const replayAsyncTasks = new AsyncTaskRuntime(clientSupportsAsyncTasks(this.clientCapabilities), sessionId, async (notification) => this.client.sessionUpdate(asSdkSessionNotification(notification)), {
6465
+ const replayAsyncTasks = new AsyncTaskRuntime(clientSupportsAsyncTasks(this.clientCapabilities), sessionId, publish, {
6422
6466
  routeOf: (toolCallId) => {
6423
6467
  const target = replayToolUses.get(toolCallId)?.sessionId;
6424
6468
  return target && target !== sessionId
@@ -6464,6 +6508,7 @@ export class ClaudeAcpAgent {
6464
6508
  const pause = messageLoopYielder.maybeYield();
6465
6509
  if (pause)
6466
6510
  await pause;
6511
+ detached?.signal.throwIfAborted();
6467
6512
  if (pending?.stopped || isReplayHiddenMetaMessage(message)) {
6468
6513
  return;
6469
6514
  }
@@ -6529,7 +6574,7 @@ export class ClaudeAcpAgent {
6529
6574
  if (replayChild?.announced && entry && !sameModelEntry(replayChild.model, entry)) {
6530
6575
  replayChild.responseModel = model;
6531
6576
  replayChild.model = entry;
6532
- await this.client.sessionUpdate({
6577
+ await publish({
6533
6578
  sessionId: replayChild.sessionId,
6534
6579
  update: {
6535
6580
  sessionUpdate: "config_option_update",
@@ -6580,7 +6625,10 @@ export class ClaudeAcpAgent {
6580
6625
  // A subagent's own compaction summary is not the root session's.
6581
6626
  if (replayCompactionUpdates &&
6582
6627
  parentToolUseId === null &&
6583
- (await replayCompactSummary(message, (notification) => this.client.sessionUpdate(notification), { sessionId, airClient: this.toolCallCapabilities.air.client }))) {
6628
+ (await replayCompactSummary(message, publish, {
6629
+ sessionId,
6630
+ airClient: this.toolCallCapabilities.air.client,
6631
+ }))) {
6584
6632
  return;
6585
6633
  }
6586
6634
  for (const notification of toAcpNotifications(
@@ -6612,7 +6660,7 @@ export class ClaudeAcpAgent {
6612
6660
  : undefined;
6613
6661
  if (handback !== undefined) {
6614
6662
  if (handback !== null) {
6615
- await this.client.sessionUpdate({
6663
+ await publish({
6616
6664
  sessionId: replayTargetSessionId,
6617
6665
  update: {
6618
6666
  sessionUpdate: "agent_message_chunk",
@@ -6624,7 +6672,7 @@ export class ClaudeAcpAgent {
6624
6672
  continue;
6625
6673
  }
6626
6674
  const replayed = { ...notification, sessionId: replayTargetSessionId };
6627
- await this.client.sessionUpdate(rfdReplay
6675
+ await publish(rfdReplay
6628
6676
  ? asSdkSessionNotification(rfdReplay.withTarget(replayed, replayTargetSessionId))
6629
6677
  : replayed);
6630
6678
  }
@@ -6638,7 +6686,7 @@ export class ClaudeAcpAgent {
6638
6686
  if (!agentId || replayedSubagents.has(agentId))
6639
6687
  continue;
6640
6688
  replayedSubagents.add(agentId);
6641
- const childMessages = await readSubagentMessages(sessionId, agentId, subagents, this.logger);
6689
+ const childMessages = await readChildMessages(agentId, subagents, toolUseId);
6642
6690
  registerLaunches(childMessages);
6643
6691
  airReplay?.scan(childMessages, agentId);
6644
6692
  for (const childMessage of childMessages)
@@ -6652,7 +6700,7 @@ export class ClaudeAcpAgent {
6652
6700
  const launched = rfdReplay.childOfLaunch(toolUseId);
6653
6701
  if (!launched || launched.announced)
6654
6702
  continue;
6655
- const childMessages = await readSubagentMessages(sessionId, launched.sessionId, rfdHistory, this.logger);
6703
+ const childMessages = await readChildMessages(launched.sessionId, rfdHistory, toolUseId);
6656
6704
  await rfdReplay.announce(launched);
6657
6705
  rfdReplay.scan(childMessages, launched.sessionId);
6658
6706
  for (const childMessage of childMessages)
@@ -6663,20 +6711,30 @@ export class ClaudeAcpAgent {
6663
6711
  };
6664
6712
  for (const [index, message] of messages.entries()) {
6665
6713
  // Before the message's own chunk: the cursor lies before the message.
6666
- const before = this.lastEntities.last(sessionId);
6714
+ const before = detached ? undefined : this.lastEntities.last(sessionId);
6667
6715
  await replayMessage(message);
6668
6716
  // A task notification record is no user message to the client (see `replayMessage`).
6669
6717
  if (!pending?.stopped &&
6670
6718
  hasForkCursor(messages, index) &&
6671
6719
  !isTaskNotificationRecord(message)) {
6672
- this.announceCursor(sessionId, forkCursorUpdate(message.uuid), before, {
6673
- rewindable: currentUuids.has(messages[index - 1].uuid),
6674
- });
6720
+ const update = forkCursorUpdate(message.uuid);
6721
+ if (detached) {
6722
+ if (this.clientCapabilities?.session?.cursors != null) {
6723
+ await publish({ sessionId, update });
6724
+ }
6725
+ }
6726
+ else {
6727
+ this.announceCursor(sessionId, update, before, {
6728
+ rewindable: currentUuids.has(messages[index - 1].uuid),
6729
+ });
6730
+ }
6675
6731
  }
6676
6732
  }
6733
+ detached?.endHistory();
6677
6734
  if (rfdReplay && !pending?.stopped) {
6678
6735
  await rfdReplay.finish(clientSupportsNotices(this.clientCapabilities), sessionId);
6679
- this.replayedSubagents.set(sessionId, rfdReplay);
6736
+ if (!detached)
6737
+ this.replayedSubagents.set(sessionId, rfdReplay);
6680
6738
  }
6681
6739
  if (nativeReplayEnabled && !pending?.stopped) {
6682
6740
  const childModels = new Map();
@@ -6685,7 +6743,7 @@ export class ClaudeAcpAgent {
6685
6743
  childModels.set(child.sessionId, { model: child.responseModel, sent: child.model });
6686
6744
  }
6687
6745
  }
6688
- if (childModels.size > 0)
6746
+ if (!detached && childModels.size > 0)
6689
6747
  this.replayedChildModels.set(sessionId, childModels);
6690
6748
  // Claude history persists sidechain messages and Agent/Task tool uses,
6691
6749
  // but not task_started/task_updated lifecycle frames. Recover terminal
@@ -6697,7 +6755,7 @@ export class ClaudeAcpAgent {
6697
6755
  const parentSessionId = child.parentToolUseId
6698
6756
  ? (replayChildren.get(child.parentToolUseId)?.sessionId ?? sessionId)
6699
6757
  : sessionId;
6700
- await this.client.sessionUpdate(asSdkSessionNotification({
6758
+ await publish(asSdkSessionNotification({
6701
6759
  sessionId: parentSessionId,
6702
6760
  update: {
6703
6761
  sessionUpdate: "subagent_state_update",
@@ -6714,9 +6772,10 @@ export class ClaudeAcpAgent {
6714
6772
  // A client with `loadReplayEnd` gets one more update after the whole
6715
6773
  // replay, the subagent history included. A stopped replay (the CLI start
6716
6774
  // failed) does not get it, and a failed replay throws before this line.
6717
- if (!pending?.stopped &&
6775
+ if (!detached &&
6776
+ !pending?.stopped &&
6718
6777
  clientSupportsAirCapability(this.clientCapabilities, AIR_LOAD_REPLAY_END_CAPABILITY)) {
6719
- await this.client.sessionUpdate({
6778
+ await publish({
6720
6779
  sessionId,
6721
6780
  // No `title` and no `updatedAt`: `null` would clear them.
6722
6781
  update: {
@@ -7982,10 +8041,11 @@ export class ClaudeAcpAgent {
7982
8041
  settingsManager.getSettings().permissions?.disableBypassPermissionsMode !== "disable" &&
7983
8042
  sessionMeta?.claudeCode?.options?.allowDangerouslySkipPermissions !== false;
7984
8043
  const allowAuto = !autoModeDisabled(settingsManager.getSettings());
8044
+ const spawnSettings = settingsManager.getSettings();
7985
8045
  const { mode: initialPermissionMode, builtInDefault: builtInPermissionMode } = resolveInitialPermissionMode({
7986
8046
  explicit: creationOpts.permissionMode,
7987
8047
  resumed: resumedPermissionMode,
7988
- defaultMode: settingsManager.getSettings().permissions?.defaultMode,
8048
+ defaultMode: spawnSettings.permissions?.defaultMode,
7989
8049
  }, this.logger, { allowBypass, allowAuto });
7990
8050
  const userProvidedOptions = sessionMeta?.claudeCode?.options;
7991
8051
  const forwardSubagentText = this.forwardsSubagentText(params._meta);
@@ -8368,6 +8428,18 @@ export class ClaudeAcpAgent {
8368
8428
  if (route)
8369
8429
  await applyProviderRoute(q, route);
8370
8430
  timing.phase("sdk-initialize");
8431
+ // From here on the settings include the policy the CLI applies, which
8432
+ // the host resolver can miss (see `followCliPolicy`). The SDK's bypass
8433
+ // flag stays as it was decided before the CLI started. The mode is
8434
+ // decided again: `sessionModes.initialize` sets it on the query below.
8435
+ const cliSettings = await followQueryPolicy(q, settingsManager, this.logger);
8436
+ const startMode = startModeUnderPolicy({
8437
+ allowBypass,
8438
+ allowAuto,
8439
+ mode: initialPermissionMode,
8440
+ builtInDefault: builtInPermissionMode,
8441
+ }, { explicit: creationOpts.permissionMode, resumed: resumedPermissionMode }, { atStart: spawnSettings, withPolicy: settingsManager.getSettings() }, this.logger);
8442
+ timing.phase("cli-settings");
8371
8443
  // Publish the identity BEFORE the guard can refuse this session. A
8372
8444
  // refusal is exactly when the client most needs to know which account it
8373
8445
  // was refused for.
@@ -8415,7 +8487,7 @@ export class ClaudeAcpAgent {
8415
8487
  const allowedModels = resolvedProvider?.listedModels
8416
8488
  ? narrowToGatewayModels(settingsAllowedModels, resolvedProvider.listedModels, resolvedProvider.bedrockRegionPrefix)
8417
8489
  : settingsAllowedModels;
8418
- const models = await getAvailableModels(q, allowedModels, initializationResult.models, settingsManager, this.logger, creationOpts.resume !== undefined, sessionId, resumedModel, resolvedProvider?.listedModels !== undefined);
8490
+ const models = await getAvailableModels(q, allowedModels, initializationResult.models, settingsManager, this.logger, creationOpts.resume !== undefined, sessionId, resumedModel, resolvedProvider?.listedModels !== undefined, cliSettings);
8419
8491
  timing.phase("models");
8420
8492
  // Resolve the current model's capabilities separately from the stable
8421
8493
  // permission-mode catalog advertised to ACP clients (see
@@ -8423,12 +8495,13 @@ export class ClaudeAcpAgent {
8423
8495
  const { allowlistedModelInfo, currentModelInfo, modelInfos } = withCurrentModelInfo(allowedModels, sdkModels, models.currentModelId);
8424
8496
  const { modes, autoModeFallbackWarningPending } = await this.sessionModes.initialize({
8425
8497
  query: q,
8426
- requestedMode: initialPermissionMode,
8427
- builtInDefault: builtInPermissionMode,
8498
+ requestedMode: startMode.mode,
8499
+ builtInDefault: startMode.builtInDefault,
8500
+ startedIn: initialPermissionMode,
8428
8501
  currentModelInfo,
8429
8502
  currentModelId: models.currentModelId,
8430
- allowBypass,
8431
- allowAuto,
8503
+ allowBypass: startMode.allowBypass,
8504
+ allowAuto: startMode.allowAuto,
8432
8505
  });
8433
8506
  timing.phase("modes");
8434
8507
  const agents = await discoverCustomAgents(q);
@@ -9126,6 +9199,7 @@ export function v1AgentApp(logger, onAgent) {
9126
9199
  .onRequest(methods.agent.initialize, (ctx) => agent.initialize(ctx.params))
9127
9200
  .onRequest(methods.agent.session.new, (ctx) => agent.newSession(ctx.params))
9128
9201
  .onRequest(methods.agent.session.load, ofRootSession("load", (ctx) => agent.loadSession(ctx.params)))
9202
+ .onRequest(SESSION_READ_METHOD, { parse: (params) => params }, (ctx) => agent.readSession(ctx.params, ctx.signal))
9129
9203
  .onRequest(methods.agent.session.fork, ofRootSession("fork", (ctx) => agent.forking(ctx.params.sessionId, () => agent.unstable_forkSession(ctx.params))))
9130
9204
  .onRequest(methods.agent.session.list, (ctx) => agent.listSessions(ctx.params))
9131
9205
  .onRequest(methods.agent.session.delete, ofRootSession("delete", (ctx) => agent.deleteSession(ctx.params)))
@@ -0,0 +1,31 @@
1
+ import type { ClientCapabilities } from "@agentclientprotocol/sdk/unstable";
2
+ import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk";
3
+ import type { AcpClient } from "../acp-client.js";
4
+ /** A render whose updates are held until the read cursor is validated. */
5
+ export type DetachedReplay = {
6
+ messages: SessionMessage[];
7
+ transcript: string;
8
+ publish: AcpClient["sessionUpdate"];
9
+ endHistory: () => void;
10
+ signal: AbortSignal;
11
+ };
12
+ export declare class V1SessionReads {
13
+ private readonly client;
14
+ private readonly reads;
15
+ private readonly closed;
16
+ constructor(client: Pick<AcpClient, "sessionUpdate">);
17
+ dispose(): void;
18
+ readonly transition: <T>(sessionId: string | undefined, kind: "open" | "close", run: () => Promise<T>) => Promise<T>;
19
+ read(params: unknown, options: {
20
+ capabilities: ClientCapabilities | undefined;
21
+ airClient: boolean;
22
+ signal?: AbortSignal;
23
+ isOpen: (sessionId: string) => boolean;
24
+ assertRoot: (sessionId: string) => void;
25
+ clientTitle: (title: string) => string;
26
+ render: (sessionId: string, cwd: string, replay: DetachedReplay) => Promise<void>;
27
+ }): Promise<{
28
+ cursorId?: string;
29
+ }>;
30
+ }
31
+ //# sourceMappingURL=session-read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-read.d.ts","sourceRoot":"","sources":["../../src/v1/session-read.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAuB,MAAM,mCAAmC,CAAC;AACjG,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAKlD,0EAA0E;AAC1E,MAAM,MAAM,cAAc,GAAG;IAC3B,QAAQ,EAAE,cAAc,EAAE,CAAC;IAC3B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,SAAS,CAAC,eAAe,CAAC,CAAC;IACpC,UAAU,EAAE,MAAM,IAAI,CAAC;IACvB,MAAM,EAAE,WAAW,CAAC;CACrB,CAAC;AAEF,qBAAa,cAAc;IAIb,OAAO,CAAC,QAAQ,CAAC,MAAM;IAHnC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAsB;IAC5C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAyB;gBAEnB,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,eAAe,CAAC;IAErE,OAAO,IAAI,IAAI;IAIf,QAAQ,CAAC,UAAU,kGAA0C;IAE7D,IAAI,CACF,MAAM,EAAE,OAAO,EACf,OAAO,EAAE;QACP,YAAY,EAAE,kBAAkB,GAAG,SAAS,CAAC;QAC7C,SAAS,EAAE,OAAO,CAAC;QACnB,MAAM,CAAC,EAAE,WAAW,CAAC;QACrB,MAAM,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC;QACvC,UAAU,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAC;QACxC,WAAW,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAC;QACvC,MAAM,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACnF,GACA,OAAO,CAAC;QAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAiDlC"}
@@ -0,0 +1,62 @@
1
+ import { readSessionTranscript, SessionReads } from "../session-read.js";
2
+ import { ChangedMetaFilter } from "./tool-calls/changed-meta-filter.js";
3
+ export class V1SessionReads {
4
+ client;
5
+ reads = new SessionReads();
6
+ closed = new AbortController();
7
+ constructor(client) {
8
+ this.client = client;
9
+ }
10
+ dispose() {
11
+ this.closed.abort();
12
+ }
13
+ transition = this.reads.transition.bind(this.reads);
14
+ read(params, options) {
15
+ const signal = options.signal
16
+ ? AbortSignal.any([options.signal, this.closed.signal])
17
+ : this.closed.signal;
18
+ return this.reads.read(params, {
19
+ protocol: 1,
20
+ capabilities: options.capabilities,
21
+ cursors: options.capabilities?.session?.cursors != null,
22
+ isOpen: options.isOpen,
23
+ signal,
24
+ replay: async (sessionId, cwd) => {
25
+ options.assertRoot(sessionId);
26
+ const transcript = await readSessionTranscript(sessionId, cwd);
27
+ signal.throwIfAborted();
28
+ const frames = [];
29
+ let historyEnd;
30
+ const filter = options.airClient ? new ChangedMetaFilter() : undefined;
31
+ await options.render(sessionId, transcript.cwd, {
32
+ ...transcript,
33
+ signal,
34
+ endHistory: () => {
35
+ historyEnd = frames.length;
36
+ },
37
+ publish: async (notification) => {
38
+ signal.throwIfAborted();
39
+ const update = filter
40
+ ? filter.apply(notification.update)
41
+ : notification.update;
42
+ if (update) {
43
+ frames.push({
44
+ ...notification,
45
+ update: update.sessionUpdate === "async_task_spawned"
46
+ ? { ...update, canStop: false }
47
+ : update,
48
+ });
49
+ }
50
+ },
51
+ });
52
+ return {
53
+ frames,
54
+ cwd: transcript.cwd,
55
+ historyEnd,
56
+ title: transcript.title === undefined ? undefined : options.clientTitle(transcript.title),
57
+ };
58
+ },
59
+ send: (frame) => this.client.sessionUpdate(frame),
60
+ });
61
+ }
62
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/v2/agent.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAcxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AA+E3C,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"}
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/v2/agent.ts"],"names":[],"mappings":"AAqBA,OAAO,KAAK,EAAE,MAAM,mDAAmD,CAAC;AAcxE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAiF3C,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,CAoDb"}