@agentclientprotocol/claude-agent-acp 0.102.1-preview.1 → 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 (203) hide show
  1. package/README.md +5 -1
  2. package/dist/acp-agent.d.ts +113 -439
  3. package/dist/acp-agent.d.ts.map +1 -1
  4. package/dist/acp-agent.js +362 -2409
  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/prompt-suggestions.d.ts +29 -0
  46. package/dist/prompt-suggestions.d.ts.map +1 -1
  47. package/dist/prompt-suggestions.js +45 -0
  48. package/dist/providers.d.ts +139 -0
  49. package/dist/providers.d.ts.map +1 -0
  50. package/dist/providers.js +286 -0
  51. package/dist/remote-control.d.ts +62 -0
  52. package/dist/remote-control.d.ts.map +1 -0
  53. package/dist/remote-control.js +78 -0
  54. package/dist/result-end.d.ts +39 -0
  55. package/dist/result-end.d.ts.map +1 -0
  56. package/dist/result-end.js +50 -0
  57. package/dist/serve.d.ts +7 -2
  58. package/dist/serve.d.ts.map +1 -1
  59. package/dist/serve.js +10 -5
  60. package/dist/session-config-ids.d.ts +1 -0
  61. package/dist/session-config-ids.d.ts.map +1 -1
  62. package/dist/session-config-ids.js +1 -0
  63. package/dist/session-config-options.d.ts +64 -0
  64. package/dist/session-config-options.d.ts.map +1 -0
  65. package/dist/session-config-options.js +162 -0
  66. package/dist/session-effort.d.ts +67 -0
  67. package/dist/session-effort.d.ts.map +1 -1
  68. package/dist/session-effort.js +98 -0
  69. package/dist/session-env.d.ts +22 -0
  70. package/dist/session-env.d.ts.map +1 -0
  71. package/dist/session-env.js +66 -0
  72. package/dist/session-fast-mode.d.ts +83 -0
  73. package/dist/session-fast-mode.d.ts.map +1 -0
  74. package/dist/session-fast-mode.js +142 -0
  75. package/dist/session-index/connection.d.ts +2 -5
  76. package/dist/session-index/connection.d.ts.map +1 -1
  77. package/dist/session-index/connection.js +3 -5
  78. package/dist/session-mode.d.ts +1 -0
  79. package/dist/session-mode.d.ts.map +1 -1
  80. package/dist/session-mode.js +1 -1
  81. package/dist/session-model.d.ts +41 -0
  82. package/dist/session-model.d.ts.map +1 -1
  83. package/dist/session-model.js +110 -45
  84. package/dist/session-notices.d.ts +44 -0
  85. package/dist/session-notices.d.ts.map +1 -1
  86. package/dist/session-notices.js +68 -0
  87. package/dist/session-titles.d.ts +34 -12
  88. package/dist/session-titles.d.ts.map +1 -1
  89. package/dist/session-titles.js +7 -6
  90. package/dist/session-usage.d.ts +125 -0
  91. package/dist/session-usage.d.ts.map +1 -0
  92. package/dist/session-usage.js +196 -0
  93. package/dist/streamed-text.d.ts +33 -0
  94. package/dist/streamed-text.d.ts.map +1 -0
  95. package/dist/streamed-text.js +71 -0
  96. package/dist/subagent-configuration.d.ts +32 -0
  97. package/dist/subagent-configuration.d.ts.map +1 -0
  98. package/dist/subagent-configuration.js +70 -0
  99. package/dist/subagent-replay.d.ts +18 -0
  100. package/dist/subagent-replay.d.ts.map +1 -1
  101. package/dist/subagent-replay.js +25 -15
  102. package/dist/tool-calls/client-capabilities.d.ts +8 -8
  103. package/dist/tool-calls/client-capabilities.js +4 -4
  104. package/dist/tool-calls/renderer.d.ts +4 -5
  105. package/dist/tool-calls/renderer.d.ts.map +1 -1
  106. package/dist/tool-calls/renderer.js +4 -5
  107. package/dist/turn-events.d.ts +6 -46
  108. package/dist/turn-events.d.ts.map +1 -1
  109. package/dist/v2/agent.d.ts +7 -11
  110. package/dist/v2/agent.d.ts.map +1 -1
  111. package/dist/v2/agent.js +751 -331
  112. package/dist/v2/air.d.ts +33 -0
  113. package/dist/v2/air.d.ts.map +1 -0
  114. package/dist/v2/air.js +29 -0
  115. package/dist/v2/auth.d.ts +97 -0
  116. package/dist/v2/auth.d.ts.map +1 -0
  117. package/dist/v2/auth.js +216 -0
  118. package/dist/v2/background.d.ts +27 -16
  119. package/dist/v2/background.d.ts.map +1 -1
  120. package/dist/v2/background.js +4 -32
  121. package/dist/v2/child-config.d.ts +55 -0
  122. package/dist/v2/child-config.d.ts.map +1 -0
  123. package/dist/v2/child-config.js +92 -0
  124. package/dist/v2/clear-context.d.ts +94 -0
  125. package/dist/v2/clear-context.d.ts.map +1 -0
  126. package/dist/v2/clear-context.js +176 -0
  127. package/dist/v2/commands.d.ts +46 -0
  128. package/dist/v2/commands.d.ts.map +1 -0
  129. package/dist/v2/commands.js +54 -0
  130. package/dist/v2/config.d.ts +187 -0
  131. package/dist/v2/config.d.ts.map +1 -0
  132. package/dist/v2/config.js +494 -0
  133. package/dist/v2/elicitation.d.ts +93 -0
  134. package/dist/v2/elicitation.d.ts.map +1 -0
  135. package/dist/v2/elicitation.js +160 -0
  136. package/dist/v2/file-changes.d.ts +61 -0
  137. package/dist/v2/file-changes.d.ts.map +1 -0
  138. package/dist/v2/file-changes.js +108 -0
  139. package/dist/v2/file-preview.d.ts +18 -0
  140. package/dist/v2/file-preview.d.ts.map +1 -0
  141. package/dist/v2/file-preview.js +29 -0
  142. package/dist/v2/initialize.d.ts +10 -24
  143. package/dist/v2/initialize.d.ts.map +1 -1
  144. package/dist/v2/initialize.js +4 -111
  145. package/dist/v2/outcome.d.ts +81 -0
  146. package/dist/v2/outcome.d.ts.map +1 -0
  147. package/dist/v2/outcome.js +165 -0
  148. package/dist/v2/permissions.d.ts +92 -0
  149. package/dist/v2/permissions.d.ts.map +1 -0
  150. package/dist/v2/permissions.js +162 -0
  151. package/dist/v2/prompt.d.ts +2 -42
  152. package/dist/v2/prompt.d.ts.map +1 -1
  153. package/dist/v2/prompt.js +2 -119
  154. package/dist/v2/remote-control.d.ts +41 -0
  155. package/dist/v2/remote-control.d.ts.map +1 -0
  156. package/dist/v2/remote-control.js +63 -0
  157. package/dist/v2/reports.d.ts +198 -0
  158. package/dist/v2/reports.d.ts.map +1 -0
  159. package/dist/v2/reports.js +487 -0
  160. package/dist/v2/restarts.d.ts +128 -0
  161. package/dist/v2/restarts.d.ts.map +1 -0
  162. package/dist/v2/restarts.js +348 -0
  163. package/dist/v2/session-requests.d.ts +20 -0
  164. package/dist/v2/session-requests.d.ts.map +1 -0
  165. package/dist/v2/session-requests.js +108 -0
  166. package/dist/v2/session-update.d.ts +2 -13
  167. package/dist/v2/session-update.d.ts.map +1 -1
  168. package/dist/v2/session-update.js +2 -22
  169. package/dist/v2/session.d.ts +340 -41
  170. package/dist/v2/session.d.ts.map +1 -1
  171. package/dist/v2/session.js +1223 -141
  172. package/dist/v2/setup.d.ts +49 -0
  173. package/dist/v2/setup.d.ts.map +1 -0
  174. package/dist/v2/setup.js +62 -0
  175. package/dist/v2/stopped-work.d.ts +123 -0
  176. package/dist/v2/stopped-work.d.ts.map +1 -0
  177. package/dist/v2/stopped-work.js +210 -0
  178. package/dist/v2/stream.d.ts +228 -0
  179. package/dist/v2/stream.d.ts.map +1 -0
  180. package/dist/v2/stream.js +506 -0
  181. package/dist/v2/subagent-replay.d.ts +115 -0
  182. package/dist/v2/subagent-replay.d.ts.map +1 -0
  183. package/dist/v2/subagent-replay.js +479 -0
  184. package/dist/v2/subscription-guard.d.ts +60 -0
  185. package/dist/v2/subscription-guard.d.ts.map +1 -0
  186. package/dist/v2/subscription-guard.js +84 -0
  187. package/dist/v2/tasks.d.ts +492 -0
  188. package/dist/v2/tasks.d.ts.map +1 -0
  189. package/dist/v2/tasks.js +1728 -0
  190. package/dist/v2/terminal.d.ts.map +1 -1
  191. package/dist/v2/terminal.js +6 -1
  192. package/dist/v2/tool-call.d.ts +3 -2
  193. package/dist/v2/tool-call.d.ts.map +1 -1
  194. package/dist/v2/update-translator.d.ts +36 -0
  195. package/dist/v2/update-translator.d.ts.map +1 -0
  196. package/dist/v2/update-translator.js +80 -0
  197. package/dist/workflow-progress.d.ts +23 -0
  198. package/dist/workflow-progress.d.ts.map +1 -1
  199. package/dist/workflow-progress.js +31 -8
  200. package/package.json +1 -1
  201. package/dist/v2/permission.d.ts +0 -28
  202. package/dist/v2/permission.d.ts.map +0 -1
  203. package/dist/v2/permission.js +0 -41
