@vellumai/assistant 0.11.3-dev.202608121709.4a2dc5b → 0.11.3-dev.202608122017.f5ae62a

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.11.3-dev.202608121709.4a2dc5b",
3
+ "version": "0.11.3-dev.202608122017.f5ae62a",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -234,6 +234,11 @@ const BASELINE: Record<string, readonly string[]> = {
234
234
  "../../../util/worker-memory.js",
235
235
  "../../../util/worker-process.js",
236
236
  "../../types.js",
237
+ // The memory jobs worker runs as its own OS process and hosts real agent
238
+ // conversations, so it registers the host's default-plugin hook and
239
+ // injector surface at startup (hooks only, no init hooks). Host-owned
240
+ // composition with no plugin-api equivalent.
241
+ "../../worker-plugin-surface.js",
237
242
  "../injection-presence.js",
238
243
  "../injector-order.js",
239
244
  "@qdrant/js-client-rest",
@@ -18,10 +18,18 @@ import { Glob } from "bun";
18
18
  * - start the PID-file identity guard — the PID file is a worker's sole
19
19
  * tracking handle, so a worker the file stops naming can never be
20
20
  * stopped externally and must evict itself.
21
+ *
22
+ * The subset that hosts real agent conversations
23
+ * ({@link CONVERSATION_RUNNING_ENTRYPOINTS}) must additionally register the
24
+ * default plugins' hooks and injectors, since hook dispatch is process-global
25
+ * and a worker that skips it runs conversations with no plugin behavior at all
26
+ * (no image captioning or vision-rejection recovery, no tool-result
27
+ * truncation, no runtime injections).
21
28
  */
22
29
 
23
30
  const DISABLE_CALL = "disableStreamSeqStamping()";
24
31
  const PID_GUARD_CALL = "startWorkerPidFileGuard(";
32
+ const PLUGIN_SURFACE_CALL = "registerWorkerPluginSurface(";
25
33
 
26
34
  /** Shape of a shutdown that schedules `process.exit` instead of calling it. */
27
35
  const DEFERRED_EXIT = ".finally(() => process.exit";
@@ -44,6 +52,16 @@ const WORK_START_MARKERS: Record<string, string> = {
44
52
  "routes/worker.ts": 'server.on("connection"',
45
53
  };
46
54
 
55
+ /**
56
+ * The entrypoints whose work wakes real agent conversations. `monitoring` (a
57
+ * resource sampler) and `routes` (an HTTP route host) run no conversations, so
58
+ * they carry no plugin surface.
59
+ */
60
+ const CONVERSATION_RUNNING_ENTRYPOINTS: ReadonlySet<string> = new Set([
61
+ "schedule/worker.ts",
62
+ "plugins/defaults/memory/worker.ts",
63
+ ]);
64
+
47
65
  function findWorkerEntrypoints(): string[] {
48
66
  const srcRoot = join(process.cwd(), "src");
49
67
  const glob = new Glob("**/worker.ts");
@@ -137,4 +155,40 @@ describe("worker entrypoint guards", () => {
137
155
  "worker superseded at startup before it runs orphaned work.",
138
156
  ).toEqual([]);
139
157
  });
158
+
159
+ test("the conversation-running entrypoints are all discovered workers", () => {
160
+ const discovered = new Set(findWorkerEntrypoints());
161
+ const unknown = [...CONVERSATION_RUNNING_ENTRYPOINTS].filter(
162
+ (file) => !discovered.has(file),
163
+ );
164
+ expect(
165
+ unknown,
166
+ "CONVERSATION_RUNNING_ENTRYPOINTS names an entrypoint the glob does " +
167
+ "not find — the worker moved or was renamed.",
168
+ ).toEqual([]);
169
+ });
170
+
171
+ test("every conversation-running entrypoint registers the default plugin surface before starting work", () => {
172
+ const offenders = [...CONVERSATION_RUNNING_ENTRYPOINTS]
173
+ .sort()
174
+ .filter((file) => {
175
+ const source = readFileSync(join(process.cwd(), "src", file), "utf8");
176
+ const marker = WORK_START_MARKERS[file];
177
+ if (marker == null) {
178
+ return true;
179
+ }
180
+ const registerAt = source.indexOf(PLUGIN_SURFACE_CALL);
181
+ const workAt = source.indexOf(marker);
182
+ return registerAt < 0 || workAt < 0 || registerAt > workAt;
183
+ });
184
+ expect(
185
+ offenders,
186
+ `A worker that wakes agent conversations must call ` +
187
+ `${PLUGIN_SURFACE_CALL}) before its work-start call (see ` +
188
+ "WORK_START_MARKERS). Hook dispatch is process-global, so without it " +
189
+ "the conversations this process runs get no default plugin behavior: " +
190
+ "no vision-rejection recovery, no tool-result truncation, no runtime " +
191
+ "injections.",
192
+ ).toEqual([]);
193
+ });
140
194
  });
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Tests for {@link registerWorkerPluginSurface}, the default-plugin surface
3
+ * that sidecar worker processes install at startup.
4
+ *
5
+ * A worker that wakes real agent conversations shares the daemon's
6
+ * process-global hook and injector registries, so registering the defaults is
7
+ * what gives those conversations the same behavior as daemon conversations.
8
+ * Registration must populate both tables and stay idempotent, and it must do so
9
+ * without running any plugin `init` hook (the memory plugin's init starts the
10
+ * memory jobs worker process itself).
11
+ */
12
+
13
+ import { beforeEach, describe, expect, test } from "bun:test";
14
+
15
+ import { getHookEntriesFor } from "../hooks/registry.js";
16
+ import {
17
+ clearInjectorRegistry,
18
+ getRegisteredInjectors,
19
+ } from "../plugins/injector-registry.js";
20
+ import { resetPluginRegistryForTests } from "../plugins/registry.js";
21
+ import { registerWorkerPluginSurface } from "../plugins/worker-plugin-surface.js";
22
+
23
+ async function hookOwnersFor(name: string): Promise<string[]> {
24
+ const entries = await getHookEntriesFor(name);
25
+ return entries.map((entry) => entry.owner.id);
26
+ }
27
+
28
+ describe("registerWorkerPluginSurface", () => {
29
+ beforeEach(() => {
30
+ resetPluginRegistryForTests();
31
+ clearInjectorRegistry();
32
+ });
33
+
34
+ test("serves the default plugins' hooks from the process-global registry", async () => {
35
+ expect(await hookOwnersFor("post-model-call")).not.toContain(
36
+ "default-image-fallback",
37
+ );
38
+
39
+ registerWorkerPluginSurface();
40
+
41
+ // The vision-rejection recovery that a worker without this surface never
42
+ // ran, plus an oversized-tool-result guard on the other hook surface.
43
+ expect(await hookOwnersFor("post-model-call")).toContain(
44
+ "default-image-fallback",
45
+ );
46
+ expect(await hookOwnersFor("post-tool-use")).toContain(
47
+ "default-tool-result-truncate",
48
+ );
49
+ });
50
+
51
+ test("registers the injector-only defaults' runtime injectors", () => {
52
+ expect(
53
+ getRegisteredInjectors().some((i) => i.name === "unified-turn-context"),
54
+ ).toBe(false);
55
+
56
+ registerWorkerPluginSurface();
57
+
58
+ // `default-turn-context` contributes no hooks, so its injections only reach
59
+ // a worker's conversations through the injector registry.
60
+ expect(
61
+ getRegisteredInjectors().some((i) => i.name === "unified-turn-context"),
62
+ ).toBe(true);
63
+ });
64
+
65
+ test("is idempotent: a second call neither throws nor duplicates", async () => {
66
+ registerWorkerPluginSurface();
67
+ const hooksAfterFirst = await hookOwnersFor("post-model-call");
68
+ const injectorsAfterFirst = getRegisteredInjectors().map((i) => i.name);
69
+
70
+ expect(() => registerWorkerPluginSurface()).not.toThrow();
71
+
72
+ expect(await hookOwnersFor("post-model-call")).toEqual(hooksAfterFirst);
73
+ expect(getRegisteredInjectors().map((i) => i.name)).toEqual(
74
+ injectorsAfterFirst,
75
+ );
76
+ });
77
+ });
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Pins the two shapes a Claude auth failure travels in, plus the
3
+ * wire-contract literals. Losing either shape silently degrades an actionable
4
+ * "reconnect Claude" failure into an opaque one.
5
+ */
6
+
7
+ import { describe, expect, test } from "bun:test";
8
+
9
+ import { AcpAuthRequiredEventSchema } from "../../api/events/acp-auth-required.js";
10
+ import { AcpSessionErrorEventSchema } from "../../api/events/acp-session-error.js";
11
+ import {
12
+ ACP_CLAUDE_AUTH_REQUIRED_CODE,
13
+ AcpAuthRequiredError,
14
+ AUTH_REQUIRED_CODE,
15
+ CLAUDE_ACP_COMMAND,
16
+ isAcpAuthRequired,
17
+ isClaudeAuthFailureMessage,
18
+ } from "../auth-required.js";
19
+
20
+ describe("isAcpAuthRequired", () => {
21
+ test("recognizes the raw JSON-RPC rejection from the agent", () => {
22
+ // What the adapter actually sends: a plain object off the wire, not an
23
+ // instance of any class we control.
24
+ expect(isAcpAuthRequired({ code: AUTH_REQUIRED_CODE })).toBe(true);
25
+ });
26
+
27
+ test("recognizes our own error after the retry path gives up", () => {
28
+ expect(isAcpAuthRequired(new AcpAuthRequiredError("claude", "nope"))).toBe(
29
+ true,
30
+ );
31
+ });
32
+
33
+ test("does not fire on other failures", () => {
34
+ expect(isAcpAuthRequired(new Error("Internal error"))).toBe(false);
35
+ expect(isAcpAuthRequired({ code: -32601 })).toBe(false);
36
+ expect(isAcpAuthRequired(null)).toBe(false);
37
+ expect(isAcpAuthRequired(undefined)).toBe(false);
38
+ expect(isAcpAuthRequired("auth_required")).toBe(false);
39
+ });
40
+
41
+ test("uses the ACP-specified code", () => {
42
+ // Matches the SDK's RequestError.authRequired(); drifting from it would
43
+ // silently stop classifying every auth failure.
44
+ expect(AUTH_REQUIRED_CODE).toBe(-32000);
45
+ });
46
+ });
47
+
48
+ describe("isClaudeAuthFailureMessage", () => {
49
+ test("matches the live rejected-credential failure verbatim", () => {
50
+ // Captured from a real claude-agent-acp run against a revoked token: the
51
+ // adapter relays the CLI's failure as a -32603 internal error carrying
52
+ // this text, NOT as the structured auth_required rejection. This message
53
+ // is the reported bug, so it must classify.
54
+ expect(
55
+ isClaudeAuthFailureMessage(
56
+ "Internal error: Failed to authenticate. API Error: 401 OAuth access token has been revoked.",
57
+ ),
58
+ ).toBe(true);
59
+ });
60
+
61
+ test("is insensitive to the server's variable suffix", () => {
62
+ // The CLI-authored prefix is the stable part; the API's suffix varies.
63
+ expect(
64
+ isClaudeAuthFailureMessage(
65
+ "Failed to authenticate. API Error: 401 OAuth access token has expired. Re-authenticate to continue.",
66
+ ),
67
+ ).toBe(true);
68
+ });
69
+
70
+ test("matches the CLI's other auth phrasings", () => {
71
+ expect(
72
+ isClaudeAuthFailureMessage(
73
+ "Session expired. Please run /login to sign in again.",
74
+ ),
75
+ ).toBe(true);
76
+ expect(isClaudeAuthFailureMessage("Not logged in")).toBe(true);
77
+ });
78
+
79
+ test("does not fire on ordinary failures", () => {
80
+ expect(isClaudeAuthFailureMessage("Internal error")).toBe(false);
81
+ expect(isClaudeAuthFailureMessage("ECONNRESET: connection reset")).toBe(
82
+ false,
83
+ );
84
+ expect(
85
+ isClaudeAuthFailureMessage("Command failed: login.sh: not found"),
86
+ ).toBe(false);
87
+ expect(isClaudeAuthFailureMessage(undefined)).toBe(false);
88
+ expect(isClaudeAuthFailureMessage("")).toBe(false);
89
+ });
90
+ });
91
+
92
+ describe("AcpAuthRequiredError", () => {
93
+ test("is an Error that carries the agent id and its message", () => {
94
+ const err = new AcpAuthRequiredError("claude", "needs a reconnect");
95
+ expect(err).toBeInstanceOf(Error);
96
+ expect(err.name).toBe("AcpAuthRequiredError");
97
+ expect(err.agentId).toBe("claude");
98
+ expect(err.message).toBe("needs a reconnect");
99
+ });
100
+ });
101
+
102
+ describe("event shape is additive-safe for older clients", () => {
103
+ test("acp_session_error rejects unknown keys, which is why the signal is not a field on it", () => {
104
+ // Clients drop a whole event over an unknown key (strict schemas plus a
105
+ // safeParse fallback to `unknown`), so new signals must ride new event
106
+ // types; this pins the strictness that forces that.
107
+ const result = AcpSessionErrorEventSchema.safeParse({
108
+ type: "acp_session_error",
109
+ acpSessionId: "acp-1",
110
+ error: "boom",
111
+ someFutureField: "x",
112
+ });
113
+ expect(result.success).toBe(false);
114
+ });
115
+
116
+ test("acp_session_error still parses in its unchanged shape", () => {
117
+ expect(
118
+ AcpSessionErrorEventSchema.safeParse({
119
+ type: "acp_session_error",
120
+ acpSessionId: "acp-1",
121
+ error: "boom",
122
+ }).success,
123
+ ).toBe(true);
124
+ });
125
+
126
+ test("acp_auth_required carries the code and an optional anchor", () => {
127
+ const parsed = AcpAuthRequiredEventSchema.parse({
128
+ type: "acp_auth_required",
129
+ acpSessionId: "acp-1",
130
+ authCode: ACP_CLAUDE_AUTH_REQUIRED_CODE,
131
+ agent: "claude",
132
+ parentToolUseId: "tool-1",
133
+ });
134
+ expect(parsed.authCode).toBe(ACP_CLAUDE_AUTH_REQUIRED_CODE);
135
+ expect(parsed.parentToolUseId).toBe("tool-1");
136
+
137
+ // The anchor is optional: a run not started by a tool call has none.
138
+ expect(
139
+ AcpAuthRequiredEventSchema.safeParse({
140
+ type: "acp_auth_required",
141
+ acpSessionId: "acp-1",
142
+ authCode: ACP_CLAUDE_AUTH_REQUIRED_CODE,
143
+ agent: "claude",
144
+ }).success,
145
+ ).toBe(true);
146
+ });
147
+ });
148
+
149
+ describe("wire contract", () => {
150
+ test("the client marker matches the web literal", () => {
151
+ // Paired with ACP_CLAUDE_AUTH_REQUIRED_CODE in
152
+ // clients/web/src/domains/chat/utils/acp-connect.ts. A silent rename on
153
+ // either side turns the Connect card off with nothing failing.
154
+ expect(ACP_CLAUDE_AUTH_REQUIRED_CODE).toBe("acp_claude_auth_required");
155
+ });
156
+
157
+ test("the adapter gate matches the resolved command basename", () => {
158
+ // Compared against SessionEntry.command, which is already a basename.
159
+ expect(CLAUDE_ACP_COMMAND).toBe("claude-agent-acp");
160
+ });
161
+ });
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, test } from "bun:test";
2
2
 
