@agentclientprotocol/claude-agent-acp 0.85.2-preview.4 → 0.85.2-preview.6

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.
@@ -1,5 +1,6 @@
1
1
  import { RequestError, } from "@agentclientprotocol/sdk";
2
2
  import { AIR_KIND_KEY, airOnlyMeta } from "./air-extension.js";
3
+ import { resolvePermissionMode } from "./permissions/modes.js";
3
4
  import { noticeOrTranscriptUpdate, noticeTranscriptText, sentenceCase, } from "./session-notices.js";
4
5
  export const MODE_CONFIG_ID = "mode";
5
6
  export const AUTO_MODE_FALLBACK = "acceptEdits";
@@ -11,6 +12,27 @@ const AUTO_MODE_FALLBACK_NOTICE = {
11
12
  title: "Auto mode unavailable",
12
13
  description: sentenceCase(AUTO_MODE_FALLBACK_REASON),
13
14
  };
15
+ /**
16
+ * The permission mode a new Claude query starts in.
17
+ *
18
+ * An explicit mode wins. A resume or a load continues in the mode of the last
19
+ * user record of the transcript. If that mode is unknown or not available now,
20
+ * for example bypass, the session starts in `defaultMode` of the settings.
21
+ */
22
+ export function resolveInitialPermissionMode(sources, logger, allowBypass) {
23
+ if (sources.explicit !== undefined) {
24
+ return resolvePermissionMode(sources.explicit, logger, allowBypass);
25
+ }
26
+ if (sources.resumed !== undefined) {
27
+ let rejected = false;
28
+ const mode = resolvePermissionMode(sources.resumed, { error: () => (rejected = true) }, allowBypass);
29
+ if (!rejected)
30
+ return mode;
31
+ logger.error(`Ignoring permission mode "${sources.resumed}" of the resumed transcript: ` +
32
+ `not available in this session.`);
33
+ }
34
+ return resolvePermissionMode(sources.defaultMode, logger, allowBypass);
35
+ }
14
36
  /** Owns session-mode policy and the ACP/SDK synchronization it requires. */
