@agentclientprotocol/claude-agent-acp 0.113.1-preview.8 → 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 (69) hide show
  1. package/README.md +5 -3
  2. package/dist/claude-cli.d.ts +22 -16
  3. package/dist/claude-cli.d.ts.map +1 -1
  4. package/dist/claude-cli.js +40 -18
  5. package/dist/query-settings.d.ts +42 -0
  6. package/dist/query-settings.d.ts.map +1 -0
  7. package/dist/query-settings.js +43 -0
  8. package/dist/resumed-session.d.ts +9 -2
  9. package/dist/resumed-session.d.ts.map +1 -1
  10. package/dist/resumed-session.js +51 -7
  11. package/dist/sdk-to-acp.js +4 -2
  12. package/dist/session-cursors.d.ts +1 -1
  13. package/dist/session-cursors.d.ts.map +1 -1
  14. package/dist/session-cursors.js +8 -2
  15. package/dist/session-index/transcript-scan.d.ts +13 -3
  16. package/dist/session-index/transcript-scan.d.ts.map +1 -1
  17. package/dist/session-index/transcript-scan.js +21 -5
  18. package/dist/session-mode.d.ts +69 -3
  19. package/dist/session-mode.d.ts.map +1 -1
  20. package/dist/session-mode.js +103 -15
  21. package/dist/session-model.d.ts +4 -1
  22. package/dist/session-model.d.ts.map +1 -1
  23. package/dist/session-model.js +26 -4
  24. package/dist/session-read.d.ts +45 -0
  25. package/dist/session-read.d.ts.map +1 -0
  26. package/dist/session-read.js +300 -0
  27. package/dist/session-rewind.d.ts +6 -2
  28. package/dist/session-rewind.d.ts.map +1 -1
  29. package/dist/session-rewind.js +13 -4
  30. package/dist/session-ultracode.d.ts +4 -1
  31. package/dist/session-ultracode.d.ts.map +1 -1
  32. package/dist/session-ultracode.js +14 -25
  33. package/dist/settings.d.ts +34 -0
  34. package/dist/settings.d.ts.map +1 -1
  35. package/dist/settings.js +55 -4
  36. package/dist/startup-failure.d.ts +3 -1
  37. package/dist/startup-failure.d.ts.map +1 -1
  38. package/dist/startup-failure.js +7 -1
  39. package/dist/subagent-history.d.ts +9 -1
  40. package/dist/subagent-history.d.ts.map +1 -1
  41. package/dist/subagent-history.js +55 -13
  42. package/dist/v1/acp-agent.d.ts +6 -0
  43. package/dist/v1/acp-agent.d.ts.map +1 -1
  44. package/dist/v1/acp-agent.js +162 -76
  45. package/dist/v1/session-read.d.ts +31 -0
  46. package/dist/v1/session-read.d.ts.map +1 -0
  47. package/dist/v1/session-read.js +62 -0
  48. package/dist/v2/agent.d.ts.map +1 -1
  49. package/dist/v2/agent.js +62 -27
  50. package/dist/v2/config.d.ts +9 -8
  51. package/dist/v2/config.d.ts.map +1 -1
  52. package/dist/v2/config.js +11 -8
  53. package/dist/v2/session-read.d.ts +11 -0
  54. package/dist/v2/session-read.d.ts.map +1 -0
  55. package/dist/v2/session-read.js +28 -0
  56. package/dist/v2/session.d.ts.map +1 -1
  57. package/dist/v2/session.js +6 -0
  58. package/dist/v2/setup.d.ts +4 -1
  59. package/dist/v2/setup.d.ts.map +1 -1
  60. package/dist/v2/setup.js +4 -2
  61. package/dist/v2/stream.d.ts +9 -13
  62. package/dist/v2/stream.d.ts.map +1 -1
  63. package/dist/v2/stream.js +10 -9
  64. package/dist/v2/subagent-replay.d.ts +16 -4
  65. package/dist/v2/subagent-replay.d.ts.map +1 -1
  66. package/dist/v2/subagent-replay.js +22 -10
  67. package/dist/v2/tasks.d.ts.map +1 -1
  68. package/dist/v2/tasks.js +5 -3
  69. package/package.json +4 -4