3
3
  import { AcpAgentProcess } from "./agent-process.js";
4
+ import { AcpAuthRequiredError, isAcpAuthRequired } from "./auth-required.js";
4
5
  import type { AcpAgentConfig } from "./types.js";
5
6
 
6
7
  const config: AcpAgentConfig = { command: "noop", args: [] };
@@ -114,3 +115,102 @@ describe("AcpAgentProcess.markStderr / stderrSince", () => {
114
115
  expect(proc.stderrSince(mark)).toBe("fresh failure");
115
116
  });
116
117
  });
118
+
119
+ // ---------------------------------------------------------------------------
120
+ // createSession: structured auth_required handling through the real retry path
121
+ // ---------------------------------------------------------------------------
122
+
123
+ /**
124
+ * Wires a process with a fake protocol connection and advertised auth methods,
125
+ * following the same no-child-process injection style as `feed` above. The
126
+ * retry logic under test (`withAuthRetry`, method selection, the typed throw)
127
+ * runs for real.
128
+ */
129
+ function wireProcess(opts: {
130
+ authMethods: unknown[];
131
+ newSession: () => Promise<unknown>;
132
+ env?: Record<string, string>;
133
+ }): { proc: AcpAgentProcess; authenticateCalls: () => number } {
134
+ const proc = new AcpAgentProcess("test-agent", config, clientFactory);
135
+ let authed = 0;
136
+ (proc as unknown as { connection: unknown }).connection = {
137
+ newSession: opts.newSession,
138
+ authenticate: async () => {
139
+ authed += 1;
140
+ return {};
141
+ },
142
+ };
143
+ (proc as unknown as { initializeResponse: unknown }).initializeResponse = {
144
+ authMethods: opts.authMethods,
145
+ };
146
+ (proc as unknown as { spawnedEnv: unknown }).spawnedEnv = opts.env ?? {};
147
+ return { proc, authenticateCalls: () => authed };
148
+ }
149
+
150
+ const TERMINAL_ONLY_METHODS = [
151
+ { id: "claude-ai-login", name: "Claude Subscription", type: "terminal" },
152
+ ];
153
+
154
+ describe("AcpAgentProcess.createSession auth_required handling", () => {
155
+ test("a structured auth_required rejection with only terminal methods becomes AcpAuthRequiredError", async () => {
156
+ // The wire shape the adapter actually sends: a plain JSON-RPC error
157
+ // object, not an Error subclass. With no satisfiable env_var method the
158
+ // retry path must surface the typed error the session manager and the
159
+ // spawn tool classify on; losing the type here silently degrades the
160
+ // whole recovery surface back into a generic failure.
161
+ const { proc } = wireProcess({
162
+ authMethods: TERMINAL_ONLY_METHODS,
163
+ newSession: () =>
164
+ Promise.reject({ code: -32000, message: "Authentication required" }),
165
+ });
166
+
167
+ const err: unknown = await proc.createSession("/tmp").then(
168
+ () => null,
169
+ (e: unknown) => e,
170
+ );
171
+
172
+ expect(err).toBeInstanceOf(AcpAuthRequiredError);
173
+ expect((err as AcpAuthRequiredError).agentId).toBe("test-agent");
174
+ expect(isAcpAuthRequired(err)).toBe(true);
175
+ });
176
+
177
+ test("a satisfiable env_var method authenticates and retries instead of throwing", async () => {
178
+ let calls = 0;
179
+ const { proc, authenticateCalls } = wireProcess({
180
+ authMethods: [
181
+ {
182
+ id: "api-key",
183
+ name: "Use SOME_KEY",
184
+ type: "env_var",
185
+ vars: [{ name: "SOME_KEY" }],
186
+ },
187
+ ],
188
+ env: { SOME_KEY: "value" },
189
+ newSession: () => {
190
+ calls += 1;
191
+ return calls === 1
192
+ ? Promise.reject({ code: -32000, message: "Authentication required" })
193
+ : Promise.resolve({ sessionId: "session-1" });
194
+ },
195
+ });
196
+
197
+ await expect(proc.createSession("/tmp")).resolves.toBe("session-1");
198
+ expect(authenticateCalls()).toBe(1);
199
+ });
200
+
201
+ test("a non-auth rejection passes through untyped", async () => {
202
+ const { proc } = wireProcess({
203
+ authMethods: TERMINAL_ONLY_METHODS,
204
+ newSession: () =>
205
+ Promise.reject({ code: -32603, message: "Internal error" }),
206
+ });
207
+
208
+ const err: unknown = await proc.createSession("/tmp").then(
209
+ () => null,
210
+ (e: unknown) => e,
211
+ );
212
+
213
+ expect(err).not.toBeInstanceOf(AcpAuthRequiredError);
214
+ expect(isAcpAuthRequired(err)).toBe(false);
215
+ });
216
+ });
@@ -20,16 +20,11 @@ import type {
20
20
  import * as acp from "@agentclientprotocol/sdk";
21
21
 
22
22
  import { getLogger } from "../util/logger.js";
23
+ import { AcpAuthRequiredError, isAcpAuthRequired } from "./auth-required.js";
23
24
  import type { AcpAgentConfig } from "./types.js";
24
25
 
25
26
  const log = getLogger("acp");
26
27
 
27
- /**
28
- * JSON-RPC error code agents use to signal that authentication is required
29
- * (matches the SDK's RequestError.authRequired()).
30
- */
31
- const AUTH_REQUIRED_CODE = -32000;
32
-
33
28
  /**
34
29
  * Rough byte cap for retained stderr. Oldest lines are evicted once the sum of
35
30
  * retained line lengths exceeds this, so the stderr ring (read via stderrSince)
@@ -37,19 +32,6 @@ const AUTH_REQUIRED_CODE = -32000;
37
32
  */
38
33
  const STDERR_RETENTION_BYTES = 4096;
39
34
 
40
- /**
41
- * Detects the ACP auth-required error. Checks the `code` property rather than
42
- * `instanceof acp.RequestError` so plain JSON-RPC error objects are also
43
- * recognized.
44
- */
45
- function isAuthRequiredError(err: unknown): boolean {
46
- return (
47
- typeof err === "object" &&
48
- err !== null &&
49
- (err as { code?: unknown }).code === AUTH_REQUIRED_CODE
50
- );
51
- }
52
-
53
35
  function isEnvVarMethod(
54
36
  method: AuthMethod,
55
37
  ): method is AuthMethodEnvVar & { type: "env_var" } {
@@ -296,7 +278,7 @@ export class AcpAgentProcess {
296
278
  try {
297
279
  return await op();
298
280
  } catch (err) {
299
- if (!isAuthRequiredError(err)) {
281
+ if (!isAcpAuthRequired(err)) {
300
282
  throw err;
301
283
  }
302
284
 
@@ -306,12 +288,23 @@ export class AcpAgentProcess {
306
288
 
307
289
  const method = this.selectEnvVarAuthMethod();
308
290
  if (!method) {
309
- throw new Error(
310
- `ACP agent "${this.agentId}" requires authentication. ` +
311
- `Advertised methods: ${this.describeAuthMethods()}. ` +
312
- "Set the required env var under acp.agents.<id>.env in config.json, " +
313
- "collect it securely via 'assistant credentials prompt --service acp --field <field> --label \"<label>\"', " +
314
- "or complete the agent's own login flow in the workspace.",
291
+ // Typed so the session manager can tell an auth failure from a crash
292
+ // and surface a re-authentication path. The remediation text is split
293
+ // by what the agent advertises: env-var and `credentials prompt`
294
+ // advice only helps when an env_var method exists to satisfy, and for
295
+ // terminal-login-only adapters it sends the user chasing a CLI
296
+ // workaround for a credential the app repairs on its own.
297
+ throw new AcpAuthRequiredError(
298
+ this.agentId,
299
+ this.hasEnvVarAuthMethod()
300
+ ? `ACP agent "${this.agentId}" requires authentication. ` +
301
+ `Advertised methods: ${this.describeAuthMethods()}. ` +
302
+ "Set the required env var under acp.agents.<id>.env in config.json, " +
303
+ "or collect it securely via 'assistant credentials prompt --service acp --field <field> --label \"<label>\"'."
304
+ : `ACP agent "${this.agentId}" requires authentication and its ` +
305
+ "stored credential was not accepted. Advertised methods: " +
306
+ `${this.describeAuthMethods()}. None can be completed headlessly, ` +
307
+ "so the credential has to be reconnected.",
315
308
  );
316
309
  }
317
310
 
@@ -325,6 +318,16 @@ export class AcpAgentProcess {
325
318
  }
326
319
  }
327
320
 
321
+ /**
322
+ * Whether the agent advertises any `env_var` auth method at all, satisfiable
323
+ * or not. Distinguishes "we could not satisfy the env var it wants" from
324
+ * "env vars are not how this agent authenticates", which are different
325
+ * problems with different fixes.
326
+ */
327
+ private hasEnvVarAuthMethod(): boolean {
328
+ return this.authMethods.some(isEnvVarMethod);
329
+ }
330
+
328
331
  /**
329
332
  * Renders the agent's advertised auth methods for error messages, e.g.
330
333
  * `"Login with ChatGPT" (chatgpt), "Use OPENAI_API_KEY" (env var OPENAI_API_KEY)`.
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Detection of Claude authentication failures on ACP runs.
3
+ *
4
+ * These failures reach the daemon in two shapes, and both are needed:
5
+ *
6
+ * 1. No credentials at all: the adapter raises a structured ACP
7
+ * `auth_required` rejection (JSON-RPC -32000). {@link isAcpAuthRequired}.
8
+ * 2. Credentials present but rejected (the expired/revoked case): the CLI
9
+ * surfaces the API 401 as an error message it authors, and the adapter
10
+ * relays it as a generic -32603 internal error, NOT as `auth_required`.
11
+ * {@link isClaudeAuthFailureMessage}.
12
+ *
13
+ * A positive detection becomes {@link ACP_CLAUDE_AUTH_REQUIRED_CODE} on the
14
+ * `acp_auth_required` event, which the client turns into the inline
15
+ * "Connect Claude Code" card.
16
+ */
17
+
18
+ export { ACP_CLAUDE_AUTH_REQUIRED_CODE } from "../api/events/acp-auth-required.js";
19
+
20
+ /**
21
+ * JSON-RPC error code agents use to signal that authentication is required
22
+ * (matches the ACP SDK's `RequestError.authRequired()`).
23
+ */
24
+ export const AUTH_REQUIRED_CODE = -32000;
25
+
26
+ /**
27
+ * An agent rejected an operation with `auth_required` and the daemon has no
28
+ * way to satisfy it. A distinct type so the classification survives to the
29
+ * session manager, where the failure becomes an event the UI can act on.
30
+ */
31
+ export class AcpAuthRequiredError extends Error {
32
+ constructor(
33
+ readonly agentId: string,
34
+ message: string,
35
+ ) {
36
+ super(message);
37
+ this.name = "AcpAuthRequiredError";
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Detects the structured auth-required signal in either shape it travels: the
43
+ * raw JSON-RPC rejection from the agent, or our own
44
+ * {@link AcpAuthRequiredError}. Checks the `code` property rather than an
45
+ * `instanceof` so plain JSON-RPC error objects are recognized too.
46
+ */
47
+ export function isAcpAuthRequired(err: unknown): boolean {
48
+ if (err instanceof AcpAuthRequiredError) {
49
+ return true;
50
+ }
51
+ return (
52
+ typeof err === "object" &&
53
+ err !== null &&
54
+ (err as { code?: unknown }).code === AUTH_REQUIRED_CODE
55
+ );
56
+ }
57
+
58
+ /**
59
+ * The Claude CLI's own auth-failure phrasings. Unanchored (no ^/$) because
60
+ * the messages arrive with adapter framing ("Internal error: ...") or as a
61
+ * line `deriveFailureError` picked out of stderr.
62
+ */
63
+ const CLAUDE_AUTH_FAILURE_PATTERNS: readonly RegExp[] = [
64
+ /Failed to authenticate\b/,
65
+ /Please run \/login/,
66
+ /\bNot logged in\b/,
67
+ ];
68
+
69
+ /**
70
+ * Whether a failure message is a Claude authentication failure. Callers gate
71
+ * on the adapter (`claude-agent-acp`) BEFORE consulting this: the patterns
72
+ * are Claude-specific, and the marker built on them promises a repair only
73
+ * the Connect Claude flow can perform.
74
+ */
75
+ export function isClaudeAuthFailureMessage(
76
+ message: string | undefined,
77
+ ): boolean {
78
+ return (
79
+ message != null &&
80
+ CLAUDE_AUTH_FAILURE_PATTERNS.some((pattern) => pattern.test(message))
81
+ );
82
+ }
83
+
84
+ /** The adapter whose auth failures the Connect Claude flow can repair. */
85
+ export const CLAUDE_ACP_COMMAND = "claude-agent-acp";
86
+
87
+ /**
88
+ * Model-facing text accompanying a Claude auth failure wherever the inline
89
+ * Connect card is raised (the tool result for a pre-spawn rejection, the
90
+ * parent notification for a post-spawn one), so the model points at the card
91
+ * instead of inventing a remedy (CLI commands, pasted tokens, or a card that
92
+ * is not there). Bans placement words because card position is a UI detail
93
+ * the model cannot see.
94
+ */
95
+ export const ACP_AUTH_RECOVERY_GUIDANCE =
96
+ "The Claude Code connection needs to be re-authorized. The app shows the " +
97
+ 'user an inline "Connect Claude Code" card. Reply with ONE short sentence: ' +
98
+ "ask them to click Connect to sign in again, and tell them you'll continue " +
99
+ "automatically once they are connected. Do NOT say where the card is; never " +
100
+ 'say "below", "above", "at the bottom", or "here". Do NOT tell them to run ' +
101
+ "`claude setup-token`, paste a token in chat, run credential CLI commands, " +
102
+ "or re-run the agent yourself; the card and auto-continue handle it.";
@@ -5,6 +5,7 @@ import {
5
5
  deleteConversation,
6
6
  setConversation,
7
7
  } from "../daemon/conversation-registry.js";
8
+ import { hasAcpConnectCardRaised } from "./acp-connect-card-state.js";
8
9
  import { VellumAcpClientHandler } from "./client-handler.js";
9
10
  import { AcpSessionManager } from "./session-manager.js";
10
11
 
@@ -310,3 +311,121 @@ describe("AcpSessionManager parent notification", () => {
310
311
  expect((manager.getStatus() as unknown[]).length).toBe(1);
311
312
  });
312
313
  });
314
+
315
+ // ---------------------------------------------------------------------------
316
+ // Auth-required recovery surface
317
+ // ---------------------------------------------------------------------------
318
+
319
+ describe("AcpSessionManager auth-required recovery surface", () => {
320
+ /** The live-captured shape of a rejected-credential failure. */
321
+ const authFailure = () =>
322
+ Promise.reject(
323
+ new Error(
324
+ "Internal error: Failed to authenticate. API Error: 401 OAuth access token has been revoked.",
325
+ ),
326
+ );
327
+
328
+ /** Drives an auth-shaped prompt failure through firePromptInBackground. */
329
+ async function driveAuthFailure(opts: {
330
+ id: string;
331
+ command: string;
332
+ parentToolUseId?: string;
333
+ cancelled?: boolean;
334
+ }) {
335
+ const manager = new AcpSessionManager(1);
336
+ const parentId = `parent-${opts.id}`;
337
+ const { conversation, persistUserMessage, loopRan } = mockConversation();
338
+ setConversation(parentId, conversation);
339
+ registered.push(parentId);
340
+
341
+ const entry = injectSession(
342
+ manager,
343
+ opts.id,
344
+ parentId,
345
+ fakeProcess(authFailure),
346
+ );
347
+ entry.command = opts.command;
348
+ (entry as { parentToolUseId?: string }).parentToolUseId =
349
+ opts.parentToolUseId;
350
+ if (opts.cancelled) {
351
+ entry.state.status = "cancelled";
352
+ }
353
+
354
+ await fire(manager, opts.id, entry).catch(() => {});
355
+ if (!opts.cancelled) {
356
+ await loopRan;
357
+ }
358
+
359
+ const events = (
360
+ entry.sendToVellum as ReturnType<typeof mock>
361
+ ).mock.calls.map((c) => c[0] as { type: string } & Record<string, unknown>);
362
+ const firstPersist = persistUserMessage.mock.calls[0] as unknown as
363
+ | [{ content: string }]
364
+ | undefined;
365
+ return {
366
+ parentId,
367
+ authEvent: events.find((e) => e.type === "acp_auth_required"),
368
+ persistedContent: firstPersist?.[0].content,
369
+ };
370
+ }
371
+
372
+ test("claude failure with an anchor raises the full surface: event, registry mark, guidance", async () => {
373
+ const r = await driveAuthFailure({
374
+ id: "sess-auth-anchor",
375
+ command: "claude-agent-acp",
376
+ parentToolUseId: "tool-anchor-1",
377
+ });
378
+
379
+ expect(r.authEvent).toMatchObject({
380
+ acpSessionId: "sess-auth-anchor",
381
+ authCode: "acp_claude_auth_required",
382
+ agent: "claude",
383
+ parentToolUseId: "tool-anchor-1",
384
+ });
385
+ // The credential-prompt route consults this registry to redirect a
386
+ // redundant secure prompt at the card instead of stacking a second one.
387
+ expect(hasAcpConnectCardRaised(r.parentId)).toBe(true);
388
+ expect(r.persistedContent).toContain("Connect Claude Code");
389
+ });
390
+
391
+ test("claude failure without an anchor keeps the plain failure: no event, no mark, no guidance", async () => {
392
+ // No spawning tool call means no transcript row to render the card under;
393
+ // guidance would point the model at a card that cannot appear.
394
+ const r = await driveAuthFailure({
395
+ id: "sess-auth-noanchor",
396
+ command: "claude-agent-acp",
397
+ });
398
+
399
+ expect(r.authEvent).toBeUndefined();
400
+ expect(hasAcpConnectCardRaised(r.parentId)).toBe(false);
401
+ expect(r.persistedContent).not.toContain("Connect Claude Code");
402
+ });
403
+
404
+ test("a run the user already stopped raises nothing: no event, no registry mark, no parent turn", async () => {
405
+ // The client never renders a card for a cancelled run, and the
406
+ // prompt-dedup registry is never cleared, so marking it here would
407
+ // suppress the secure token prompt for the daemon's lifetime against a
408
+ // card that does not exist.
409
+ const r = await driveAuthFailure({
410
+ id: "sess-auth-cancelled",
411
+ command: "claude-agent-acp",
412
+ parentToolUseId: "tool-anchor-3",
413
+ cancelled: true,
414
+ });
415
+
416
+ expect(r.authEvent).toBeUndefined();
417
+ expect(hasAcpConnectCardRaised(r.parentId)).toBe(false);
418
+ expect(r.persistedContent).toBeUndefined();
419
+ });
420
+
421
+ test("a non-claude adapter never raises the surface, even on an auth-shaped failure", async () => {
422
+ const r = await driveAuthFailure({
423
+ id: "sess-auth-codex",
424
+ command: "codex-acp",
425
+ parentToolUseId: "tool-anchor-2",
426
+ });
427
+
428
+ expect(r.authEvent).toBeUndefined();
429
+ expect(hasAcpConnectCardRaised(r.parentId)).toBe(false);
430
+ });
431
+ });
@@ -15,7 +15,15 @@ import { getDb } from "../persistence/db-connection.js";
15
15
  import { acpSessionHistory } from "../persistence/schema/index.js";
16
16
  import * as pendingInteractions from "../runtime/pending-interactions.js";
17
17
  import { getLogger } from "../util/logger.js";
18
+ import { markAcpConnectCardRaised } from "./acp-connect-card-state.js";
18
19
  import { AcpAgentProcess } from "./agent-process.js";
20
+ import {
21
+ ACP_AUTH_RECOVERY_GUIDANCE,
22
+ ACP_CLAUDE_AUTH_REQUIRED_CODE,
23
+ CLAUDE_ACP_COMMAND,
24
+ isAcpAuthRequired,
25
+ isClaudeAuthFailureMessage,
26
+ } from "./auth-required.js";
19
27
  import { resolveAgentWithAutoInstall } from "./auto-install.js";
20
28
  import { VellumAcpClientHandler } from "./client-handler.js";
21
29
  import { deriveFailureError } from "./failure-error.js";
@@ -26,6 +34,30 @@ import type { AcpAgentConfig, AcpSessionState } from "./types.js";
26
34
 
27
35
  const log = getLogger("acp:session-manager");
28
36
 
37
+ /**
38
+ * The `authCode` for a run that failed on its Claude credential, or undefined
39
+ * for any other failure. Adapter-gated first: the signals are Claude-specific,
40
+ * and the marker promises a repair only the Connect Claude flow can perform.
41
+ * Checks both auth-failure shapes (see `auth-required.ts`) against both the
42
+ * raw rejection and the derived failure message, since `deriveFailureError`
43
+ * may replace one with the other.
44
+ */
45
+ function claudeAuthRequiredCode(
46
+ err: unknown,
47
+ failureMessage: string,
48
+ entry: { command: string },
49
+ ): string | undefined {
50
+ if (entry.command !== CLAUDE_ACP_COMMAND) {
51
+ return undefined;
52
+ }
53
+ const rawMessage = err instanceof Error ? err.message : String(err);
54
+ return isAcpAuthRequired(err) ||
55
+ isClaudeAuthFailureMessage(rawMessage) ||
56
+ isClaudeAuthFailureMessage(failureMessage)
57
+ ? ACP_CLAUDE_AUTH_REQUIRED_CODE
58
+ : undefined;
59
+ }
60
+
29
61
  /**
30
62
  * The manager's "unknown session id" error. Thrown whenever an operation
31
63
  * references an acpSessionId with no in-memory entry (and, for resume, no
@@ -1093,6 +1125,11 @@ export class AcpSessionManager {
1093
1125
  err.message,
1094
1126
  current.process.stderrSince(stderrMark),
1095
1127
  );
1128
+ const errorCode = claudeAuthRequiredCode(
1129
+ err,
1130
+ failureMessage,
1131
+ current,
1132
+ );
1096
1133
  if (current.state.status !== "cancelled") {
1097
1134
  current.state.status = "failed";
1098
1135
  current.state.completedAt = Date.now();
@@ -1100,14 +1137,40 @@ export class AcpSessionManager {
1100
1137
  }
1101
1138
  current.currentPrompt = null;
1102
1139
  log.error(
1103
- { acpSessionId, error: err.message, failureMessage },
1140
+ { acpSessionId, error: err.message, failureMessage, errorCode },
1104
1141
  "ACP prompt failed",
1105
1142
  );
1143
+ // `acp_session_error` keeps its pre-existing shape so older packaged
1144
+ // clients still parse it; the recovery signal rides its own event
1145
+ // below (see `api/events/acp-auth-required.ts`).
1106
1146
  current.sendToVellum({
1107
1147
  type: "acp_session_error",
1108
1148
  acpSessionId,
1109
1149
  error: failureMessage,
1110
1150
  });
1151
+ // The recovery surface (event, model guidance, prompt-dedup marker)
1152
+ // is raised as a unit, and only when a spawning tool call exists to
1153
+ // anchor the card AND the user did not already stop the run. A
1154
+ // cancelled run renders no card (the client guards it), so marking
1155
+ // the never-cleared prompt-dedup registry here would suppress the
1156
+ // secure token prompt against a card that never appears.
1157
+ const recoveryAnchor =
1158
+ errorCode !== undefined && current.state.status !== "cancelled"
1159
+ ? current.parentToolUseId
1160
+ : undefined;
1161
+ if (errorCode !== undefined && recoveryAnchor !== undefined) {
1162
+ current.sendToVellum({
1163
+ type: "acp_auth_required",
1164
+ acpSessionId,
1165
+ authCode: errorCode,
1166
+ agent: current.state.agentId,
1167
+ parentToolUseId: recoveryAnchor,
1168
+ });
1169
+ // Same registry as the missing-token spawn path, so the
1170
+ // credential-prompt route redirects a redundant secure prompt at
1171
+ // the card instead of stacking a second one.
1172
+ markAcpConnectCardRaised(current.parentConversationId);
1173
+ }
1111
1174
 
1112
1175
  // Persist the terminal row before teardown clears the buffer.
1113
1176
  this.persistTerminal(acpSessionId, current);
@@ -1123,7 +1186,10 @@ export class AcpSessionManager {
1123
1186
  if (current.state.status !== "cancelled") {
1124
1187
  this.notifyParent(
1125
1188
  current,
1126
- `[ACP agent "${current.state.agentId}" failed]\n\n${failureMessage}`,
1189
+ `[ACP agent "${current.state.agentId}" failed]\n\n${failureMessage}` +
1190
+ (recoveryAnchor !== undefined
1191
+ ? `\n\n${ACP_AUTH_RECOVERY_GUIDANCE}`
1192
+ : ""),
1127
1193
  );
1128
1194
  }
1129
1195
  }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * `acp_auth_required` SSE event.
3
+ *
4
+ * Server to client notification that an ACP run failed because the agent
5
+ * rejected its stored credential and the client can offer a re-authentication
6
+ * affordance. Always emitted immediately AFTER the `acp_session_error` that
7
+ * carries the human-readable failure.
8
+ *
9
+ * It is a separate event rather than a field on `acp_session_error` because
10
+ * every event schema here is `.strict()` and clients fall back to an inert
11
+ * `unknown` event when parsing fails: a new FIELD makes an older packaged
12
+ * client (iOS/macOS bundle the web app) reject the whole error event and
13
+ * render the run as still active, while an unknown event TYPE is simply
14
+ * ignored. Additive signals on existing events need their own event type for
15
+ * the same reason.
16
+ *
17
+ * Canonical wire-contract source. Re-exported to external consumers via
18
+ * `@vellumai/assistant-api` (the `api/index.ts` barrel).
19
+ */
20
+
21
+ import { z } from "zod";
22
+
23
+ /**
24
+ * The code for a `claude-agent-acp` run whose Claude credential needs to be
25
+ * reconnected: the `authCode` on this event for post-spawn failures, and the
26
+ * `errorCode` on the failed `acp_spawn` tool result for pre-spawn ones.
27
+ * Single source for both sides of the wire: the daemon re-exports it via
28
+ * `acp/auth-required.ts`, the web client via
29
+ * `domains/chat/utils/acp-connect.ts`.
30
+ */
31
+ export const ACP_CLAUDE_AUTH_REQUIRED_CODE = "acp_claude_auth_required";
32
+
33
+ export const AcpAuthRequiredEventSchema = z
34
+ .object({
35
+ type: z.literal("acp_auth_required"),
36
+ acpSessionId: z.string(),
37
+ /**
38
+ * Machine-readable classification of what kind of re-authentication is
39
+ * needed, so clients branch on a stable value rather than on the failure
40
+ * text (which varies by adapter and failure mode). Currently only
41
+ * {@link ACP_CLAUDE_AUTH_REQUIRED_CODE}.
42
+ */
43
+ authCode: z.string(),
44
+ /** Agent id the run was spawned with, for display. */
45
+ agent: z.string(),
46
+ /**
47
+ * Tool-use id of the `acp_spawn` call that started this run, so the
48
+ * client anchors the inline affordance to the right transcript row.
49
+ * Absent when the run was not started by a tool call.
50
+ */
51
+ parentToolUseId: z.string().optional(),
52
+ })
53
+ .strict();
54
+
55
+ export type AcpAuthRequiredEvent = z.infer<typeof AcpAuthRequiredEventSchema>;
package/src/api/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
 
3
+ import { AcpAuthRequiredEventSchema } from "./events/acp-auth-required.js";
3
4
  import { AcpSessionCompletedEventSchema } from "./events/acp-session-completed.js";
4
5
  import { AcpSessionErrorEventSchema } from "./events/acp-session-error.js";
5
6
  import { AcpSessionSpawnedEventSchema } from "./events/acp-session-spawned.js";
@@ -149,6 +150,11 @@ export {
149
150
  SSE_REPLAY_RING_COUNT_LIMIT,
150
151
  } from "./constants/sse-replay.js";
151
152
  export { DEFAULT_TOOL_EXECUTION_TIMEOUT_SEC } from "./constants/tool-execution.js";
153
+ export {
154
+ ACP_CLAUDE_AUTH_REQUIRED_CODE,
155
+ type AcpAuthRequiredEvent,
156
+ AcpAuthRequiredEventSchema,
157
+ } from "./events/acp-auth-required.js";
152
158
  export {
153
159
  type AcpSessionCompletedEvent,
154
160
  AcpSessionCompletedEventSchema,
@@ -895,6 +901,7 @@ export {
895
901
  * migration recipe.
896
902
  */
897
903
  export const AssistantEventSchema = z.discriminatedUnion("type", [
904
+ AcpAuthRequiredEventSchema,
898
905
  AcpSessionCompletedEventSchema,
899
906
  AcpSessionErrorEventSchema,
900
907
  AcpSessionSpawnedEventSchema,
@@ -27,6 +27,7 @@ import {
27
27
  cleanupWorkerPidFile,
28
28
  startWorkerPidFileGuard,
29
29
  } from "../../../util/worker-process.js";
30
+ import { registerWorkerPluginSurface } from "../../worker-plugin-surface.js";
30
31
  import { registerMemoryPluginJobHandlers } from "./job-handler-registration.js";
31
32
  import { startMemoryJobsWorkerLoop } from "./jobs-worker.js";
32
33
  import { getLogger } from "./logging.js";
@@ -59,9 +60,11 @@ async function main(): Promise<void> {
59
60
  // and are rejected.
60
61
  await rehydratePlatformCredentials();
61
62
 
62
- // This process does not run plugin bootstrap, so self-register the job
63
- // handlers the worker dispatches from before starting it — the memory
64
- // plugin's own plus the host's non-plugin domain handlers.
63
+ // Jobs in this process wake real agent conversations, so it registers the
64
+ // default plugin hook surface (hooks and injectors, no init hooks) the same
65
+ // way the daemon does, and the job handlers the worker dispatches from: the
66
+ // memory plugin's own plus the host's non-plugin domain handlers.
67
+ registerWorkerPluginSurface();
65
68
  registerMemoryPluginJobHandlers();
66
69
 
67
70
  // Populate the tool registry (core built-ins + workspace tools), exactly as
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Default-plugin surface for sidecar worker processes.
3
+ *
4
+ * Worker processes that run real agent conversations (the memory jobs worker,
5
+ * the schedule worker) register the first-party default plugins' hooks and
6
+ * runtime injectors so those conversations get the same hook-driven behavior as
7
+ * conversations in the daemon: image captioning and vision-rejection recovery,
8
+ * tool-result truncation, history repair, and the per-turn runtime injections.
9
+ * Hook and injector dispatch is process-global, so one call at worker startup
10
+ * covers every conversation that process runs.
11
+ *
12
+ * Plugin `init` hooks are deliberately not run here. Registration is pure
13
+ * hook-table and injector-table population, and the default plugins degrade
14
+ * gracefully without their init-owned state (the image-fallback caption cache
15
+ * falls back to in-memory caching when its SQLite handle is absent). The memory
16
+ * plugin's init must never run in a worker: it starts the memory jobs worker
17
+ * process itself.
18
+ */
19
+
20
+ import {
21
+ registerDefaultPluginInjectors,
22
+ registerDefaultPlugins,
23
+ } from "./defaults/index.js";
24
+
25
+ /**
26
+ * Register the first-party default plugins' hooks and runtime injectors in the
27
+ * current process. Both registration functions are idempotent, so repeat calls
28
+ * are safe.
29
+ */
30
+ export function registerWorkerPluginSurface(): void {
31
+ registerDefaultPlugins();
32
+ registerDefaultPluginInjectors();
33
+ }
@@ -16,6 +16,7 @@ import { writeFileSync } from "node:fs";
16
16
  import { getConfig } from "../config/loader.js";
17
17
  import { rehydratePlatformCredentials } from "../config/platform-rehydration.js";
18
18
  import { resetDb } from "../persistence/db-connection.js";
19
+ import { registerWorkerPluginSurface } from "../plugins/worker-plugin-surface.js";
19
20
  import { disableStreamSeqStamping } from "../runtime/assistant-stream-state.js";
20
21
  import { initializeTools } from "../tools/registry.js";
21
22
  import { getLogger } from "../util/logger.js";
@@ -51,6 +52,11 @@ async function main(): Promise<void> {
51
52
  // rejected for both inference and background-wake requests.
52
53
  await rehydratePlatformCredentials();
53
54
 
55
+ // This process is the sole runner of schedule execution and hosts real agent
56
+ // conversations (wake, execute, and workflow modes), so it needs the default
57
+ // plugins' hooks and injectors just like the daemon.
58
+ registerWorkerPluginSurface();
59
+
54
60
  // Populate the tool registry (core built-ins + workspace tools). The daemon
55
61
  // does this at startup; this standalone process has to do it itself so
56
62
  // workflow schedules pass the core-tools readiness gate and agent-executed
@@ -147,6 +147,11 @@ const { _resetAdapterInstallCacheForTests } =
147
147
  await import("../../acp/auto-install.js");
148
148
  const { ACP_CLAUDE_OAUTH_MISSING_CODE } =
149
149
  await import("../../acp/prepare-agent-env.js");
150
+ const { ACP_CLAUDE_AUTH_REQUIRED_CODE, AcpAuthRequiredError } =
151
+ await import("../../acp/auth-required.js");
152
+ const { hasAcpConnectCardRaised } =
153
+ await import("../../acp/acp-connect-card-state.js");
154
+ const { AcpAgentProcess } = await import("../../acp/agent-process.js");
150
155
 
151
156
  // ---------------------------------------------------------------------------
152
157
  // Helpers
@@ -547,3 +552,95 @@ describe("executeAcpSpawn — CLAUDE_CODE_OAUTH_TOKEN injection", () => {
547
552
  expect(result.errorCode).toBe(ACP_CLAUDE_OAUTH_MISSING_CODE);
548
553
  });
549
554
  });
555
+
556
+ // ---------------------------------------------------------------------------
557
+ // Pre-spawn Claude auth rejection
558
+ // ---------------------------------------------------------------------------
559
+
560
+ describe("pre-spawn Claude auth rejection", () => {
561
+ test("raises the recovery surface: errorCode, card guidance, registry mark", async () => {
562
+ // The adapter can reject session creation with auth_required (a stored
563
+ // credential the server refuses). The error thrown here is produced by
564
+ // the REAL conversion seam, not hand-built: a wire-shaped JSON-RPC
565
+ // auth_required rejection driven through AcpAgentProcess.createSession's
566
+ // actual retry path, so this test fails if that seam stops yielding the
567
+ // typed error the tool boundary maps to the recovery surface.
568
+ const proc = new AcpAgentProcess(
569
+ "claude",
570
+ { command: "claude-agent-acp", args: [] },
571
+ (() => ({})) as never,
572
+ );
573
+ (proc as unknown as { connection: unknown }).connection = {
574
+ newSession: () =>
575
+ Promise.reject({ code: -32000, message: "Authentication required" }),
576
+ };
577
+ (proc as unknown as { initializeResponse: unknown }).initializeResponse = {
578
+ authMethods: [
579
+ {
580
+ id: "claude-ai-login",
581
+ name: "Claude Subscription",
582
+ type: "terminal",
583
+ },
584
+ ],
585
+ };
586
+ (proc as unknown as { spawnedEnv: unknown }).spawnedEnv = {};
587
+ const realSeamError: unknown = await proc.createSession("/tmp").then(
588
+ () => null,
589
+ (e: unknown) => e,
590
+ );
591
+ expect(realSeamError).toBeInstanceOf(AcpAuthRequiredError);
592
+
593
+ spawnMock.mockImplementationOnce(async () => {
594
+ throw realSeamError;
595
+ });
596
+
597
+ const context = { ...makeContext(), conversationId: "conv-prespawn-auth" };
598
+ const result = await executeAcpSpawn(
599
+ { agent: "claude", task: "do something" },
600
+ context,
601
+ );
602
+
603
+ expect(result.isError).toBe(true);
604
+ expect(result.errorCode).toBe(ACP_CLAUDE_AUTH_REQUIRED_CODE);
605
+ expect(result.content).toContain("Connect Claude Code");
606
+ expect(hasAcpConnectCardRaised("conv-prespawn-auth")).toBe(true);
607
+ });
608
+
609
+ test("a raw wire auth_required object (unwrapped initialize path) gets the same surface", async () => {
610
+ // initialize() cannot ride withAuthRetry (its response advertises the
611
+ // methods the retry selects from), so its rejection arrives as the plain
612
+ // JSON-RPC object rather than the typed error. The gate must recognize
613
+ // both shapes or this path silently flattens to a generic failure.
614
+ spawnMock.mockImplementationOnce(async () => {
615
+ throw { code: -32000, message: "Authentication required" };
616
+ });
617
+
618
+ const context = { ...makeContext(), conversationId: "conv-prespawn-raw" };
619
+ const result = await executeAcpSpawn(
620
+ { agent: "claude", task: "do something" },
621
+ context,
622
+ );
623
+
624
+ expect(result.isError).toBe(true);
625
+ expect(result.errorCode).toBe(ACP_CLAUDE_AUTH_REQUIRED_CODE);
626
+ expect(result.content).toContain("Connect Claude Code");
627
+ expect(hasAcpConnectCardRaised("conv-prespawn-raw")).toBe(true);
628
+ });
629
+
630
+ test("a non-auth spawn failure keeps the plain flattened result", async () => {
631
+ spawnMock.mockImplementationOnce(async () => {
632
+ throw new Error("adapter exploded");
633
+ });
634
+
635
+ const context = { ...makeContext(), conversationId: "conv-prespawn-boom" };
636
+ const result = await executeAcpSpawn(
637
+ { agent: "claude", task: "do something" },
638
+ context,
639
+ );
640
+
641
+ expect(result.isError).toBe(true);
642
+ expect(result.errorCode).toBeUndefined();
643
+ expect(result.content).toContain("adapter exploded");
644
+ expect(hasAcpConnectCardRaised("conv-prespawn-boom")).toBe(false);
645
+ });
646
+ });
@@ -3,6 +3,12 @@ import { basename } from "node:path";
3
3
  import { z } from "zod";
4
4
 
5
5
  import { markAcpConnectCardRaised } from "../../acp/acp-connect-card-state.js";
6
+ import {
7
+ ACP_AUTH_RECOVERY_GUIDANCE,
8
+ ACP_CLAUDE_AUTH_REQUIRED_CODE,
9
+ CLAUDE_ACP_COMMAND,
10
+ isAcpAuthRequired,
11
+ } from "../../acp/auth-required.js";
6
12
  import { resolveAgentWithAutoInstall } from "../../acp/auto-install.js";
7
13
  import { getAcpSessionManager } from "../../acp/index.js";
8
14
  import {
@@ -147,6 +153,32 @@ export async function executeAcpSpawn(
147
153
 
148
154
  return { content: payload, isError: false };
149
155
  } catch (err) {
156
+ // A pre-spawn rejection of the stored Claude credential (the adapter
157
+ // raises auth_required during session creation) gets the same recovery
158
+ // surface as the missing-token preflight: the errorCode raises the inline
159
+ // Connect card off this failed tool call, the registry mark dedups a
160
+ // redundant secure prompt, and the guidance keeps the model pointed at
161
+ // the card. Adapter-gated: the card repairs Claude credentials only.
162
+ // `isAcpAuthRequired` rather than an instanceof: it also recognizes the
163
+ // raw JSON-RPC auth_required object, which is how a rejection reaches
164
+ // this catch from the one protocol call `withAuthRetry` cannot wrap
165
+ // (`initialize`, whose response is what advertises the auth methods the
166
+ // retry would need).
167
+ if (
168
+ isAcpAuthRequired(err) &&
169
+ basename(agentConfig.command) === CLAUDE_ACP_COMMAND
170
+ ) {
171
+ const message =
172
+ err instanceof Error
173
+ ? err.message
174
+ : String((err as { message?: unknown }).message ?? err);
175
+ markAcpConnectCardRaised(context.conversationId);
176
+ return {
177
+ content: `${message}\n\n${ACP_AUTH_RECOVERY_GUIDANCE}`,
178
+ isError: true,
179
+ errorCode: ACP_CLAUDE_AUTH_REQUIRED_CODE,
180
+ };
181
+ }
150
182
  const msg =
151
183
  err instanceof Error
152
184
  ? err.message