15
37
  export class SessionModeManager {
16
38
  options;
@@ -37,9 +37,10 @@ export interface TurnEvents {
37
37
  ended(outcome: TurnOutcome): void;
38
38
  /**
39
39
  * The turn failed. Without {@link inserted} before, Claude Code was not seen
40
- * taking the prompt in.
40
+ * taking the prompt in. `title`, when the agent has one, describes the
41
+ * failure for the user in plain text, such as "API Error: 529 Overloaded".
41
42
  */
42
- failed(error: unknown): void;
43
+ failed(error: unknown, title?: string): void;
43
44
  }
44
45
  /** Why a turn ended. Every ACP version has these reasons. */
45
46
  export type StopReason = "end_turn" | "max_tokens" | "max_turn_requests" | "refusal" | "cancelled";
@@ -1 +1 @@
1
- {"version":3,"file":"turn-events.d.ts","sourceRoot":"","sources":["../src/turn-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,WAAW,UAAU;IACzB;;;;;;OAMG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC;;;;;OAKG;IACH,YAAY,IAAI,IAAI,CAAC;IACrB;;;OAGG;IACH,OAAO,IAAI,IAAI,CAAC;IAChB;;;OAGG;IACH,KAAK,CAAC,OAAO,EAAE,WAAW,GAAG,IAAI,CAAC;IAClC;;;OAGG;IACH,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI,CAAC;CAC9B;AAED,6DAA6D;AAC7D,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,YAAY,GAAG,mBAAmB,GAAG,SAAS,GAAG,WAAW,CAAC;AAEnG,wBAAwB;AACxB,MAAM,MAAM,WAAW,GAAG;IACxB,UAAU,EAAE,UAAU,CAAC;IACvB,4DAA4D;IAC5D,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC"}
1
+ {"version":3,"file":"turn-events.d.ts","sourceRoot":"","sources":["../src/turn-events.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,WAAW,UAAU;IACzB;;;;;;OAMG;IACH,QAAQ,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC;;;;;OAKG;IACH,YAAY,IAAI,IAAI,CAAC;IACrB;;;OAGG;IACH,OAAO,IAAI,IAAI,CAAC;IAChB;;;OAGG;IACH,KAAK,CAAC,OAAO,EAAE,WAAW,GAAG,IAAI,CAAC;IAClC;;;;OAIG;IACH,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9C;AAED,6DAA6D;AAC7D,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,YAAY,GAAG,mBAAmB,GAAG,SAAS,GAAG,WAAW,CAAC;AAEnG,wBAAwB;AACxB,MAAM,MAAM,WAAW,GAAG;IACxB,UAAU,EAAE,UAAU,CAAC;IACvB,4DAA4D;IAC5D,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC"}
@@ -2,6 +2,8 @@ import type { SDKControlGetUsageResponse } from "@anthropic-ai/claude-agent-sdk"
2
2
  /** Validate the experimental SDK response at the runtime boundary. */
3
3
  export declare function parseUsageResponse(value: unknown): SDKControlGetUsageResponse | null;
4
4
  export declare function isUsageCommandText(text: string): boolean;
5
+ /** Escape the Markdown syntax characters of `value` and fold its line breaks. */
6
+ export declare function escapeMarkdown(value: string): string;
5
7
  /** Render the SDK's structured `/usage` response as Markdown. */
6
8
  export declare function formatUsageResponse(usage: SDKControlGetUsageResponse): string;
7
9
  //# sourceMappingURL=usage-markdown.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"usage-markdown.d.ts","sourceRoot":"","sources":["../src/usage-markdown.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AA8DjF,sEAAsE;AACtE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,0BAA0B,GAAG,IAAI,CAMpF;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAExD;AA0ED,iEAAiE;AACjE,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,0BAA0B,GAAG,MAAM,CAiE7E"}
1
+ {"version":3,"file":"usage-markdown.d.ts","sourceRoot":"","sources":["../src/usage-markdown.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AA8DjF,sEAAsE;AACtE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,0BAA0B,GAAG,IAAI,CAMpF;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAExD;AASD,iFAAiF;AACjF,wBAAgB,cAAc,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEpD;AA+DD,iEAAiE;AACjE,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,0BAA0B,GAAG,MAAM,CAiE7E"}
@@ -71,7 +71,8 @@ function usageBar(percent) {
71
71
  const filled = clamped === 0 ? 0 : Math.max(1, Math.round((clamped / 100) * cells));
72
72
  return `${"█".repeat(filled)}${"░".repeat(cells - filled)}`;
73
73
  }
74
- function escapeMarkdown(value) {
74
+ /** Escape the Markdown syntax characters of `value` and fold its line breaks. */
75
+ export function escapeMarkdown(value) {
75
76
  return value.replace(/([\\`*_[\]<>|])/g, "\\$1").replace(/[\r\n]+/g, " ");
76
77
  }
77
78
  function formatDuration(milliseconds) {
package/dist/utils.d.ts CHANGED
@@ -13,4 +13,16 @@ export declare function nodeToWebWritable(nodeStream: Writable): WritableStream<
13
13
  export declare function nodeToWebReadable(nodeStream: Readable): ReadableStream<Uint8Array>;
14
14
  export declare function unreachable(value: never, logger?: Logger): void;
15
15
  export declare function sleep(time: number): Promise<void>;
16
+ /** The outcome of {@link raceTimeoutAndAbort}. */
17
+ export type RaceOutcome<T> = {
18
+ type: "done";
19
+ value: T;
20
+ } | {
21
+ type: "timeout";
22
+ } | {
23
+ type: "aborted";
24
+ };
25
+ /** Wait for `promise` until `timeoutMs` passes or `signal` aborts. A rejection
26
+ * of `promise` rejects the result. The timer does not keep the process alive. */
27
+ export declare function raceTimeoutAndAbort<T>(promise: Promise<T>, timeoutMs: number, signal: AbortSignal): Promise<RaceOutcome<T>>;
16
28
  //# sourceMappingURL=utils.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAGxC,qBAAa,QAAQ,CAAC,CAAC,CAAE,YAAW,aAAa,CAAC,CAAC,CAAC;IAClD,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,SAAS,CAA8C;IAC/D,OAAO,CAAC,IAAI,CAAS;IAErB,IAAI,CAAC,IAAI,EAAE,CAAC;IASZ,GAAG;IAQH,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC;CAgB3C;AAGD,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,QAAQ,GAAG,cAAc,CAAC,UAAU,CAAC,CAclF;AAED,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,QAAQ,GAAG,cAAc,CAAC,UAAU,CAAC,CAUlF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,GAAE,MAAgB,QAQjE;AAED,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEjD"}
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjE,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAGxC,qBAAa,QAAQ,CAAC,CAAC,CAAE,YAAW,aAAa,CAAC,CAAC,CAAC;IAClD,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,SAAS,CAA8C;IAC/D,OAAO,CAAC,IAAI,CAAS;IAErB,IAAI,CAAC,IAAI,EAAE,CAAC;IASZ,GAAG;IAQH,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,aAAa,CAAC,CAAC,CAAC;CAgB3C;AAGD,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,QAAQ,GAAG,cAAc,CAAC,UAAU,CAAC,CAclF;AAED,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,QAAQ,GAAG,cAAc,CAAC,UAAU,CAAC,CAUlF;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,GAAE,MAAgB,QAQjE;AAED,wBAAgB,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEjD;AAED,kDAAkD;AAClD,MAAM,MAAM,WAAW,CAAC,CAAC,IAAI;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,CAAC,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,CAAC;AAEpG;kFACkF;AAClF,wBAAsB,mBAAmB,CAAC,CAAC,EACzC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EACnB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAoBzB"}
package/dist/utils.js CHANGED
@@ -79,3 +79,31 @@ export function unreachable(value, logger = console) {
79
79
  export function sleep(time) {
80
80
  return new Promise((resolve) => setTimeout(resolve, time));
81
81
  }
82
+ /** Wait for `promise` until `timeoutMs` passes or `signal` aborts. A rejection
83
+ * of `promise` rejects the result. The timer does not keep the process alive. */
84
+ export async function raceTimeoutAndAbort(promise, timeoutMs, signal) {
85
+ let timeout;
86
+ let onAbort;
87
+ try {
88
+ return await Promise.race([
89
+ promise.then((value) => ({ type: "done", value })),
90
+ new Promise((resolve) => {
91
+ timeout = setTimeout(() => resolve({ type: "timeout" }), timeoutMs);
92
+ timeout.unref?.();
93
+ }),
94
+ new Promise((resolve) => {
95
+ onAbort = () => resolve({ type: "aborted" });
96
+ if (signal.aborted)
97
+ onAbort();
98
+ else
99
+ signal.addEventListener("abort", onAbort, { once: true });
100
+ }),
101
+ ]);
102
+ }
103
+ finally {
104
+ if (timeout)
105
+ clearTimeout(timeout);
106
+ if (onAbort)
107
+ signal.removeEventListener("abort", onAbort);
108
+ }
109
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/v2/agent.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,MAAM,0CAA0C,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAkB,KAAK,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAa9E;;;;;;GAMG;AACH,wBAAgB,UAAU,CACxB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,GACvC,EAAE,CAAC,QAAQ,CA4Bb"}
1
+ {"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../../src/v2/agent.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,MAAM,0CAA0C,CAAC;AAC/D,OAAO,EAAE,cAAc,EAAkB,KAAK,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAc9E;;;;;;GAMG;AACH,wBAAgB,UAAU,CACxB,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,OAAO,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,IAAI,GACvC,EAAE,CAAC,QAAQ,CAoCb"}
package/dist/v2/agent.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as v2 from "@agentclientprotocol/sdk/experimental/v2";
2
2
  import { ClaudeAcpAgent } from "../acp-agent.js";
3
3
  import { v1InitializeRequest, v2InitializeResponse } from "./initialize.js";
4
+ import { v2Prompt } from "./prompt.js";
4
5
  import { v1NewSessionRequest, v1ResumeSessionRequest, v1SetSessionConfigOptionRequest, v2ConfigOptions, v2NewSessionResponse, v2ResumeSessionResponse, } from "./session.js";
5
6
  import { v2SessionUpdate } from "./session-update.js";
6
7
  /**
@@ -12,10 +13,12 @@ import { v2SessionUpdate } from "./session-update.js";
12
13
  */
13
14
  export function v2AgentApp(logger, onAgent) {
14
15
  let agent;
16
+ let client;
15
17
  return v2
16
18
  .agent({ name: "claude-code-acp" })
17
19
  .onConnect((connection) => {
18
- agent = new ClaudeAcpAgent(new V2ClientConnection(connection.client), logger);
20
+ client = new V2ClientConnection(connection.client, logger ?? console);
21
+ agent = new ClaudeAcpAgent(client, logger);
19
22
  onAgent(agent);
20
23
  })
21
24
  .onRequest(v2.methods.agent.initialize, async ({ params }) => v2InitializeResponse(await agent.initialize(v1InitializeRequest(params))))
@@ -29,19 +32,38 @@ export function v2AgentApp(logger, onAgent) {
29
32
  .onRequest(v2.methods.agent.session.setConfigOption, async ({ params }) => {
30
33
  const { configOptions, ...response } = await agent.setSessionConfigOption(v1SetSessionConfigOptionRequest(params));
31
34
  return { ...response, configOptions: v2ConfigOptions(configOptions) };
32
- });
35
+ })
36
+ .onRequest(v2.methods.agent.session.prompt, ({ params }) => v2Prompt(agent, params, (update) => {
37
+ void client.send({ sessionId: params.sessionId, update });
38
+ }))
39
+ .onNotification(v2.methods.agent.session.cancel, ({ params }) => agent.cancel(params));
33
40
  }
34
41
  /**
35
42
  * The {@link AcpClient} of an ACP v2 connection: it sends the v1 messages of
36
43
  * the agent as v2 messages.
37
44
  *
38
- * The v2 surface does not serve prompts yet, so permission requests, which
39
- * only a prompt turn makes, still reject.
45
+ * Permission requests still reject until the v2 surface translates them.
40
46
  */
41
47
  class V2ClientConnection {
42
48
  ctx;
43
- constructor(ctx) {
49
+ logger;
50
+ constructor(ctx, logger) {
44
51
  this.ctx = ctx;
52
+ this.logger = logger;
53
+ }
54
+ /**
55
+ * Sends a v2 session update, and logs rather than rejects when that fails.
56
+ * It and {@link sessionUpdate} hand updates to the connection synchronously,
57
+ * so they go out in the order of the calls. The agent's consumer awaits each
58
+ * of its updates before it reports the next turn event, so a turn's state
59
+ * follows the output that came before it. (An update the consumer is still
60
+ * routing can be overtaken by an event from elsewhere, such as a permission
61
+ * request opening.)
62
+ */
63
+ send(notification) {
64
+ return this.ctx.notify(v2.methods.client.session.update, notification).catch((error) => {
65
+ this.logger.error(`Failed to send a ${notification.update.sessionUpdate} update:`, error);
66
+ });
45
67
  }
46
68
  extNotification(method, params) {
47
69
  if (!isExtensionMethod(method)) {
@@ -0,0 +1,47 @@
1
+ /**
2
+ * ACP v2 `session/prompt`, served through the turn events of `ClaudeAcpAgent`.
3
+ *
4
+ * v2 answers the prompt once Claude Code takes it in, with the id of the user
5
+ * message it became, and reports the rest of the turn as `state_update`s.
6
+ */
7
+ import { type PromptRequest } from "@agentclientprotocol/sdk";
8
+ import * as v2 from "@agentclientprotocol/sdk/experimental/v2";
9
+ import type { ClaudeAcpAgent } from "../acp-agent.js";
10
+ /**
11
+ * Starts a turn for `params`, and answers when Claude Code takes the prompt
12
+ * in. `send` delivers a session update of the prompt's session; it must not
13
+ * throw, and must deliver updates in the order it is called, also relative to
14
+ * the agent's own updates.
15
+ *
16
+ * - Taken in: the prompt's `user_message`, then `running`, then the answer.
17
+ * - Waiting on a permission request or a question: `requires_action`, and
18
+ * `running` once none is open.
19
+ * - Ended: `idle` with the stop reason, usage, and `_meta` of the turn.
20
+ * - Failed after it was taken in: `idle` with {@link FAILED_STOP_REASON} and
21
+ * the JSON-RPC error that v1 answers with in `_meta.claudeCode.error`, and
22
+ * an error `notice` before it that shows the failure. v2 has no error on
23
+ * `idle`, and a notice must not be the only report of a failure.
24
+ * - Ended or failed before it was taken in: the answer is a JSON-RPC error,
25
+ * `-32800` for a prompt that a cancel ended in the queue.
26
+ *
27
+ * Deferred decision: a turn whose background subagents still run ends only
28
+ * when they finish (`Turn.deferredSettle`), so `idle` waits for them too. The
29
+ * hold exists for v1, whose clients stop listening at the prompt response.
30
+ * v2 allows background updates while idle, so it could report `idle` at the
31
+ * turn's result instead, with a turn event for the hold. To be decided with
32
+ * async tasks (step 6 in `docs/acp-v2.md`).
33
+ */
34
+ export declare function v2Prompt(agent: ClaudeAcpAgent, params: v2.PromptRequest, send: (update: v2.SessionUpdate) => void): Promise<v2.PromptResponse>;
35
+ /**
36
+ * The stop reason of a turn that failed after it was taken in. v2's stop
37
+ * reasons all describe work that ended without an error, and a custom one
38
+ * starts with `_`; clients show it as a generic stop.
39
+ */
40
+ export declare const FAILED_STOP_REASON = "_error";
41
+ /**
42
+ * A v2 prompt may hold content blocks that v1 cannot express: a custom one,
43
+ * or one from a newer ACP version. Clients send only the kinds the agent
44
+ * advertised, so such a block is rejected rather than silently dropped.
45
+ */
46
+ export declare function v1PromptRequest({ prompt, ...request }: v2.PromptRequest): PromptRequest;
47
+ //# sourceMappingURL=prompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../src/v2/prompt.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAIL,KAAK,aAAa,EAEnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,MAAM,0CAA0C,CAAC;AAC/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAItD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAgB,QAAQ,CACtB,KAAK,EAAE,cAAc,EACrB,MAAM,EAAE,EAAE,CAAC,aAAa,EACxB,IAAI,EAAE,CAAC,MAAM,EAAE,EAAE,CAAC,aAAa,KAAK,IAAI,GACvC,OAAO,CAAC,EAAE,CAAC,cAAc,CAAC,CA0D5B;AAED;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,WAAW,CAAC;AA2B3C;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,EAAE,MAAM,EAAE,GAAG,OAAO,EAAE,EAAE,EAAE,CAAC,aAAa,GAAG,aAAa,CAEvF"}
@@ -0,0 +1,153 @@
1
+ /**
2
+ * ACP v2 `session/prompt`, served through the turn events of `ClaudeAcpAgent`.
3
+ *
4
+ * v2 answers the prompt once Claude Code takes it in, with the id of the user
5
+ * message it became, and reports the rest of the turn as `state_update`s.
6
+ */
7
+ import { RequestError, } from "@agentclientprotocol/sdk";
8
+ import * as v2 from "@agentclientprotocol/sdk/experimental/v2";
9
+ import { splitNoticeText } from "../session-notices.js";
10
+ /**
11
+ * Starts a turn for `params`, and answers when Claude Code takes the prompt
12
+ * in. `send` delivers a session update of the prompt's session; it must not
13
+ * throw, and must deliver updates in the order it is called, also relative to
14
+ * the agent's own updates.
15
+ *
16
+ * - Taken in: the prompt's `user_message`, then `running`, then the answer.
17
+ * - Waiting on a permission request or a question: `requires_action`, and
18
+ * `running` once none is open.
19
+ * - Ended: `idle` with the stop reason, usage, and `_meta` of the turn.
20
+ * - Failed after it was taken in: `idle` with {@link FAILED_STOP_REASON} and
21
+ * the JSON-RPC error that v1 answers with in `_meta.claudeCode.error`, and
22
+ * an error `notice` before it that shows the failure. v2 has no error on
23
+ * `idle`, and a notice must not be the only report of a failure.
24
+ * - Ended or failed before it was taken in: the answer is a JSON-RPC error,
25
+ * `-32800` for a prompt that a cancel ended in the queue.
26
+ *
27
+ * Deferred decision: a turn whose background subagents still run ends only
28
+ * when they finish (`Turn.deferredSettle`), so `idle` waits for them too. The
29
+ * hold exists for v1, whose clients stop listening at the prompt response.
30
+ * v2 allows background updates while idle, so it could report `idle` at the
31
+ * turn's result instead, with a turn event for the hold. To be decided with
32
+ * async tasks (step 6 in `docs/acp-v2.md`).
33
+ */
34
+ export function v2Prompt(agent, params, send) {
35
+ return new Promise((resolve, reject) => {
36
+ let inserted = false;
37
+ const events = {
38
+ inserted(messageId) {
39
+ inserted = true;
40
+ send({ sessionUpdate: "user_message", messageId, content: params.prompt });
41
+ send({ sessionUpdate: "state_update", state: "running" });
42
+ resolve({ messageId });
43
+ },
44
+ awaitingUser() {
45
+ send({ sessionUpdate: "state_update", state: "requires_action" });
46
+ },
47
+ resumed() {
48
+ send({ sessionUpdate: "state_update", state: "running" });
49
+ },
50
+ ended(outcome) {
51
+ if (inserted) {
52
+ send(idle(outcome));
53
+ }
54
+ else if (outcome.stopReason === "cancelled") {
55
+ reject(RequestError.requestCancelled());
56
+ }
57
+ else {
58
+ reject(RequestError.internalError({ stopReason: outcome.stopReason }, "The turn ended before Claude Code took the prompt in"));
59
+ }
60
+ },
61
+ failed(error, title) {
62
+ if (!inserted) {
63
+ reject(error);
64
+ return;
65
+ }
66
+ const failure = jsonRpcError(error);
67
+ send({
68
+ sessionUpdate: "notice",
69
+ severity: "error",
70
+ ...splitNoticeText(title ?? failure.message, "The turn failed"),
71
+ });
72
+ send({
73
+ sessionUpdate: "state_update",
74
+ state: "idle",
75
+ stopReason: FAILED_STOP_REASON,
76
+ _meta: { claudeCode: { error: failure } },
77
+ });
78
+ },
79
+ };
80
+ let request;
81
+ try {
82
+ request = v1PromptRequest(params);
83
+ }
84
+ catch (error) {
85
+ reject(error);
86
+ return;
87
+ }
88
+ agent.startTurn(request, events).catch(reject);
89
+ });
90
+ }
91
+ /**
92
+ * The stop reason of a turn that failed after it was taken in. v2's stop
93
+ * reasons all describe work that ended without an error, and a custom one
94
+ * starts with `_`; clients show it as a generic stop.
95
+ */
96
+ export const FAILED_STOP_REASON = "_error";
97
+ /** The JSON-RPC error that v1 answers a failed prompt with. */
98
+ function jsonRpcError(error) {
99
+ if (error instanceof RequestError) {
100
+ return {
101
+ code: error.code,
102
+ message: error.message,
103
+ ...(error.data !== undefined ? { data: error.data } : {}),
104
+ };
105
+ }
106
+ return {
107
+ code: RequestError.internalError().code,
108
+ message: error instanceof Error ? error.message : String(error),
109
+ };
110
+ }
111
+ function idle({ stopReason, usage, _meta }) {
112
+ return {
113
+ sessionUpdate: "state_update",
114
+ state: "idle",
115
+ stopReason,
116
+ ...(usage ? { usage } : {}),
117
+ ...(_meta ? { _meta } : {}),
118
+ };
119
+ }
120
+ /**
121
+ * A v2 prompt may hold content blocks that v1 cannot express: a custom one,
122
+ * or one from a newer ACP version. Clients send only the kinds the agent
123
+ * advertised, so such a block is rejected rather than silently dropped.
124
+ */
125
+ export function v1PromptRequest({ prompt, ...request }) {
126
+ return { ...request, prompt: prompt.map(v1ContentBlock) };
127
+ }
128
+ function v1ContentBlock(block) {
129
+ if (v2.ContentBlock.isText(block) ||
130
+ v2.ContentBlock.isImage(block) ||
131
+ v2.ContentBlock.isAudio(block) ||
132
+ v2.ContentBlock.isResourceLink(block) ||
133
+ v2.ContentBlock.isResource(block)) {
134
+ const { annotations, ...rest } = block;
135
+ return annotations != null ? { ...rest, annotations: v1Annotations(annotations) } : rest;
136
+ }
137
+ throw RequestError.invalidParams({ type: block.type }, `Content blocks of type ${block.type} are not supported`);
138
+ }
139
+ /**
140
+ * v2 also accepts audiences of a newer ACP version; v1 knows two. An audience
141
+ * of only unknown roles is dropped rather than narrowed to nobody.
142
+ */
143
+ function v1Annotations({ audience, ...annotations }) {
144
+ if (audience == null)
145
+ return annotations;
146
+ const known = audience.filter(isV1Role);
147
+ return known.length > 0 || audience.length === 0
148
+ ? { ...annotations, audience: known }
149
+ : annotations;
150
+ }
151
+ function isV1Role(role) {
152
+ return role === "assistant" || role === "user";
153
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"session-update.d.ts","sourceRoot":"","sources":["../../src/v2/session-update.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,MAAM,0CAA0C,CAAC;AAC/D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAGlE;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,sBAAsB,CAAC,QAAQ,CAAC,GACvC,EAAE,CAAC,aAAa,GAAG,SAAS,CAoB9B"}
1
+ {"version":3,"file":"session-update.d.ts","sourceRoot":"","sources":["../../src/v2/session-update.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,MAAM,0CAA0C,CAAC;AAC/D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAGlE;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,sBAAsB,CAAC,QAAQ,CAAC,GACvC,EAAE,CAAC,aAAa,GAAG,SAAS,CA8B9B"}
@@ -16,6 +16,16 @@ export function v2SessionUpdate(update) {
16
16
  case "usage_update":
17
17
  case "notice":
18
18
  return update;
19
+ case "agent_message_chunk":
20
+ case "agent_thought_chunk":
21
+ case "user_message_chunk": {
22
+ // v2 requires the id of the message a chunk belongs to; v1 allows none.
23
+ const { messageId, ...chunk } = update;
24
+ if (!messageId) {
25
+ throw new Error(`An ACP v2 ${update.sessionUpdate} needs a messageId`);
26
+ }
27
+ return { ...chunk, messageId };
28
+ }
19
29
  case "current_mode_update":
20
30
  // v2 has no modes: the mode is the `mode` config option. Every mode
21
31
  // change also reaches the client as a `config_option_update` or in the
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "0.85.2-preview.4",
6
+ "version": "0.85.2-preview.6",
7
7
  "description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
8
8
  "main": "dist/lib.js",
9
9
  "types": "dist/lib.d.ts",