@@ -88,3 +88,71 @@ export function splitNoticeText(text, fallbackTitle) {
88
88
  }
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;IAEzB;;;8EAG0E;IAC1E,OAAO,CAAC,OAAO,CAAS;IAExB;;kEAE8D;IAC9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M,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.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-usage.d.ts","sourceRoot":"","sources":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uB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxC,2BAA2B,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7C,EACD,GAAG,EAAE,MAAM,GAAG,IAAI,GACjB,eAAe,CAWjB;AAED;6CAC6C;AAC7C,wBAAgB,aAAa,CAAC,IAAI,EAAE,eAAe,EAAE,SAAS,EAAE,eAAe,GAAG,eAAe,CAchG;AAED;;;+DAG+D;AAC/D,wBAAgB,WAAW,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,CAOxD;AAED;;;;;;;qEAOqE;AACrE,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IACvC,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,uBAAuB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxC,2BAA2B,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7C,GAAG,aAAa,CAOhB;AAUD;;;;;;;;;;;;;;qEAcqE;AACrE,wBAAgB,2BAA2B,CAAC,GAAG,KAAK,EAAE,KAAK,CAAC,MAAM,GAAG,SAAS,CAAC,GAAG,MAAM,GAAG,IAAI,CAG9F;AAED,wBAAgB,qBAAqB,CACnC,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,EACtC,YAAY,EAAE,MAAM;;;cAsBrB"}
@@ -0,0 +1,196 @@
1
+ export const ZERO_USAGE = Object.freeze({
2
+ input_tokens: 0,
3
+ output_tokens: 0,
4
+ cache_read_input_tokens: 0,
5
+ cache_creation_input_tokens: 0,
6
+ });
7
+ export const DEFAULT_CONTEXT_WINDOW = 200000;
8
+ /** `_meta.quota` for work that spent `usage` in its main agent loop and
9
+ * `modelUsage` by model (see `turnQuotaMeta` in `acp-agent.ts`). */
10
+ export function quotaMeta(usage, modelUsage) {
11
+ return {
12
+ quota: {
13
+ token_count: quotaTokenCount(usage),
14
+ model_usage: Object.entries(modelUsage ?? {}).map(([model, usage]) => ({
15
+ model,
16
+ token_count: quotaTokenCount(usage),
17
+ })),
18
+ },
19
+ };
20
+ }
21
+ /** One `token_count` object. `cachedInputTokens` is cache reads, matching
22
+ * codex's field; Claude also reports cache writes, which codex has no slot
23
+ * for, so those ride along in an extra sibling (the same name the ACP `usage`
24
+ * field already uses) and are counted in `totalTokens`. `reasoningOutputTokens`
25
+ * is always 0: Claude bills thinking inside its output tokens and never breaks
26
+ * it out — the key is kept so the shape stays uniform across agents. */
27
+ function quotaTokenCount(usage) {
28
+ return {
29
+ totalTokens: tallyTotal(usage),
30
+ inputTokens: usage.inputTokens,
31
+ cachedInputTokens: usage.cachedReadTokens,
32
+ cachedWriteTokens: usage.cachedWriteTokens,
33
+ outputTokens: usage.outputTokens,
34
+ reasoningOutputTokens: 0,
35
+ };
36
+ }
37
+ /** Sum a tally's four counters. Per the Anthropic API `inputTokens` excludes
38
+ * the cache counters, so this is not double-counting (see `totalTokens`). */
39
+ export function tallyTotal(usage) {
40
+ return usage.inputTokens + usage.outputTokens + usage.cachedReadTokens + usage.cachedWriteTokens;
41
+ }
42
+ /** Project `result.modelUsage` into our tally shape. Counters are coerced the
43
+ * way `snapshotFromUsage` coerces the stream's: third-party backends have been
44
+ * observed omitting fields, and a missing or NaN counter must not reach the
45
+ * wire as NaN (which `JSON.stringify` writes as `null`). */
46
+ export function normalizeModelUsage(modelUsage) {
47
+ const tally = {};
48
+ for (const [model, usage] of Object.entries(modelUsage ?? {})) {
49
+ tally[model] = {
50
+ inputTokens: finiteCount(usage?.inputTokens),
51
+ outputTokens: finiteCount(usage?.outputTokens),
52
+ cachedReadTokens: finiteCount(usage?.cacheReadInputTokens),
53
+ cachedWriteTokens: finiteCount(usage?.cacheCreationInputTokens),
54
+ };
55
+ }
56
+ return tally;
57
+ }
58
+ function finiteCount(value) {
59
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
60
+ }
61
+ /** `current - previous` per model, dropping models with nothing to report so a
62
+ * turn only lists the models it actually ran on. A reading that fell BELOW the
63
+ * previous one means the running total restarted under us (a mid-session
64
+ * /clear, a zeroed crash result): there is no usable reference left to
65
+ * subtract, so the reading itself is the increment. */
66
+ export function modelUsageIncrement(current, previous) {
67
+ const increment = {};
68
+ for (const [model, usage] of Object.entries(current)) {
69
+ const base = previous[model];
70
+ const subtracted = base
71
+ ? {
72
+ inputTokens: usage.inputTokens - base.inputTokens,
73
+ outputTokens: usage.outputTokens - base.outputTokens,
74
+ cachedReadTokens: usage.cachedReadTokens - base.cachedReadTokens,
75
+ cachedWriteTokens: usage.cachedWriteTokens - base.cachedWriteTokens,
76
+ }
77
+ : usage;
78
+ const rewound = Object.values(subtracted).some((count) => count < 0);
79
+ const resolved = rewound ? usage : subtracted;
80
+ if (tallyTotal(resolved) > 0) {
81
+ increment[model] = resolved;
82
+ }
83
+ }
84
+ return increment;
85
+ }
86
+ /** The per-model rows for the first result of a resumed session. Its
87
+ * `modelUsage` reading continues from the totals the transcript saved (SDK
88
+ * 0.3.277+; older transcripts may hold none), so there is no earlier reading
89
+ * to subtract from, and taking the reading itself would charge the whole
90
+ * pre-resume history to this one turn. The result's own `usage` is per-turn
91
+ * (main agent loop only, like the response's `usage`), so it stands in under
92
+ * the turn's top-level model — `key` is that model's `modelUsage` spelling
93
+ * when the reading has one, else the assistant message's own. Any subagent
94
+ * spend on this one turn goes unlisted rather than over-listed. */
95
+ export function resumedFirstResultModelUsage(usage, key) {
96
+ if (key === null) {
97
+ return {};
98
+ }
99
+ const row = {
100
+ inputTokens: finiteCount(usage.input_tokens),
101
+ outputTokens: finiteCount(usage.output_tokens),
102
+ cachedReadTokens: finiteCount(usage.cache_read_input_tokens),
103
+ cachedWriteTokens: finiteCount(usage.cache_creation_input_tokens),
104
+ };
105
+ return tallyTotal(row) > 0 ? { [key]: row } : {};
106
+ }
107
+ /** Fold `increment` into `base` per model — the per-model counterpart of the
108
+ * `+=` the turn's flat accumulator uses. */
109
+ export function addModelUsage(base, increment) {
110
+ const merged = { ...base };
111
+ for (const [model, usage] of Object.entries(increment)) {
112
+ const existing = merged[model];
113
+ merged[model] = existing
114
+ ? {
115
+ inputTokens: existing.inputTokens + usage.inputTokens,
116
+ outputTokens: existing.outputTokens + usage.outputTokens,
117
+ cachedReadTokens: existing.cachedReadTokens + usage.cachedReadTokens,
118
+ cachedWriteTokens: existing.cachedWriteTokens + usage.cachedWriteTokens,
119
+ }
120
+ : usage;
121
+ }
122
+ return merged;
123
+ }
124
+ /** Sum all four fields as a proxy for post-turn context occupancy: the current
125
+ * turn's output becomes next turn's input. Per the Anthropic API, input_tokens
126
+ * excludes cache tokens — cache_read and cache_creation are reported
127
+ * separately — so summing all four is not double-counting. */
128
+ export function totalTokens(usage) {
129
+ return (usage.input_tokens +
130
+ usage.output_tokens +
131
+ usage.cache_read_input_tokens +
132
+ usage.cache_creation_input_tokens);
133
+ }
134
+ /** Project a nullable API usage object into our non-null snapshot shape.
135
+ * Both SDK message_start and assistant message `usage` have `number | null`
136
+ * cache fields; we coerce absent values to 0 so `totalTokens` never hits
137
+ * NaN. `input_tokens`/`output_tokens` are typed `number` by the SDK but
138
+ * synthetic or third-party-backend stream events have been observed emitting
139
+ * them as null/undefined — coerce those too so a malformed upstream event
140
+ * can't leak NaN into the wire `used` field. Delta events have different
141
+ * semantics (cumulative + prev fallback) and are handled inline. */
142
+ export function snapshotFromUsage(usage) {
143
+ return {
144
+ input_tokens: usage.input_tokens ?? 0,
145
+ output_tokens: usage.output_tokens ?? 0,
146
+ cache_read_input_tokens: usage.cache_read_input_tokens ?? 0,
147
+ cache_creation_input_tokens: usage.cache_creation_input_tokens ?? 0,
148
+ };
149
+ }
150
+ function commonPrefixLength(a, b) {
151
+ let i = 0;
152
+ while (i < a.length && i < b.length && a[i] === b[i]) {
153
+ i++;
154
+ }
155
+ return i;
156
+ }
157
+ /** Best-effort first guess of a model's context window, used to seed the
158
+ * window synchronously (via `immediateContextWindow`) until a `result` message
159
+ * arrives with the authoritative `modelUsage` value.
160
+ *
161
+ * Anthropic 1M-context variants encode "1m" as a distinct token in the SDK
162
+ * model ID (e.g., "claude-opus-4-6-1m"), which `\b1m\b` catches without also
163
+ * matching things like "10m" or embedded substrings. Semantic aliases like
164
+ * `default` carry no such token in the ID, but their `resolvedModel` and the
165
+ * SDK's human-facing `displayName`/`description` can (e.g.
166
+ * "claude-opus-4-8[1m]", "Opus 4.7 (1M context)"), so callers pass those too.
167
+ * This text scan can't catch every model — some resolve to extended-context
168
+ * models with no "1m" anywhere (e.g. `sonnet` → claude-sonnet-5, natively
169
+ * ~1M). Such a miss falls back to the default window, is refined by the
170
+ * background `getContextUsage` (`refreshContextWindowInBackground`), and is
171
+ * corrected by `result.modelUsage` (and cached) within one turn. */
172
+ export function inferContextWindowFromModel(...texts) {
173
+ if (texts.some((text) => text != null && /\b1m\b/i.test(text)))
174
+ return 1_000_000;
175
+ return null;
176
+ }
177
+ export function getMatchingModelUsage(modelUsage, currentModel) {
178
+ let bestKey = null;
179
+ let bestLen = 0;
180
+ for (const key of Object.keys(modelUsage)) {
181
+ const len = commonPrefixLength(key, currentModel);
182
+ if (len > bestLen) {
183
+ bestLen = len;
184
+ bestKey = key;
185
+ }
186
+ }
187
+ if (bestKey) {
188
+ // `bestKey` is the SDK's resolved model id (e.g. "claude-sonnet-5[1m]"),
189
+ // the same spelling as ModelInfo.resolvedModel — the primary key the
190
+ // window is cached under. `currentModel` (the assistant message's
191
+ // `.model`) can be the bare form (e.g. "claude-sonnet-5"); the result
192
+ // handler caches under that spelling too, for seed-time reads that fall
193
+ // back to a bare id (rows without `resolvedModel`).
194
+ return { key: bestKey, usage: modelUsage[bestKey] };
195
+ }
196
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The text and thinking of an assistant message that streamed live as
3
+ * deltas, and what its consolidated message adds to them. Shared by the v1
4
+ * core and the v2 core.
5
+ */
6
+ import type { SDKPartialAssistantMessage } from "@anthropic-ai/claude-agent-sdk";
7
+ /** Text or thinking that streamed live as deltas, accumulated per block. */
8
+ export type StreamedBlock = {
9
+ index: number;
10
+ type: "text" | "thinking";
11
+ text: string;
12
+ };
13
+ /**
14
+ * Records the text or thinking that `event` streamed in `streamedBlocks`.
15
+ * Contiguous deltas of the same block (same index and type) extend the
16
+ * current entry; anything else opens a new one. Other events change nothing.
17
+ */
18
+ export declare function recordStreamedDelta(streamedBlocks: StreamedBlock[], event: SDKPartialAssistantMessage["event"]): void;
19
+ /**
20
+ * The blocks of a consolidated assistant message without the text that
21
+ * already streamed as deltas.
22
+ *
23
+ * Each assembled text/thinking block is diffed against the streamed blocks in
24
+ * document order: nothing is left if it streamed in full (the common case),
25
+ * the whole block if it never streamed (a non-streaming gateway), and just the
26
+ * tail if the stream was cut short mid-block. Matching on content rather than
27
+ * the message id keeps the dedupe robust for gateways without a stable id.
28
+ * Tool-use and other blocks pass through untouched.
29
+ */
30
+ export declare function unstreamedRemainder<Block extends {
31
+ type: string;
32
+ }>(blocks: Block[], streamedBlocks: StreamedBlock[]): Block[];
33
+ //# sourceMappingURL=streamed-text.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"streamed-text.d.ts","sourceRoot":"","sources":["../src/streamed-text.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AAEjF,4EAA4E;AAC5E,MAAM,MAAM,aAAa,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,GAAG,UAAU,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAEvF;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,cAAc,EAAE,aAAa,EAAE,EAC/B,KAAK,EAAE,0BAA0B,CAAC,OAAO,CAAC,GACzC,IAAI,CAoBN;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,SAAS;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,EAChE,MAAM,EAAE,KAAK,EAAE,EACf,cAAc,EAAE,aAAa,EAAE,GAC9B,KAAK,EAAE,CA+BT"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Records the text or thinking that `event` streamed in `streamedBlocks`.
3
+ * Contiguous deltas of the same block (same index and type) extend the
4
+ * current entry; anything else opens a new one. Other events change nothing.
5
+ */
6
+ export function recordStreamedDelta(streamedBlocks, event) {
7
+ if (event.type !== "content_block_delta")
8
+ return;
9
+ const delta = event.delta;
10
+ const chunk = delta.type === "text_delta"
11
+ ? { type: "text", text: delta.text }
12
+ : delta.type === "thinking_delta"
13
+ ? { type: "thinking", text: delta.thinking }
14
+ : undefined;
15
+ // Skip empty deltas (some gateways emit empty thinking chunks — #793):
16
+ // appending "" is a no-op, but pushing a "" entry would create a block the
17
+ // `text.length > 0` guard of `unstreamedRemainder` can never consume,
18
+ // stalling the diff cursor and re-emitting the next block as a duplicate.
19
+ if (!chunk?.text)
20
+ return;
21
+ const last = streamedBlocks[streamedBlocks.length - 1];
22
+ if (last && last.index === event.index && last.type === chunk.type) {
23
+ last.text += chunk.text;
24
+ }
25
+ else {
26
+ streamedBlocks.push({ index: event.index, type: chunk.type, text: chunk.text });
27
+ }
28
+ }
29
+ /**
30
+ * The blocks of a consolidated assistant message without the text that
31
+ * already streamed as deltas.
32
+ *
33
+ * Each assembled text/thinking block is diffed against the streamed blocks in
34
+ * document order: nothing is left if it streamed in full (the common case),
35
+ * the whole block if it never streamed (a non-streaming gateway), and just the
36
+ * tail if the stream was cut short mid-block. Matching on content rather than
37
+ * the message id keeps the dedupe robust for gateways without a stable id.
38
+ * Tool-use and other blocks pass through untouched.
39
+ */
40
+ export function unstreamedRemainder(blocks, streamedBlocks) {
41
+ const kept = [];
42
+ let streamPos = 0;
43
+ for (const item of blocks) {
44
+ if (item.type !== "text" && item.type !== "thinking") {
45
+ kept.push(item);
46
+ continue;
47
+ }
48
+ const block = item;
49
+ const full = (item.type === "text" ? block.text : block.thinking) ?? "";
50
+ // Empty assembled blocks carry nothing: drop them.
51
+ if (full.length === 0)
52
+ continue;
53
+ // A streamed block of the same type whose text is a prefix of this one
54
+ // was already delivered, at least partly. A non-empty streamed text is
55
+ // required so an empty or aborted streamed block does not swallow it.
56
+ const streamed = streamedBlocks[streamPos];
57
+ if (streamed &&
58
+ streamed.type === item.type &&
59
+ streamed.text.length > 0 &&
60
+ full.startsWith(streamed.text)) {
61
+ streamPos++;
62
+ const remainder = full.slice(streamed.text.length);
63
+ if (remainder.length === 0)
64
+ continue;
65
+ kept.push({ ...item, [item.type === "text" ? "text" : "thinking"]: remainder });
66
+ continue;
67
+ }
68
+ kept.push(item);
69
+ }
70
+ return kept;
71
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The configuration of a subagent's session, as its hooks report it. Both
3
+ * the v1 core (`ClaudeAcpAgent.subagentConfigurationHook`, for both forms of
4
+ * subagent sessions) and the v2 core (`v2/child-config.ts`)
5
+ * build a child's config options with these.
6
+ */
7
+ import type { SessionConfigOption, SessionModeState } from "@agentclientprotocol/sdk/unstable";
8
+ import type { AgentInfo, HookInput } from "@anthropic-ai/claude-agent-sdk";
9
+ import { type SubagentModels } from "./native-subagents.js";
10
+ /** What the root session knows that a child's options name. */
11
+ export type SubagentConfigurationContext = {
12
+ /** The root session's modes, for the name of the child's mode. */
13
+ availableModes: SessionModeState["availableModes"];
14
+ /** The root session's `model` entries, for the child's model. */
15
+ models: SubagentModels | undefined;
16
+ /** The custom agents of the session, for the description of the child's agent type. */
17
+ agents: readonly AgentInfo[];
18
+ };
19
+ /**
20
+ * The config options that a hook of a subagent (`agent_id`) reports of it:
21
+ * its permission mode, its model after a `PostModelSwitch`, its effort, and
22
+ * its agent type. Each option lists only the child's current value. Empty
23
+ * for a hook of the root session, and for one that reports none of these.
24
+ */
25
+ export declare function subagentHookOptions(input: HookInput, context: SubagentConfigurationContext): SessionConfigOption[];
26
+ /**
27
+ * A child's configuration, as it goes to the client: every option it holds,
28
+ * the mode first, then the model, the effort and the model config, then the
29
+ * rest in the order they came.
30
+ */
31
+ export declare function orderedSubagentConfiguration(options: Iterable<SessionConfigOption>): SessionConfigOption[];
32
+ //# sourceMappingURL=subagent-configuration.d.ts.map