@@ -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
894
  }
895
- async loadSession(params) {
895
+ loadSession(params) {
896
+ return this.sessionReads.transition(params.sessionId, "open", () => this.loadAndReplay(params));
897
+ }
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
@@ -3395,6 +3409,10 @@ export class ClaudeAcpAgent {
3395
3409
  case "system":
3396
3410
  switch (message.subtype) {
3397
3411
  case "init":
3412
+ // The mode at the start of the turn (see `modeReported`).
3413
+ if (message.permissionMode) {
3414
+ await this.sessionModes.modeReported(params.sessionId, session, message.permissionMode);
3415
+ }
3398
3416
  // Latch the lifecycle capability so cancel() routes orphan
3399
3417
  // accounting through `orphanCommands` (per-uuid, exact)
3400
3418
  // instead of the coalescing-blind count. Never unlatch: init
@@ -3454,6 +3472,10 @@ export class ClaudeAcpAgent {
3454
3472
  await this.reportMcpServerStartupFailures(session, message.mcp_servers, supportsNotices, sendUpdate, params.sessionId);
3455
3473
  break;
3456
3474
  case "status": {
3475
+ // The mode after a change (see `modeReported`).
3476
+ if (message.permissionMode) {
3477
+ await this.sessionModes.modeReported(params.sessionId, session, message.permissionMode);
3478
+ }
3457
3479
  // A model request that serves none of the prompts a cancel
3458
3480
  // stopped is new work, such as Claude Code's follow-up after a
3459
3481
  // background command finished. It comes after the stopped
@@ -5298,8 +5320,9 @@ export class ClaudeAcpAgent {
5298
5320
  else if (message.parent_tool_use_id !== null &&
5299
5321
  Array.isArray(message.message.content)) {
5300
5322
  // A foreground fork inherits a placeholder result for its own
5301
- // launch. Only the launching side can complete that Agent call
5302
- // with the fork's actual report.
5323
+ // launch, and Claude Code before 2.1.332 streams it ("Fork
5324
+ // started — that fork is you."). Only the launching side can
5325
+ // complete that Agent call with the fork's actual report.
5303
5326
  const launchId = message.parent_tool_use_id;
5304
5327
  content = message.message.content.filter((block) => block.type !== "tool_result" || block.tool_use_id !== launchId);
5305
5328
  // The message-level sidecar cannot describe a remaining result
@@ -6135,6 +6158,7 @@ export class ClaudeAcpAgent {
6135
6158
  }
6136
6159
  /** Tear down all active sessions. Called when the ACP connection closes. */
6137
6160
  async dispose() {
6161
+ this.sessionReads.dispose();
6138
6162
  this.sessionIndex.dispose();
6139
6163
  await Promise.all(Object.keys(this.sessions).map((id) => this.teardownSession(id)));
6140
6164
  }
@@ -6153,8 +6177,10 @@ export class ClaudeAcpAgent {
6153
6177
  }
6154
6178
  /** Idempotent: a session that is not loaded here is already closed. */
6155
6179
  async closeSession(params) {
6156
- await this.endSession(params.sessionId);
6157
- return {};
6180
+ return this.sessionReads.transition(params.sessionId, "close", async () => {
6181
+ await this.endSession(params.sessionId);
6182
+ return {};
6183
+ });
6158
6184
  }
6159
6185
  /**
6160
6186
  * `session/status`: `open` for a session that this connection holds. A held
@@ -6176,7 +6202,7 @@ export class ClaudeAcpAgent {
6176
6202
  }
6177
6203
  /** Per client: see {@link sessionIndex.SessionIndexConnection.deleteSession}. */
6178
6204
  async deleteSession(params) {
6179
- return this.sessionIndex.deleteSession(params);
6205
+ return this.sessionReads.transition(params.sessionId, "close", () => this.sessionIndex.deleteSession(params));
6180
6206
  }
6181
6207
  setSessionMode(params) {
6182
6208
  return this.serializeConfigurationChange(params.sessionId, () => this.sessionModes.setSessionMode(params));
@@ -6233,15 +6259,34 @@ export class ClaudeAcpAgent {
6233
6259
  await this.applyConfigOptionValue(params.sessionId, session, params.configId, effectiveValue, duringSetup);
6234
6260
  return { configOptions: session.configOptions };
6235
6261
  }
6236
- 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) {
6237
6276
  const replayStartedAt = performance.now();
6238
6277
  const toolUseCache = {};
6278
+ const publish = detached?.publish ??
6279
+ ((notification) => this.client.sessionUpdate(notification));
6239
6280
  // A replay rebuilds the client's entities, and its cursors anchor to those.
6240
- this.lastEntities.forget(sessionId);
6281
+ if (!detached)
6282
+ this.lastEntities.forget(sessionId);
6241
6283
  // A load replays the messages before each compaction too, unless reading them fails.
6242
6284
  // The rewind cut comes first: the dropped turns get no replay and no cursor.
6243
- const current = await cutAtRewindPoint(sessionId, resumedMessages ?? (await getSessionMessages(sessionId)), this.logger);
6244
- 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);
6245
6290
  // A cursor whose resume point a compaction left out cannot be rewound to.
6246
6291
  const currentUuids = new Set(current.map((message) => message.uuid));
6247
6292
  const historyLoadedAt = performance.now();
@@ -6267,12 +6312,14 @@ export class ClaudeAcpAgent {
6267
6312
  state: session.sessionFailureState,
6268
6313
  capabilities: this.clientCapabilities,
6269
6314
  isCurrent: () => {
6315
+ if (detached)
6316
+ return !detached.signal.aborted;
6270
6317
  const live = this.sessions[sessionId];
6271
6318
  if (!live)
6272
6319
  return pending !== undefined && !pending.stopped;
6273
6320
  return live.sessionFailureState === session.sessionFailureState;
6274
6321
  },
6275
- sendUpdate: (notification) => this.client.sessionUpdate(notification),
6322
+ sendUpdate: publish,
6276
6323
  logger: this.logger,
6277
6324
  })
6278
6325
  : undefined;
@@ -6290,6 +6337,12 @@ export class ClaudeAcpAgent {
6290
6337
  // no model to the list, and each child's model is its id until the load
6291
6338
  // response refines it (see `publishCurrentSubagentStates`).
6292
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);
6293
6346
  // Registers the Agent and Task launches of `list`, and the terminal state
6294
6347
  // of each launch from its tool_result.
6295
6348
  const registerLaunches = (list) => {
@@ -6372,7 +6425,7 @@ export class ClaudeAcpAgent {
6372
6425
  const parentSessionId = child.parentToolUseId
6373
6426
  ? (replayChildren.get(child.parentToolUseId)?.sessionId ?? sessionId)
6374
6427
  : sessionId;
6375
- await this.client.sessionUpdate(asSdkSessionNotification({
6428
+ await publish(asSdkSessionNotification({
6376
6429
  sessionId: parentSessionId,
6377
6430
  update: {
6378
6431
  sessionUpdate: "subagent_spawned",
@@ -6388,7 +6441,7 @@ export class ClaudeAcpAgent {
6388
6441
  };
6389
6442
  // Only a history with an Agent or Task launch has subagent transcripts to read.
6390
6443
  const subagents = nativeReplayEnabled && replayChildren.size > 0
6391
- ? await subagentHistory(sessionId)
6444
+ ? await readSubagentHistory()
6392
6445
  : { agents: new Map() };
6393
6446
  const airReplay = nativeReplayEnabled ? new ReplayTranscript(subagents) : undefined;
6394
6447
  airReplay?.scan(messages, sessionId);
@@ -6396,10 +6449,10 @@ export class ClaudeAcpAgent {
6396
6449
  const rfdHistory = form === "rfd" &&
6397
6450
  messages.some((message) => subagentLaunchIds(message.message?.content)
6398
6451
  .length > 0)
6399
- ? await subagentHistory(sessionId)
6452
+ ? await readSubagentHistory()
6400
6453
  : { agents: new Map() };
6401
6454
  const rfdReplay = form === "rfd"
6402
- ? 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)
6403
6456
  : undefined;
6404
6457
  rfdReplay?.scan(messages, sessionId);
6405
6458
  // History persists no task_started frame, so a background task gets its
@@ -6409,7 +6462,7 @@ export class ClaudeAcpAgent {
6409
6462
  // The tool cache forgets a tool use at its result, but a notification
6410
6463
  // comes later and needs the tool use that started the task.
6411
6464
  const replayToolUses = new Map();
6412
- 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, {
6413
6466
  routeOf: (toolCallId) => {
6414
6467
  const target = replayToolUses.get(toolCallId)?.sessionId;
6415
6468
  return target && target !== sessionId
@@ -6455,6 +6508,7 @@ export class ClaudeAcpAgent {
6455
6508
  const pause = messageLoopYielder.maybeYield();
6456
6509
  if (pause)
6457
6510
  await pause;
6511
+ detached?.signal.throwIfAborted();
6458
6512
  if (pending?.stopped || isReplayHiddenMetaMessage(message)) {
6459
6513
  return;
6460
6514
  }
@@ -6520,7 +6574,7 @@ export class ClaudeAcpAgent {
6520
6574
  if (replayChild?.announced && entry && !sameModelEntry(replayChild.model, entry)) {
6521
6575
  replayChild.responseModel = model;
6522
6576
  replayChild.model = entry;
6523
- await this.client.sessionUpdate({
6577
+ await publish({
6524
6578
  sessionId: replayChild.sessionId,
6525
6579
  update: {
6526
6580
  sessionUpdate: "config_option_update",
@@ -6571,7 +6625,10 @@ export class ClaudeAcpAgent {
6571
6625
  // A subagent's own compaction summary is not the root session's.
6572
6626
  if (replayCompactionUpdates &&
6573
6627
  parentToolUseId === null &&
6574
- (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
+ }))) {
6575
6632
  return;
6576
6633
  }
6577
6634
  for (const notification of toAcpNotifications(
@@ -6603,7 +6660,7 @@ export class ClaudeAcpAgent {
6603
6660
  : undefined;
6604
6661
  if (handback !== undefined) {
6605
6662
  if (handback !== null) {
6606
- await this.client.sessionUpdate({
6663
+ await publish({
6607
6664
  sessionId: replayTargetSessionId,
6608
6665
  update: {
6609
6666
  sessionUpdate: "agent_message_chunk",
@@ -6615,7 +6672,7 @@ export class ClaudeAcpAgent {
6615
6672
  continue;
6616
6673
  }
6617
6674
  const replayed = { ...notification, sessionId: replayTargetSessionId };
6618
- await this.client.sessionUpdate(rfdReplay
6675
+ await publish(rfdReplay
6619
6676
  ? asSdkSessionNotification(rfdReplay.withTarget(replayed, replayTargetSessionId))
6620
6677
  : replayed);
6621
6678
  }
@@ -6629,7 +6686,7 @@ export class ClaudeAcpAgent {
6629
6686
  if (!agentId || replayedSubagents.has(agentId))
6630
6687
  continue;
6631
6688
  replayedSubagents.add(agentId);
6632
- const childMessages = await readSubagentMessages(sessionId, agentId, subagents, this.logger);
6689
+ const childMessages = await readChildMessages(agentId, subagents, toolUseId);
6633
6690
  registerLaunches(childMessages);
6634
6691
  airReplay?.scan(childMessages, agentId);
6635
6692
  for (const childMessage of childMessages)
@@ -6643,7 +6700,7 @@ export class ClaudeAcpAgent {
6643
6700
  const launched = rfdReplay.childOfLaunch(toolUseId);
6644
6701
  if (!launched || launched.announced)
6645
6702
  continue;
6646
- const childMessages = await readSubagentMessages(sessionId, launched.sessionId, rfdHistory, this.logger);
6703
+ const childMessages = await readChildMessages(launched.sessionId, rfdHistory, toolUseId);
6647
6704
  await rfdReplay.announce(launched);
6648
6705
  rfdReplay.scan(childMessages, launched.sessionId);
6649
6706
  for (const childMessage of childMessages)
@@ -6654,20 +6711,30 @@ export class ClaudeAcpAgent {
6654
6711
  };
6655
6712
  for (const [index, message] of messages.entries()) {
6656
6713
  // Before the message's own chunk: the cursor lies before the message.
6657
- const before = this.lastEntities.last(sessionId);
6714
+ const before = detached ? undefined : this.lastEntities.last(sessionId);
6658
6715
  await replayMessage(message);
6659
6716
  // A task notification record is no user message to the client (see `replayMessage`).
6660
6717
  if (!pending?.stopped &&
6661
6718
  hasForkCursor(messages, index) &&
6662
6719
  !isTaskNotificationRecord(message)) {
6663
- this.announceCursor(sessionId, forkCursorUpdate(message.uuid), before, {
6664
- rewindable: currentUuids.has(messages[index - 1].uuid),
6665
- });
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
+ }
6666
6731
  }
6667
6732
  }
6733
+ detached?.endHistory();
6668
6734
  if (rfdReplay && !pending?.stopped) {
6669
6735
  await rfdReplay.finish(clientSupportsNotices(this.clientCapabilities), sessionId);
6670
- this.replayedSubagents.set(sessionId, rfdReplay);
6736
+ if (!detached)
6737
+ this.replayedSubagents.set(sessionId, rfdReplay);
6671
6738
  }
6672
6739
  if (nativeReplayEnabled && !pending?.stopped) {
6673
6740
  const childModels = new Map();
@@ -6676,7 +6743,7 @@ export class ClaudeAcpAgent {
6676
6743
  childModels.set(child.sessionId, { model: child.responseModel, sent: child.model });
6677
6744
  }
6678
6745
  }
6679
- if (childModels.size > 0)
6746
+ if (!detached && childModels.size > 0)
6680
6747
  this.replayedChildModels.set(sessionId, childModels);
6681
6748
  // Claude history persists sidechain messages and Agent/Task tool uses,
6682
6749
  // but not task_started/task_updated lifecycle frames. Recover terminal
@@ -6688,7 +6755,7 @@ export class ClaudeAcpAgent {
6688
6755
  const parentSessionId = child.parentToolUseId
6689
6756
  ? (replayChildren.get(child.parentToolUseId)?.sessionId ?? sessionId)
6690
6757
  : sessionId;
6691
- await this.client.sessionUpdate(asSdkSessionNotification({
6758
+ await publish(asSdkSessionNotification({
6692
6759
  sessionId: parentSessionId,
6693
6760
  update: {
6694
6761
  sessionUpdate: "subagent_state_update",
@@ -6705,9 +6772,10 @@ export class ClaudeAcpAgent {
6705
6772
  // A client with `loadReplayEnd` gets one more update after the whole
6706
6773
  // replay, the subagent history included. A stopped replay (the CLI start
6707
6774
  // failed) does not get it, and a failed replay throws before this line.
6708
- if (!pending?.stopped &&
6775
+ if (!detached &&
6776
+ !pending?.stopped &&
6709
6777
  clientSupportsAirCapability(this.clientCapabilities, AIR_LOAD_REPLAY_END_CAPABILITY)) {
6710
- await this.client.sessionUpdate({
6778
+ await publish({
6711
6779
  sessionId,
6712
6780
  // No `title` and no `updatedAt`: `null` would clear them.
6713
6781
  update: {
@@ -7973,10 +8041,11 @@ export class ClaudeAcpAgent {
7973
8041
  settingsManager.getSettings().permissions?.disableBypassPermissionsMode !== "disable" &&
7974
8042
  sessionMeta?.claudeCode?.options?.allowDangerouslySkipPermissions !== false;
7975
8043
  const allowAuto = !autoModeDisabled(settingsManager.getSettings());
8044
+ const spawnSettings = settingsManager.getSettings();
7976
8045
  const { mode: initialPermissionMode, builtInDefault: builtInPermissionMode } = resolveInitialPermissionMode({
7977
8046
  explicit: creationOpts.permissionMode,
7978
8047
  resumed: resumedPermissionMode,
7979
- defaultMode: settingsManager.getSettings().permissions?.defaultMode,
8048
+ defaultMode: spawnSettings.permissions?.defaultMode,
7980
8049
  }, this.logger, { allowBypass, allowAuto });
7981
8050
  const userProvidedOptions = sessionMeta?.claudeCode?.options;
7982
8051
  const forwardSubagentText = this.forwardsSubagentText(params._meta);
@@ -8195,9 +8264,12 @@ export class ClaudeAcpAgent {
8195
8264
  hooks: [
8196
8265
  ...(subagentConfigHook ? [subagentConfigHook] : []),
8197
8266
  createPostToolUseHook({
8267
+ // Claude Code reports the mode in a `status` frame too: the
8268
+ // first of the two is recorded.
8198
8269
  onEnterPlanMode: async () => {
8199
- await this.sessionModes.publishCurrent(sessionId, "plan");
8200
- await this.updateConfigOption(sessionId, MODE_CONFIG_ID, "plan");
8270
+ const entered = this.sessions[sessionId];
8271
+ if (entered)
8272
+ await this.sessionModes.modeReported(sessionId, entered, "plan");
8201
8273
  },
8202
8274
  }),
8203
8275
  ],
@@ -8356,6 +8428,18 @@ export class ClaudeAcpAgent {
8356
8428
  if (route)
8357
8429
  await applyProviderRoute(q, route);
8358
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");
8359
8443
  // Publish the identity BEFORE the guard can refuse this session. A
8360
8444
  // refusal is exactly when the client most needs to know which account it
8361
8445
  // was refused for.
@@ -8403,7 +8487,7 @@ export class ClaudeAcpAgent {
8403
8487
  const allowedModels = resolvedProvider?.listedModels
8404
8488
  ? narrowToGatewayModels(settingsAllowedModels, resolvedProvider.listedModels, resolvedProvider.bedrockRegionPrefix)
8405
8489
  : settingsAllowedModels;
8406
- 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);
8407
8491
  timing.phase("models");
8408
8492
  // Resolve the current model's capabilities separately from the stable
8409
8493
  // permission-mode catalog advertised to ACP clients (see
@@ -8411,12 +8495,13 @@ export class ClaudeAcpAgent {
8411
8495
  const { allowlistedModelInfo, currentModelInfo, modelInfos } = withCurrentModelInfo(allowedModels, sdkModels, models.currentModelId);
8412
8496
  const { modes, autoModeFallbackWarningPending } = await this.sessionModes.initialize({
8413
8497
  query: q,
8414
- requestedMode: initialPermissionMode,
8415
- builtInDefault: builtInPermissionMode,
8498
+ requestedMode: startMode.mode,
8499
+ builtInDefault: startMode.builtInDefault,
8500
+ startedIn: initialPermissionMode,
8416
8501
  currentModelInfo,
8417
8502
  currentModelId: models.currentModelId,
8418
- allowBypass,
8419
- allowAuto,
8503
+ allowBypass: startMode.allowBypass,
8504
+ allowAuto: startMode.allowAuto,
8420
8505
  });
8421
8506
  timing.phase("modes");
8422
8507
  const agents = await discoverCustomAgents(q);
@@ -9114,6 +9199,7 @@ export function v1AgentApp(logger, onAgent) {
9114
9199
  .onRequest(methods.agent.initialize, (ctx) => agent.initialize(ctx.params))
9115
9200
  .onRequest(methods.agent.session.new, (ctx) => agent.newSession(ctx.params))
9116
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))
9117
9203
  .onRequest(methods.agent.session.fork, ofRootSession("fork", (ctx) => agent.forking(ctx.params.sessionId, () => agent.unstable_forkSession(ctx.params))))
9118
9204
  .onRequest(methods.agent.session.list, (ctx) => agent.listSessions(ctx.params))
9119
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
+ }