@agentclientprotocol/claude-agent-acp 0.102.0 → 0.102.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.
Files changed (206) hide show
  1. package/README.md +5 -1
  2. package/dist/acp-agent.d.ts +119 -439
  3. package/dist/acp-agent.d.ts.map +1 -1
  4. package/dist/acp-agent.js +380 -2412
  5. package/dist/acp-subagents.d.ts +1 -2
  6. package/dist/acp-subagents.d.ts.map +1 -1
  7. package/dist/auth-methods.d.ts +21 -0
  8. package/dist/auth-methods.d.ts.map +1 -0
  9. package/dist/auth-methods.js +68 -0
  10. package/dist/auth-status-reporter.d.ts +112 -0
  11. package/dist/auth-status-reporter.d.ts.map +1 -0
  12. package/dist/auth-status-reporter.js +253 -0
  13. package/dist/background-work.d.ts +12 -265
  14. package/dist/background-work.d.ts.map +1 -1
  15. package/dist/background-work.js +8 -558
  16. package/dist/client-system-prompt.d.ts +7 -0
  17. package/dist/client-system-prompt.d.ts.map +1 -1
  18. package/dist/client-system-prompt.js +24 -0
  19. package/dist/context-compaction.d.ts +20 -0
  20. package/dist/context-compaction.d.ts.map +1 -1
  21. package/dist/context-compaction.js +26 -0
  22. package/dist/context-window.d.ts +70 -0
  23. package/dist/context-window.d.ts.map +1 -0
  24. package/dist/context-window.js +132 -0
  25. package/dist/diff.d.ts +1 -1
  26. package/dist/diff.js +1 -1
  27. package/dist/elicitation.d.ts +66 -1
  28. package/dist/elicitation.d.ts.map +1 -1
  29. package/dist/elicitation.js +109 -0
  30. package/dist/file-change-audit.d.ts +4 -3
  31. package/dist/file-change-audit.d.ts.map +1 -1
  32. package/dist/file-change-audit.js +3 -2
  33. package/dist/mcp-oauth.d.ts +44 -0
  34. package/dist/mcp-oauth.d.ts.map +1 -0
  35. package/dist/mcp-oauth.js +142 -0
  36. package/dist/mcp-servers.d.ts +10 -0
  37. package/dist/mcp-servers.d.ts.map +1 -0
  38. package/dist/mcp-servers.js +29 -0
  39. package/dist/native-subagents.d.ts +18 -8
  40. package/dist/native-subagents.d.ts.map +1 -1
  41. package/dist/native-subagents.js +7 -35
  42. package/dist/permissions/presentation.d.ts +29 -0
  43. package/dist/permissions/presentation.d.ts.map +1 -1
  44. package/dist/permissions/presentation.js +38 -11
  45. package/dist/plans.d.ts +36 -6
  46. package/dist/plans.d.ts.map +1 -1
  47. package/dist/plans.js +49 -11
  48. package/dist/prompt-suggestions.d.ts +29 -0
  49. package/dist/prompt-suggestions.d.ts.map +1 -1
  50. package/dist/prompt-suggestions.js +45 -0
  51. package/dist/providers.d.ts +139 -0
  52. package/dist/providers.d.ts.map +1 -0
  53. package/dist/providers.js +286 -0
  54. package/dist/remote-control.d.ts +62 -0
  55. package/dist/remote-control.d.ts.map +1 -0
  56. package/dist/remote-control.js +78 -0
  57. package/dist/result-end.d.ts +39 -0
  58. package/dist/result-end.d.ts.map +1 -0
  59. package/dist/result-end.js +50 -0
  60. package/dist/serve.d.ts +7 -2
  61. package/dist/serve.d.ts.map +1 -1
  62. package/dist/serve.js +10 -5
  63. package/dist/session-config-ids.d.ts +1 -0
  64. package/dist/session-config-ids.d.ts.map +1 -1
  65. package/dist/session-config-ids.js +1 -0
  66. package/dist/session-config-options.d.ts +64 -0
  67. package/dist/session-config-options.d.ts.map +1 -0
  68. package/dist/session-config-options.js +162 -0
  69. package/dist/session-effort.d.ts +67 -0
  70. package/dist/session-effort.d.ts.map +1 -1
  71. package/dist/session-effort.js +98 -0
  72. package/dist/session-env.d.ts +22 -0
  73. package/dist/session-env.d.ts.map +1 -0
  74. package/dist/session-env.js +66 -0
  75. package/dist/session-fast-mode.d.ts +83 -0
  76. package/dist/session-fast-mode.d.ts.map +1 -0
  77. package/dist/session-fast-mode.js +142 -0
  78. package/dist/session-index/connection.d.ts +2 -5
  79. package/dist/session-index/connection.d.ts.map +1 -1
  80. package/dist/session-index/connection.js +3 -5
  81. package/dist/session-mode.d.ts +1 -0
  82. package/dist/session-mode.d.ts.map +1 -1
  83. package/dist/session-mode.js +1 -1
  84. package/dist/session-model.d.ts +41 -0
  85. package/dist/session-model.d.ts.map +1 -1
  86. package/dist/session-model.js +110 -45
  87. package/dist/session-notices.d.ts +44 -0
  88. package/dist/session-notices.d.ts.map +1 -1
  89. package/dist/session-notices.js +68 -0
  90. package/dist/session-titles.d.ts +34 -12
  91. package/dist/session-titles.d.ts.map +1 -1
  92. package/dist/session-titles.js +7 -6
  93. package/dist/session-usage.d.ts +125 -0
  94. package/dist/session-usage.d.ts.map +1 -0
  95. package/dist/session-usage.js +196 -0
  96. package/dist/streamed-text.d.ts +33 -0
  97. package/dist/streamed-text.d.ts.map +1 -0
  98. package/dist/streamed-text.js +71 -0
  99. package/dist/subagent-configuration.d.ts +32 -0
  100. package/dist/subagent-configuration.d.ts.map +1 -0
  101. package/dist/subagent-configuration.js +70 -0
  102. package/dist/subagent-replay.d.ts +18 -0
  103. package/dist/subagent-replay.d.ts.map +1 -1
  104. package/dist/subagent-replay.js +25 -15
  105. package/dist/tool-calls/client-capabilities.d.ts +8 -8
  106. package/dist/tool-calls/client-capabilities.js +4 -4
  107. package/dist/tool-calls/renderer.d.ts +4 -5
  108. package/dist/tool-calls/renderer.d.ts.map +1 -1
  109. package/dist/tool-calls/renderer.js +4 -5
  110. package/dist/turn-events.d.ts +6 -46
  111. package/dist/turn-events.d.ts.map +1 -1
  112. package/dist/v2/agent.d.ts +7 -11
  113. package/dist/v2/agent.d.ts.map +1 -1
  114. package/dist/v2/agent.js +751 -331
  115. package/dist/v2/air.d.ts +33 -0
  116. package/dist/v2/air.d.ts.map +1 -0
  117. package/dist/v2/air.js +29 -0
  118. package/dist/v2/auth.d.ts +97 -0
  119. package/dist/v2/auth.d.ts.map +1 -0
  120. package/dist/v2/auth.js +216 -0
  121. package/dist/v2/background.d.ts +27 -16
  122. package/dist/v2/background.d.ts.map +1 -1
  123. package/dist/v2/background.js +4 -32
  124. package/dist/v2/child-config.d.ts +55 -0
  125. package/dist/v2/child-config.d.ts.map +1 -0
  126. package/dist/v2/child-config.js +92 -0
  127. package/dist/v2/clear-context.d.ts +94 -0
  128. package/dist/v2/clear-context.d.ts.map +1 -0
  129. package/dist/v2/clear-context.js +176 -0
  130. package/dist/v2/commands.d.ts +46 -0
  131. package/dist/v2/commands.d.ts.map +1 -0
  132. package/dist/v2/commands.js +54 -0
  133. package/dist/v2/config.d.ts +187 -0
  134. package/dist/v2/config.d.ts.map +1 -0
  135. package/dist/v2/config.js +494 -0
  136. package/dist/v2/elicitation.d.ts +93 -0
  137. package/dist/v2/elicitation.d.ts.map +1 -0
  138. package/dist/v2/elicitation.js +160 -0
  139. package/dist/v2/file-changes.d.ts +61 -0
  140. package/dist/v2/file-changes.d.ts.map +1 -0
  141. package/dist/v2/file-changes.js +108 -0
  142. package/dist/v2/file-preview.d.ts +18 -0
  143. package/dist/v2/file-preview.d.ts.map +1 -0
  144. package/dist/v2/file-preview.js +29 -0
  145. package/dist/v2/initialize.d.ts +10 -24
  146. package/dist/v2/initialize.d.ts.map +1 -1
  147. package/dist/v2/initialize.js +4 -111
  148. package/dist/v2/outcome.d.ts +81 -0
  149. package/dist/v2/outcome.d.ts.map +1 -0
  150. package/dist/v2/outcome.js +165 -0
  151. package/dist/v2/permissions.d.ts +92 -0
  152. package/dist/v2/permissions.d.ts.map +1 -0
  153. package/dist/v2/permissions.js +162 -0
  154. package/dist/v2/prompt.d.ts +2 -42
  155. package/dist/v2/prompt.d.ts.map +1 -1
  156. package/dist/v2/prompt.js +2 -119
  157. package/dist/v2/remote-control.d.ts +41 -0
  158. package/dist/v2/remote-control.d.ts.map +1 -0
  159. package/dist/v2/remote-control.js +63 -0
  160. package/dist/v2/reports.d.ts +198 -0
  161. package/dist/v2/reports.d.ts.map +1 -0
  162. package/dist/v2/reports.js +487 -0
  163. package/dist/v2/restarts.d.ts +128 -0
  164. package/dist/v2/restarts.d.ts.map +1 -0
  165. package/dist/v2/restarts.js +348 -0
  166. package/dist/v2/session-requests.d.ts +20 -0
  167. package/dist/v2/session-requests.d.ts.map +1 -0
  168. package/dist/v2/session-requests.js +108 -0
  169. package/dist/v2/session-update.d.ts +2 -13
  170. package/dist/v2/session-update.d.ts.map +1 -1
  171. package/dist/v2/session-update.js +2 -22
  172. package/dist/v2/session.d.ts +340 -41
  173. package/dist/v2/session.d.ts.map +1 -1
  174. package/dist/v2/session.js +1223 -141
  175. package/dist/v2/setup.d.ts +49 -0
  176. package/dist/v2/setup.d.ts.map +1 -0
  177. package/dist/v2/setup.js +62 -0
  178. package/dist/v2/stopped-work.d.ts +123 -0
  179. package/dist/v2/stopped-work.d.ts.map +1 -0
  180. package/dist/v2/stopped-work.js +210 -0
  181. package/dist/v2/stream.d.ts +228 -0
  182. package/dist/v2/stream.d.ts.map +1 -0
  183. package/dist/v2/stream.js +506 -0
  184. package/dist/v2/subagent-replay.d.ts +115 -0
  185. package/dist/v2/subagent-replay.d.ts.map +1 -0
  186. package/dist/v2/subagent-replay.js +479 -0
  187. package/dist/v2/subscription-guard.d.ts +60 -0
  188. package/dist/v2/subscription-guard.d.ts.map +1 -0
  189. package/dist/v2/subscription-guard.js +84 -0
  190. package/dist/v2/tasks.d.ts +492 -0
  191. package/dist/v2/tasks.d.ts.map +1 -0
  192. package/dist/v2/tasks.js +1728 -0
  193. package/dist/v2/terminal.d.ts.map +1 -1
  194. package/dist/v2/terminal.js +6 -1
  195. package/dist/v2/tool-call.d.ts +3 -2
  196. package/dist/v2/tool-call.d.ts.map +1 -1
  197. package/dist/v2/update-translator.d.ts +36 -0
  198. package/dist/v2/update-translator.d.ts.map +1 -0
  199. package/dist/v2/update-translator.js +80 -0
  200. package/dist/workflow-progress.d.ts +23 -0
  201. package/dist/workflow-progress.d.ts.map +1 -1
  202. package/dist/workflow-progress.js +31 -8
  203. package/package.json +1 -1
  204. package/dist/v2/permission.d.ts +0 -28
  205. package/dist/v2/permission.d.ts.map +0 -1
  206. package/dist/v2/permission.js +0 -41
@@ -64,42 +64,71 @@ function versionedModelDisplayName(model) {
64
64
  // Keep the suffix in its original spelling and insert the version before it.
65
65
  return `${withoutContext} ${version}${contextSuffix[0]}`;
66
66
  }
67
- function tokenizeModelPreference(model) {
68
- const lower = model.trim().toLowerCase();
69
- const contextHint = lower.match(MODEL_CONTEXT_HINT_PATTERN)?.[1]?.toLowerCase();
70
- const tokens = lower
71
- .replace(MODEL_CONTEXT_HINT_PATTERN, " $1 ")
67
+ function modelWords(value) {
68
+ return value
69
+ .toLowerCase()
72
70
  .split(/[^a-z0-9]+/)
73
- .filter(Boolean)
74
- .map((token) => {
75
- if (token === "opusplan")
76
- return "opus";
77
- if (token === "best" || token === "default")
78
- return "";
79
- return token;
80
- })
81
- .filter((token) => token && token !== "claude")
82
- .filter((token) => /[a-z]/.test(token) || token.endsWith("m"));
83
- return { tokens, contextHint };
71
+ .filter(Boolean);
84
72
  }
85
- function scoreModelMatch(model, tokens, contextHint) {
86
- const haystack = `${model.value} ${model.displayName}`.toLowerCase();
87
- let score = 0;
88
- let nonHintMatched = false;
89
- for (const token of tokens) {
90
- if (!haystack.includes(token))
91
- continue;
92
- if (token !== contextHint)
93
- nonHintMatched = true;
94
- score += token === contextHint ? 3 : 1;
73
+ /** Whether `needle`'s words appear in `haystack`'s words, adjacent and in
74
+ * order: "opus" in "claude-opus-4-5", but not "son" in "sonnet" or "a" in
75
+ * "Default (recommended)". */
76
+ function containsWords(haystack, needle) {
77
+ const words = modelWords(haystack);
78
+ const wanted = modelWords(needle);
79
+ if (wanted.length === 0)
80
+ return false;
81
+ for (let start = 0; start + wanted.length <= words.length; start++) {
82
+ if (wanted.every((word, offset) => words[start + offset] === word))
83
+ return true;
95
84
  }
96
- return contextHint && !nonHintMatched ? 0 : score;
85
+ return false;
86
+ }
87
+ /** `id` without the gateway spellings that `normalizeModelId` keeps for
88
+ * `deniedModels` and gateway listings: path segments before `claude-`
89
+ * (`vertex_ai/`, `openrouter/anthropic/`, `publishers/anthropic/models/`)
90
+ * and the Anthropic API's `-latest` suffix (`claude-3-5-haiku-latest`). */
91
+ function withoutGatewaySpelling(id) {
92
+ return id.replace(/^(?:[^/]+\/)+(?=claude-)/, "").replace(/-latest$/, "");
93
+ }
94
+ /** The words of `preference` that name a model: without what
95
+ * `normalizeModelId` drops (provider prefixes, dates, `-v1:0`, `-fast`,
96
+ * context hints), version numbers, "claude", and "best"/"default".
97
+ * "us.anthropic.claude-sonnet-4-5-v1:0" gives ["sonnet"], "opusplan" gives
98
+ * ["opus"]. */
99
+ function modelPreferenceTokens(preference) {
100
+ return modelWords(withoutGatewaySpelling(normalizeModelId(preference)))
101
+ .map((token) => (token === "opusplan" ? "opus" : token))
102
+ .filter((token) => /[a-z]/.test(token) && !["claude", "best", "default"].includes(token));
103
+ }
104
+ /** Whether every one of `tokens` is a word of `model`'s value or display name. */
105
+ function modelCoversTokens(model, tokens) {
106
+ const words = new Set(modelWords(`${model.value} ${model.displayName}`));
107
+ return tokens.length > 0 && tokens.every((token) => words.has(token));
97
108
  }
109
+ /**
110
+ * The entry of `models` that `preference` names, or null when it names none.
111
+ * `best` names the entry `opus` resolves to, unless an entry's value is `best`.
112
+ * In order: an entry whose value, display name or `resolvedModel` equals it
113
+ * (in either context-hint spelling); an entry whose value or display name
114
+ * contains its words ("opus" for "claude-opus-4-5"), or whose value it
115
+ * contains while every model word of the preference is the entry's
116
+ * ("sonnet" for "us.anthropic.claude-sonnet-5-v1:0"); then any entry with all
117
+ * of its model words, preferring one with the same context hint ("sonnet[1m]"
118
+ * for "claude-sonnet-5-1m"). The fuzzy tiers need a compatible version, and
119
+ * words match whole: "not-a-model", "son" and "foo-sonnet" name no entry.
120
+ */
98
121
  export function resolveModelPreference(models, preference) {
99
122
  const trimmed = preference.trim();
100
123
  if (!trimmed)
101
124
  return null;
102
125
  const lower = trimmed.toLowerCase();
126
+ // The CLI resolves `best` to its flagship: Opus, unless a server-side flag
127
+ // names another family that this adapter cannot read. The CLI ignores a
128
+ // `[1m]` hint on `best`. A listed entry named `best` still matches directly.
129
+ if (stripContextHints(lower) === "best" && !models.some((model) => model.value === trimmed)) {
130
+ return resolveModelPreference(models, "opus");
131
+ }
103
132
  const canonicalPreference = canonicalizeModelId(trimmed);
104
133
  const directMatch = models.find((model) => model.value === trimmed ||
105
134
  canonicalizeModelId(model.value) === canonicalPreference ||
@@ -112,32 +141,22 @@ export function resolveModelPreference(models, preference) {
112
141
  if (resolvedMatch)
113
142
  return resolvedMatch;
114
143
  const preferenceHint = contextHintOf(trimmed);
144
+ const tokens = modelPreferenceTokens(trimmed);
115
145
  const includesMatch = models.find((model) => {
116
146
  if (!modelVersionsCompatible(trimmed, model))
117
147
  return false;
118
148
  if (contextHintOf(model.value) !== preferenceHint)
119
149
  return false;
120
- const value = model.value.toLowerCase();
121
- const display = model.displayName.toLowerCase();
122
- return value.includes(lower) || display.includes(lower) || lower.includes(value);
150
+ return (containsWords(model.value, trimmed) ||
151
+ containsWords(model.displayName, trimmed) ||
152
+ (containsWords(trimmed, model.value) && modelCoversTokens(model, tokens)));
123
153
  });
124
154
  if (includesMatch)
125
155
  return includesMatch;
126
- const { tokens, contextHint } = tokenizeModelPreference(trimmed);
127
- if (tokens.length === 0)
128
- return null;
129
- let bestMatch = null;
130
- let bestScore = 0;
131
- for (const model of models) {
132
- if (!modelVersionsCompatible(trimmed, model))
133
- continue;
134
- const score = scoreModelMatch(model, tokens, contextHint);
135
- if (score > 0 && (!bestMatch || score > bestScore)) {
136
- bestMatch = model;
137
- bestScore = score;
138
- }
139
- }
140
- return bestMatch;
156
+ const candidates = models.filter((model) => modelVersionsCompatible(trimmed, model) && modelCoversTokens(model, tokens));
157
+ return (candidates.find((model) => contextHintOf(model.value) === preferenceHint) ??
158
+ candidates[0] ??
159
+ null);
141
160
  }
142
161
  export function matchResumedModel(models, liveModel) {
143
162
  const live = canonicalizeModelId(liveModel);
@@ -447,6 +466,52 @@ export function narrowToGatewayModels(models, listedModelIds, regionPrefix) {
447
466
  ? narrowed
448
467
  : [];
449
468
  }
469
+ /**
470
+ * The capabilities of the session's current model, and the model infos that
471
+ * every later lookup reads.
472
+ *
473
+ * A resumed session can be running a model outside the `availableModels`
474
+ * allowlist (currentModelId is then the verbatim live id, see
475
+ * `matchResumedModel`); its capabilities are still known to the SDK's
476
+ * unfiltered list, so they are resolved from that before the model is treated
477
+ * as unknown — otherwise auto mode would be spuriously clamped and the
478
+ * Fast-mode/Effort options hidden for a model that supports them.
479
+ *
480
+ * The fallback-resolved capabilities are registered under the verbatim live
481
+ * id, so every modelInfos consumer (the effort option, later rebuilds) agrees
482
+ * with that gating. `buildModelConfigOption` lists this model as its own
483
+ * entry while it is current and drops it once the user switches to a listed
484
+ * model; it is never added to `availableModels`. The spread keeps every
485
+ * capability flag (current and future); the identity fields are overridden
486
+ * because the fuzzy-matched sibling's resolvedModel/displayName/description
487
+ * can describe a different context lane and would poison later resolvedModel
488
+ * matching (a model switch that the adapter did not make) and context-window
489
+ * inference if they traveled under this id. `allowlistedModelInfo` is the
490
+ * allowlisted entry alone, the only one whose identity strings are a
491
+ * trustworthy window signal.
492
+ */
493
+ export function withCurrentModelInfo(allowedModels, sdkModels, currentModelId) {
494
+ const allowlistedModelInfo = allowedModels.find((m) => m.value === currentModelId);
495
+ const fallbackModelInfo = allowlistedModelInfo
496
+ ? undefined
497
+ : (resolveModelPreference(sdkModels, currentModelId) ?? undefined);
498
+ return {
499
+ allowlistedModelInfo,
500
+ currentModelInfo: allowlistedModelInfo ?? fallbackModelInfo,
501
+ modelInfos: fallbackModelInfo
502
+ ? [
503
+ ...allowedModels,
504
+ {
505
+ ...fallbackModelInfo,
506
+ value: currentModelId,
507
+ displayName: currentModelId,
508
+ description: "",
509
+ resolvedModel: undefined,
510
+ },
511
+ ]
512
+ : allowedModels,
513
+ };
514
+ }
450
515
  /** Whether a rejected `setModel` was vetoed by a user-configured
451
516
  * PreModelSwitch hook. The CLI's rejection message is the stable,
452
517
  * distinguishable marker ("Model switch blocked by a PreModelSwitch hook:
@@ -48,4 +48,48 @@ export declare function noticePlainText(text: string): string;
48
48
  * first line stands as the title when it is short enough, otherwise the whole
49
49
  * text becomes the description under `fallbackTitle`. */
50
50
  export declare function splitNoticeText(text: string, fallbackTitle: string): Pick<SessionNotice, "title" | "description">;
51
+ /** The notice of Claude Code's `informational` message (e.g. why a Stop hook
52
+ * blocked continuation): a warning at level `warning`, else info. */
53
+ export declare function informationalNotice(message: {
54
+ level: string;
55
+ content: string;
56
+ }): SessionNotice;
57
+ /** The notice of a client MCP server that the `system/init` lists as not
58
+ * started: `failed`, or `needs-auth` when the client cannot run the OAuth
59
+ * flow (`oauthAvailable`). Undefined for any other status. */
60
+ export declare function mcpServerStartupNotice(server: {
61
+ name: string;
62
+ status: string;
63
+ }, oauthAvailable: boolean): SessionNotice | undefined;
64
+ /**
65
+ * What Claude Code's `model_refusal_fallback` tells the user: the SDK retried
66
+ * a refused turn on the fallback model.
67
+ *
68
+ * Current CLIs only emit direction "retry", a swap that lasts for the
69
+ * session. "revert"/"sticky" are retained in the SDK enum for older CLIs,
70
+ * where "revert" marked a turn-only fallback: the session stays on the
71
+ * original model. `scope` (CLI 2.1.232+) "local" means a subagent,
72
+ * side-question or background fork response fell back and the session model
73
+ * is unchanged. Absent scope means an older CLI, where every retry was a
74
+ * session-level swap. `persistent` is whether the session now runs
75
+ * `fallback_model`, so its model option must follow.
76
+ */
77
+ export declare function modelRefusalFallback(message: {
78
+ original_model: string;
79
+ fallback_model: string;
80
+ direction?: string;
81
+ scope?: string;
82
+ api_refusal_category?: string | null;
83
+ api_refusal_explanation?: string | null;
84
+ }): {
85
+ persistent: boolean;
86
+ /** The one-line summary. */
87
+ summary: string;
88
+ explanation: string | undefined;
89
+ /** The notice: the summary as its title when it is short enough, else a
90
+ * generic title with everything in the description. */
91
+ notice: SessionNotice;
92
+ /** The transcript line for a client without `notice` updates. */
93
+ transcript: string;
94
+ };
51
95
  //# sourceMappingURL=session-notices.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-notices.d.ts","sourceRoot":"","sources":["../src/session-notices.ts"],"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  }
89
89
  return rest ? { title: firstLine, description: rest } : { title: firstLine };
90
90
  }
91
+ /** The notice of Claude Code's `informational` message (e.g. why a Stop hook
92
+ * blocked continuation): a warning at level `warning`, else info. */
93
+ export function informationalNotice(message) {
94
+ const severity = message.level === "warning" ? "warning" : "info";
95
+ return {
96
+ severity,
97
+ ...splitNoticeText(message.content, severity === "warning" ? "Claude reported a warning" : "Claude reported a notice"),
98
+ };
99
+ }
100
+ /** The notice of a client MCP server that the `system/init` lists as not
101
+ * started: `failed`, or `needs-auth` when the client cannot run the OAuth
102
+ * flow (`oauthAvailable`). Undefined for any other status. */
103
+ export function mcpServerStartupNotice(server, oauthAvailable) {
104
+ if (server.status === "failed") {
105
+ return {
106
+ severity: "warning",
107
+ title: `MCP server "${server.name}" failed to start`,
108
+ description: "Its tools are unavailable in this session. Run /mcp for the error.",
109
+ };
110
+ }
111
+ if (server.status === "needs-auth" && !oauthAvailable) {
112
+ return {
113
+ severity: "info",
114
+ title: `MCP server "${server.name}" needs authentication`,
115
+ description: "Its tools are unavailable until the server is authenticated.",
116
+ };
117
+ }
118
+ return undefined;
119
+ }
120
+ /**
121
+ * What Claude Code's `model_refusal_fallback` tells the user: the SDK retried
122
+ * a refused turn on the fallback model.
123
+ *
124
+ * Current CLIs only emit direction "retry", a swap that lasts for the
125
+ * session. "revert"/"sticky" are retained in the SDK enum for older CLIs,
126
+ * where "revert" marked a turn-only fallback: the session stays on the
127
+ * original model. `scope` (CLI 2.1.232+) "local" means a subagent,
128
+ * side-question or background fork response fell back and the session model
129
+ * is unchanged. Absent scope means an older CLI, where every retry was a
130
+ * session-level swap. `persistent` is whether the session now runs
131
+ * `fallback_model`, so its model option must follow.
132
+ */
133
+ export function modelRefusalFallback(message) {
134
+ const local = message.scope === "local";
135
+ const persistent = message.direction !== "revert" && !local;
136
+ const category = message.api_refusal_category ? ` (${message.api_refusal_category})` : "";
137
+ const outcome = persistent
138
+ ? `The session will continue on ${message.fallback_model}.`
139
+ : local
140
+ ? `Only that response came from ${message.fallback_model}; the session stays on ${message.original_model}.`
141
+ : `The session stays on ${message.original_model}.`;
142
+ const summary = `${message.original_model} declined this request${category}; ` +
143
+ `retried with ${message.fallback_model}. ${outcome}`;
144
+ const explanation = message.api_refusal_explanation || undefined;
145
+ const full = explanation ? `${summary}\n\n${explanation}` : summary;
146
+ return {
147
+ persistent,
148
+ summary,
149
+ explanation,
150
+ notice: {
151
+ severity: "warning",
152
+ ...(summary.length > MAX_NOTICE_TITLE_LENGTH
153
+ ? { title: "Model fallback", description: full }
154
+ : { title: summary, ...(explanation ? { description: explanation } : {}) }),
155
+ },
156
+ transcript: `**Model fallback:** ${full}`,
157
+ };
158
+ }
@@ -11,15 +11,37 @@
11
11
  * `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` or
12
12
  * `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` set), the same request generates it.
13
13
  *
14
- * {@link SessionTitles} holds the per-session state and is owned by `Session`.
15
- * `acp-agent.ts` drives it from five places: {@link SessionTitles.onPrompt} and
16
- * {@link SessionTitles.onAssistantText} to collect text,
17
- * {@link SessionTitles.onPromptQueued} once a prompt is sent to the CLI,
18
- * {@link SessionTitles.onTurnEnd} at `session_state_changed: idle`, and
19
- * {@link SessionTitles.reset} on `conversation_reset`.
14
+ * {@link SessionTitles} holds the per-session state and is owned by the
15
+ * session, in the v1 core (`acp-agent.ts`) and the v2 core
16
+ * (`v2/session.ts`). Each drives it from the same places:
17
+ * {@link SessionTitles.onPrompt} and {@link SessionTitles.onAssistantText} to
18
+ * collect text, {@link SessionTitles.onPromptQueued} once a prompt is sent to
19
+ * the CLI, {@link SessionTitles.onTurnEnd} at `session_state_changed: idle`,
20
+ * and, in v1, {@link SessionTitles.reset} on `conversation_reset`.
20
21
  */
21
- import type { ContentBlock, PromptRequest } from "@agentclientprotocol/sdk/unstable";
22
- import type { ClaudeAcpAgent, Session } from "./acp-agent.js";
22
+ import type { ContentBlock, PromptRequest, SessionNotification } from "@agentclientprotocol/sdk/unstable";
23
+ import { type Query } from "@anthropic-ai/claude-agent-sdk";
24
+ /** What titles read of their session. */
25
+ export interface TitledSession {
26
+ readonly query: Query;
27
+ readonly queryClosed?: boolean;
28
+ /** Whether a cancel stopped the session's work: no title is generated then. */
29
+ readonly cancelled?: boolean;
30
+ readonly cwd: string;
31
+ }
32
+ /** What titles need of the core that serves the session (`ClaudeAcpAgent` in v1). */
33
+ export interface TitleOwner {
34
+ readonly client: {
35
+ sessionUpdate(notification: SessionNotification): Promise<void>;
36
+ };
37
+ readonly logger: {
38
+ error: (...args: any[]) => void;
39
+ };
40
+ /** The live sessions by id: a session replaced or closed meanwhile adopts no title. */
41
+ readonly sessions: Readonly<Record<string, TitledSession | undefined>>;
42
+ /** The title as the client shows it, such as with an archive prefix removed. */
43
+ clientTitle?(title: string): string;
44
+ }
23
45
  export declare function sanitizeTitle(text: string): string;
24
46
  /** Rolling text a title is generated from: `previous` plus `text`, keeping only
25
47
  * the trailing {@link MAX_TITLE_CONTEXT_LENGTH} characters. */
@@ -57,7 +79,7 @@ export declare class SessionTitles {
57
79
  get storedTitle(): string | undefined;
58
80
  /** The title last published, as the client shows it. */
59
81
  get shownTitle(): string | undefined;
60
- constructor(agent: ClaudeAcpAgent, sessionId: string);
82
+ constructor(agent: TitleOwner, sessionId: string);
61
83
  /** Collect a prompt's own text for the title, skipping openers not worth
62
84
  * titling after. No-op once the title is settled. */
63
85
  onPrompt(prompt: PromptRequest["prompt"]): void;
@@ -69,7 +91,7 @@ export declare class SessionTitles {
69
91
  * prompt alone is the description, because the CLI titles from the prompt
70
92
  * alone. When this yields no title, the stored summary is published and
71
93
  * the next prompt tries again. */
72
- onPromptQueued(session: Session, prompt: PromptRequest["prompt"]): void;
94
+ onPromptQueued(session: TitledSession, prompt: PromptRequest["prompt"]): void;
73
95
  /** Collect the assistant's own answer for the title. Chunks are appended
74
96
  * verbatim so streamed text reassembles. No-op once the title is settled. */
75
97
  onAssistantText(content: ContentBlock): void;
@@ -89,7 +111,7 @@ export declare class SessionTitles {
89
111
  * turn-end must not wait on it. That covers a prompt too short to title
90
112
  * from, such as "hi". Only when that is not possible do we fall back to
91
113
  * `summary`, which for an SDK-driven session is just the raw first prompt. */
92
- onTurnEnd(session: Session): Promise<void>;
114
+ onTurnEnd(session: TitledSession): Promise<void>;
93
115
  /** Applies a title that the client chose (a rename, an archive or an
94
116
  * unarchive). Settles the title for good, waits for a generation in flight
95
117
  * so that its persisted title cannot land after this one, persists the
@@ -102,7 +124,7 @@ export declare class SessionTitles {
102
124
  * have it. Both come from the session file, as `session/list` reports
103
125
  * them; a session with no file yet sends the last title published, if any,
104
126
  * without `updatedAt`. */
105
- publishCurrent(session: Session): Promise<void>;
127
+ publishCurrent(session: TitledSession): Promise<void>;
106
128
  /** Records a title the CLI took, as soon as it took it. */
107
129
  rememberStoredTitle(title: string): void;
108
130
  /** Read the SDK's stored info for this session. A missing session file or read
@@ -1 +1 @@
1
- {"version":3,"file":"session-titles.d.ts","sourceRoot":"","sources":["../src/session-titles.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAErF,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AA+B9D,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAqBlD;AAED;gEACgE;AAChE,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAGrF;AAYD;;iDAEiD;AACjD,qBAAa,aAAa;IA0CtB,OAAO,CAAC,QAAQ,CAAC,KAAK;IACtB,OAAO,CAAC,QAAQ,CAAC,SAAS;IA1C5B;sEACkE;IAClE,OAAO,CAAC,SAAS,CAAC,CAAS;IAE3B;yEACqE;IACrE,OAAO,CAAC,OAAO,CAAC,CAAS;IAEz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K0D;IACpD,gBAAgB,CACpB,OAAO,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,KAAK,MAAM,CAAC,GAAG,SAAS,EACtE,OAAO,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,GAAG,IAAI,CAAC,GAChD,OAAO,CAAC,IAAI,CAAC;IAkChB;;;;+BAI2B;IACrB,cAAc,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAqB3D,2DAA2D;IAC3D,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAIxC;oFACgF;YAClE,eAAe;IAS7B,uEAAuE;YACzD,OAAO;IAgBrB;iFAC6E;IAC7E,OAAO,CAAC,UAAU;IAUlB;;8DAE0D;IAC1D,OAAO,CAAC,eAAe;IASvB;;;wCAGoC;YACtB,eAAe;IAgB7B;;;;+EAI2E;YAC7D,oBAAoB;CAoCnC"}
@@ -11,12 +11,13 @@
11
11
  * `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` or
12
12
  * `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` set), the same request generates it.
13
13
  *
14
- * {@link SessionTitles} holds the per-session state and is owned by `Session`.
15
- * `acp-agent.ts` drives it from five places: {@link SessionTitles.onPrompt} and
16
- * {@link SessionTitles.onAssistantText} to collect text,
17
- * {@link SessionTitles.onPromptQueued} once a prompt is sent to the CLI,
18
- * {@link SessionTitles.onTurnEnd} at `session_state_changed: idle`, and
19
- * {@link SessionTitles.reset} on `conversation_reset`.
14
+ * {@link SessionTitles} holds the per-session state and is owned by the
15
+ * session, in the v1 core (`acp-agent.ts`) and the v2 core
16
+ * (`v2/session.ts`). Each drives it from the same places:
17
+ * {@link SessionTitles.onPrompt} and {@link SessionTitles.onAssistantText} to
18
+ * collect text, {@link SessionTitles.onPromptQueued} once a prompt is sent to
19
+ * the CLI, {@link SessionTitles.onTurnEnd} at `session_state_changed: idle`,
20
+ * and, in v1, {@link SessionTitles.reset} on `conversation_reset`.
20
21
  */
21
22
  import { getSessionInfo } from "@anthropic-ai/claude-agent-sdk";
22
23
  import { ExplicitTitle } from "./session-index/explicit-title.js";
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Token usage as Claude Code reports it: the context window figures of
3
+ * `usage_update` and the `_meta.quota` of a turn. Shared by the v1 core and
4
+ * the v2 core.
5
+ */
6
+ import type { ModelUsage } from "@anthropic-ai/claude-agent-sdk";
7
+ export type AccumulatedUsage = {
8
+ inputTokens: number;
9
+ outputTokens: number;
10
+ cachedReadTokens: number;
11
+ cachedWriteTokens: number;
12
+ };
13
+ /** Per-model token tallies keyed by the model id the SDK reported them under
14
+ * (its resolved spelling, e.g. "claude-opus-5[1m]"). */
15
+ export type ModelTokenTally = Record<string, AccumulatedUsage>;
16
+ export type UsageSnapshot = {
17
+ input_tokens: number;
18
+ output_tokens: number;
19
+ cache_read_input_tokens: number;
20
+ cache_creation_input_tokens: number;
21
+ };
22
+ export declare const ZERO_USAGE: Readonly<{
23
+ input_tokens: 0;
24
+ output_tokens: 0;
25
+ cache_read_input_tokens: 0;
26
+ cache_creation_input_tokens: 0;
27
+ }>;
28
+ export declare const DEFAULT_CONTEXT_WINDOW = 200000;
29
+ /** `_meta.quota` for work that spent `usage` in its main agent loop and
30
+ * `modelUsage` by model (see `turnQuotaMeta` in `acp-agent.ts`). */
31
+ export declare function quotaMeta(usage: AccumulatedUsage, modelUsage: ModelTokenTally | undefined): {
32
+ quota: {
33
+ token_count: {
34
+ totalTokens: number;
35
+ inputTokens: number;
36
+ cachedInputTokens: number;
37
+ cachedWriteTokens: number;
38
+ outputTokens: number;
39
+ reasoningOutputTokens: number;
40
+ };
41
+ model_usage: {
42
+ model: string;
43
+ token_count: {
44
+ totalTokens: number;
45
+ inputTokens: number;
46
+ cachedInputTokens: number;
47
+ cachedWriteTokens: number;
48
+ outputTokens: number;
49
+ reasoningOutputTokens: number;
50
+ };
51
+ }[];
52
+ };
53
+ };
54
+ /** Sum a tally's four counters. Per the Anthropic API `inputTokens` excludes
55
+ * the cache counters, so this is not double-counting (see `totalTokens`). */
56
+ export declare function tallyTotal(usage: AccumulatedUsage): number;
57
+ /** Project `result.modelUsage` into our tally shape. Counters are coerced the
58
+ * way `snapshotFromUsage` coerces the stream's: third-party backends have been
59
+ * observed omitting fields, and a missing or NaN counter must not reach the
60
+ * wire as NaN (which `JSON.stringify` writes as `null`). */
61
+ export declare function normalizeModelUsage(modelUsage: Record<string, ModelUsage> | undefined): ModelTokenTally;
62
+ /** `current - previous` per model, dropping models with nothing to report so a
63
+ * turn only lists the models it actually ran on. A reading that fell BELOW the
64
+ * previous one means the running total restarted under us (a mid-session
65
+ * /clear, a zeroed crash result): there is no usable reference left to
66
+ * subtract, so the reading itself is the increment. */
67
+ export declare function modelUsageIncrement(current: ModelTokenTally, previous: ModelTokenTally): ModelTokenTally;
68
+ /** The per-model rows for the first result of a resumed session. Its
69
+ * `modelUsage` reading continues from the totals the transcript saved (SDK
70
+ * 0.3.277+; older transcripts may hold none), so there is no earlier reading
71
+ * to subtract from, and taking the reading itself would charge the whole
72
+ * pre-resume history to this one turn. The result's own `usage` is per-turn
73
+ * (main agent loop only, like the response's `usage`), so it stands in under
74
+ * the turn's top-level model — `key` is that model's `modelUsage` spelling
75
+ * when the reading has one, else the assistant message's own. Any subagent
76
+ * spend on this one turn goes unlisted rather than over-listed. */
77
+ export declare function resumedFirstResultModelUsage(usage: {
78
+ input_tokens?: number | null;
79
+ output_tokens?: number | null;
80
+ cache_read_input_tokens?: number | null;
81
+ cache_creation_input_tokens?: number | null;
82
+ }, key: string | null): ModelTokenTally;
83
+ /** Fold `increment` into `base` per model — the per-model counterpart of the
84
+ * `+=` the turn's flat accumulator uses. */
85
+ export declare function addModelUsage(base: ModelTokenTally, increment: ModelTokenTally): ModelTokenTally;
86
+ /** Sum all four fields as a proxy for post-turn context occupancy: the current
87
+ * turn's output becomes next turn's input. Per the Anthropic API, input_tokens
88
+ * excludes cache tokens — cache_read and cache_creation are reported
89
+ * separately — so summing all four is not double-counting. */
90
+ export declare function totalTokens(usage: UsageSnapshot): number;
91
+ /** Project a nullable API usage object into our non-null snapshot shape.
92
+ * Both SDK message_start and assistant message `usage` have `number | null`
93
+ * cache fields; we coerce absent values to 0 so `totalTokens` never hits
94
+ * NaN. `input_tokens`/`output_tokens` are typed `number` by the SDK but
95
+ * synthetic or third-party-backend stream events have been observed emitting
96
+ * them as null/undefined — coerce those too so a malformed upstream event
97
+ * can't leak NaN into the wire `used` field. Delta events have different
98
+ * semantics (cumulative + prev fallback) and are handled inline. */
99
+ export declare function snapshotFromUsage(usage: {
100
+ input_tokens?: number | null;
101
+ output_tokens?: number | null;
102
+ cache_read_input_tokens?: number | null;
103
+ cache_creation_input_tokens?: number | null;
104
+ }): UsageSnapshot;
105
+ /** Best-effort first guess of a model's context window, used to seed the
106
+ * window synchronously (via `immediateContextWindow`) until a `result` message
107
+ * arrives with the authoritative `modelUsage` value.
108
+ *
109
+ * Anthropic 1M-context variants encode "1m" as a distinct token in the SDK
110
+ * model ID (e.g., "claude-opus-4-6-1m"), which `\b1m\b` catches without also
111
+ * matching things like "10m" or embedded substrings. Semantic aliases like
112
+ * `default` carry no such token in the ID, but their `resolvedModel` and the
113
+ * SDK's human-facing `displayName`/`description` can (e.g.
114
+ * "claude-opus-4-8[1m]", "Opus 4.7 (1M context)"), so callers pass those too.
115
+ * This text scan can't catch every model — some resolve to extended-context
116
+ * models with no "1m" anywhere (e.g. `sonnet` → claude-sonnet-5, natively
117
+ * ~1M). Such a miss falls back to the default window, is refined by the
118
+ * background `getContextUsage` (`refreshContextWindowInBackground`), and is
119
+ * corrected by `result.modelUsage` (and cached) within one turn. */
120
+ export declare function inferContextWindowFromModel(...texts: Array<string | undefined>): number | null;
121
+ export declare function getMatchingModelUsage(modelUsage: Record<string, ModelUsage>, currentModel: string): {
122
+ key: string;
123
+ usage: ModelUsage;
124
+ } | undefined;
125
+ //# sourceMappingURL=session-usage.d.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