@moxxy/plugin-provider-claude-code 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/dist/account-limit.d.ts +8 -0
  2. package/dist/account-limit.d.ts.map +1 -0
  3. package/dist/account-limit.js +23 -0
  4. package/dist/account-limit.js.map +1 -0
  5. package/dist/agent-provider.d.ts +61 -0
  6. package/dist/agent-provider.d.ts.map +1 -0
  7. package/dist/agent-provider.js +195 -0
  8. package/dist/agent-provider.js.map +1 -0
  9. package/dist/agent-session.d.ts +145 -0
  10. package/dist/agent-session.d.ts.map +1 -0
  11. package/dist/agent-session.js +703 -0
  12. package/dist/agent-session.js.map +1 -0
  13. package/dist/background-work.d.ts +42 -0
  14. package/dist/background-work.d.ts.map +1 -0
  15. package/dist/background-work.js +140 -0
  16. package/dist/background-work.js.map +1 -0
  17. package/dist/constants.d.ts +2 -2
  18. package/dist/constants.d.ts.map +1 -1
  19. package/dist/constants.js +2 -2
  20. package/dist/constants.js.map +1 -1
  21. package/dist/executable.d.ts +15 -0
  22. package/dist/executable.d.ts.map +1 -0
  23. package/dist/executable.js +30 -0
  24. package/dist/executable.js.map +1 -0
  25. package/dist/index.d.ts +4 -3
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +55 -16
  28. package/dist/index.js.map +1 -1
  29. package/dist/login.d.ts +3 -0
  30. package/dist/login.d.ts.map +1 -1
  31. package/dist/login.js +8 -1
  32. package/dist/login.js.map +1 -1
  33. package/dist/offered-models.d.ts +13 -0
  34. package/dist/offered-models.d.ts.map +1 -0
  35. package/dist/offered-models.js +48 -0
  36. package/dist/offered-models.js.map +1 -0
  37. package/dist/own-settings.d.ts +12 -0
  38. package/dist/own-settings.d.ts.map +1 -0
  39. package/dist/own-settings.js +31 -0
  40. package/dist/own-settings.js.map +1 -0
  41. package/dist/questions.d.ts +6 -0
  42. package/dist/questions.d.ts.map +1 -0
  43. package/dist/questions.js +38 -0
  44. package/dist/questions.js.map +1 -0
  45. package/dist/scheduled-wakeups.d.ts +10 -0
  46. package/dist/scheduled-wakeups.d.ts.map +1 -0
  47. package/dist/scheduled-wakeups.js +30 -0
  48. package/dist/scheduled-wakeups.js.map +1 -0
  49. package/dist/sdk-install.d.ts +25 -0
  50. package/dist/sdk-install.d.ts.map +1 -0
  51. package/dist/sdk-install.js +94 -0
  52. package/dist/sdk-install.js.map +1 -0
  53. package/dist/sdk-types.d.ts +312 -0
  54. package/dist/sdk-types.d.ts.map +1 -0
  55. package/dist/sdk-types.js +8 -0
  56. package/dist/sdk-types.js.map +1 -0
  57. package/dist/subagents.d.ts +39 -0
  58. package/dist/subagents.d.ts.map +1 -0
  59. package/dist/subagents.js +114 -0
  60. package/dist/subagents.js.map +1 -0
  61. package/dist/task-list.d.ts +21 -0
  62. package/dist/task-list.d.ts.map +1 -0
  63. package/dist/task-list.js +68 -0
  64. package/dist/task-list.js.map +1 -0
  65. package/dist/translate.d.ts +66 -0
  66. package/dist/translate.d.ts.map +1 -0
  67. package/dist/translate.js +302 -0
  68. package/dist/translate.js.map +1 -0
  69. package/package.json +14 -9
  70. package/src/account-limit.ts +26 -0
  71. package/src/agent-cli.test.ts +83 -0
  72. package/src/agent-provider.test.ts +1176 -0
  73. package/src/agent-provider.ts +223 -0
  74. package/src/agent-session.ts +793 -0
  75. package/src/background-work.ts +163 -0
  76. package/src/constants.ts +2 -3
  77. package/src/event-coverage.test.ts +106 -0
  78. package/src/executable.test.ts +60 -0
  79. package/src/executable.ts +34 -0
  80. package/src/fake-claude.testkit.ts +376 -0
  81. package/src/fixtures/claude-agent-sdk-0.3.296.json +43 -0
  82. package/src/fixtures/claude-supported-models-0.3.296.json +218 -0
  83. package/src/index.test.ts +49 -0
  84. package/src/index.ts +61 -18
  85. package/src/login.ts +10 -1
  86. package/src/offered-models.test.ts +81 -0
  87. package/src/offered-models.ts +60 -0
  88. package/src/own-settings.test.ts +68 -0
  89. package/src/own-settings.ts +33 -0
  90. package/src/questions.test.ts +68 -0
  91. package/src/questions.ts +45 -0
  92. package/src/scheduled-wakeups.test.ts +41 -0
  93. package/src/scheduled-wakeups.ts +34 -0
  94. package/src/sdk-install.test.ts +124 -0
  95. package/src/sdk-install.ts +107 -0
  96. package/src/sdk-types.ts +278 -0
  97. package/src/subagents.ts +123 -0
  98. package/src/task-list.ts +65 -0
  99. package/src/translate.test.ts +474 -0
  100. package/src/translate.ts +306 -0
  101. package/dist/process.d.ts +0 -34
  102. package/dist/process.d.ts.map +0 -1
  103. package/dist/process.js +0 -197
  104. package/dist/process.js.map +0 -1
  105. package/dist/protocol.d.ts +0 -30
  106. package/dist/protocol.d.ts.map +0 -1
  107. package/dist/protocol.js +0 -368
  108. package/dist/protocol.js.map +0 -1
  109. package/dist/provider.d.ts +0 -53
  110. package/dist/provider.d.ts.map +0 -1
  111. package/dist/provider.js +0 -229
  112. package/dist/provider.js.map +0 -1
  113. package/src/process.test.ts +0 -208
  114. package/src/process.ts +0 -224
  115. package/src/protocol.ts +0 -390
  116. package/src/provider.test.ts +0 -671
  117. package/src/provider.ts +0 -267
@@ -0,0 +1,163 @@
1
+ import { open } from 'node:fs/promises';
2
+ import { AGENT_WORK_OUTPUT_LIMIT, type AgentBackgroundWork, type AgentStepEvent, type AgentWorkEnd } from '@moxxy/sdk';
3
+
4
+ /** Claude's `task_type` of a helper agent; every other task runs a command (a shell, a monitor, a workflow). */
5
+ const AGENT_TASK = 'local_agent';
6
+
7
+ interface Task {
8
+ type?: string;
9
+ description?: string;
10
+ /** The call that started it; a helper's work id, as its `subagent_*` events carry it. */
11
+ toolUseId?: string;
12
+ }
13
+
14
+ interface Note {
15
+ readonly subtype?: unknown;
16
+ readonly task_id?: unknown;
17
+ readonly tool_use_id?: unknown;
18
+ readonly task_type?: unknown;
19
+ readonly description?: unknown;
20
+ readonly tasks?: unknown;
21
+ readonly status?: unknown;
22
+ readonly summary?: unknown;
23
+ readonly output_file?: unknown;
24
+ }
25
+
26
+ /**
27
+ * What Claude runs in the background, as Moxxy's background work: its
28
+ * `background_tasks_changed` list (the whole list each time, so a missed end
29
+ * cannot leave work shown running), and how each command it ran there ended.
30
+ */
31
+ export class ClaudeBackgroundWork {
32
+ private readonly tasks = new Map<string, Task>();
33
+ /** Ids of the tasks in Claude's last list. */
34
+ private live: ReadonlyArray<string> = [];
35
+ private shown: ReadonlyArray<AgentBackgroundWork> = [];
36
+ /** Tasks that ran in the background at some point: only their end is background work ending. */
37
+ private readonly wentBackground = new Set<string>();
38
+ private readonly ended = new Set<string>();
39
+
40
+ /** A `task_started` or `background_tasks_changed`: the list again when what it shows changed. */
41
+ fromNote(note: Note): AgentStepEvent[] {
42
+ if (note.subtype === 'task_started' && typeof note.task_id === 'string') {
43
+ this.task(note.task_id, {
44
+ ...(typeof note.task_type === 'string' ? { type: note.task_type } : {}),
45
+ ...(typeof note.description === 'string' ? { description: note.description } : {}),
46
+ ...(typeof note.tool_use_id === 'string' ? { toolUseId: note.tool_use_id } : {}),
47
+ });
48
+ return this.listed();
49
+ }
50
+ if (note.subtype !== 'background_tasks_changed' || !Array.isArray(note.tasks)) return [];
51
+ const live: string[] = [];
52
+ for (const entry of note.tasks as ReadonlyArray<Record<string, unknown>>) {
53
+ // Housekeeping Claude runs for itself is not work of the person's conversation.
54
+ if (typeof entry.task_id !== 'string' || entry.ambient === true) continue;
55
+ this.task(entry.task_id, {
56
+ ...(typeof entry.task_type === 'string' ? { type: entry.task_type } : {}),
57
+ ...(typeof entry.description === 'string' ? { description: entry.description } : {}),
58
+ });
59
+ this.wentBackground.add(entry.task_id);
60
+ live.push(entry.task_id);
61
+ }
62
+ this.live = live;
63
+ return this.listed();
64
+ }
65
+
66
+ /** A `task_notification`: how a command Claude ran in the background ended, with the end of its output. A helper's end is its `subagent_completed`. */
67
+ async end(note: Note, read: (file: string) => Promise<string> = readOutputEnd): Promise<AgentStepEvent[]> {
68
+ if (note.subtype !== 'task_notification' || typeof note.task_id !== 'string') return [];
69
+ const id = note.task_id;
70
+ const task = this.tasks.get(id);
71
+ if (!task || task.type === AGENT_TASK || !this.wentBackground.has(id) || this.ended.has(id)) return [];
72
+ this.ended.add(id);
73
+ const output = typeof note.output_file === 'string' && note.output_file ? await read(note.output_file).catch(() => '') : '';
74
+ const summary = typeof note.summary === 'string' ? note.summary : '';
75
+ return [
76
+ {
77
+ type: 'background_work_ended',
78
+ id,
79
+ kind: 'command',
80
+ label: task.description ?? (summary || 'Background command'),
81
+ status: endOf(note.status),
82
+ ...(summary ? { summary } : {}),
83
+ ...(output ? { output } : {}),
84
+ },
85
+ ];
86
+ }
87
+
88
+ /** The id Moxxy knows a task by: a helper's call id, else the task's own. */
89
+ workIdOf(taskId: string, toolUseId?: string): string {
90
+ const task = this.tasks.get(taskId);
91
+ if (task?.type === AGENT_TASK) return task.toolUseId ?? toolUseId ?? taskId;
92
+ return taskId;
93
+ }
94
+
95
+ /** The Claude task running the work, if Claude runs it now. */
96
+ taskOf(workId: string): string | undefined {
97
+ return this.live.find((taskId) => this.workIdOf(taskId) === workId);
98
+ }
99
+
100
+ /** Claude is gone: nothing it ran goes on. */
101
+ stopped(): AgentStepEvent[] {
102
+ this.live = [];
103
+ return this.listed();
104
+ }
105
+
106
+ private task(id: string, fields: Task): void {
107
+ this.tasks.set(id, { ...this.tasks.get(id), ...fields });
108
+ }
109
+
110
+ private listed(): AgentStepEvent[] {
111
+ // Claude lists a helper before its `task_started` says which call started it,
112
+ // and that call is the helper's id everywhere else: it is listed once that is known.
113
+ const known = this.live.filter((taskId) => {
114
+ const task = this.tasks.get(taskId);
115
+ return task?.type !== AGENT_TASK || task.toolUseId !== undefined;
116
+ });
117
+ const work = known.map((taskId): AgentBackgroundWork => {
118
+ const task = this.tasks.get(taskId);
119
+ const kind = task?.type === AGENT_TASK ? 'agent' : 'command';
120
+ return { id: this.workIdOf(taskId), kind, label: task?.description ?? (kind === 'agent' ? 'Helper' : 'Background command') };
121
+ });
122
+ if (sameWork(work, this.shown)) return [];
123
+ this.shown = work;
124
+ return [{ type: 'background_work', work }];
125
+ }
126
+ }
127
+
128
+ function endOf(status: unknown): AgentWorkEnd {
129
+ return status === 'completed' || status === 'failed' ? status : 'stopped';
130
+ }
131
+
132
+ function sameWork(a: ReadonlyArray<AgentBackgroundWork>, b: ReadonlyArray<AgentBackgroundWork>): boolean {
133
+ return a.length === b.length && a.every((work, i) => work.id === b[i]?.id && work.kind === b[i]?.kind && work.label === b[i]?.label);
134
+ }
135
+
136
+ /** The end of a task's output file, its colour codes taken out: what a command printed last says how it went. */
137
+ export async function readOutputEnd(file: string): Promise<string> {
138
+ const handle = await open(file, 'r');
139
+ try {
140
+ const { size } = await handle.stat();
141
+ const length = Math.min(size, AGENT_WORK_OUTPUT_LIMIT);
142
+ const buffer = Buffer.alloc(length);
143
+ await handle.read(buffer, 0, length, size - length);
144
+ return withoutEscapes(buffer.toString('utf8'));
145
+ } finally {
146
+ await handle.close();
147
+ }
148
+ }
149
+
150
+ function withoutEscapes(text: string): string {
151
+ let out = '';
152
+ for (let i = 0; i < text.length; i += 1) {
153
+ if (text.charCodeAt(i) !== 0x1b || text[i + 1] !== '[') {
154
+ out += text[i];
155
+ continue;
156
+ }
157
+ // A CSI sequence: ESC [ parameters, ending at the first character in @–~.
158
+ let j = i + 2;
159
+ while (j < text.length && !(text.charCodeAt(j) >= 0x40 && text.charCodeAt(j) <= 0x7e)) j += 1;
160
+ i = j;
161
+ }
162
+ return out;
163
+ }
package/src/constants.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  /** Provider name in the registry / model picker / provider config. */
2
2
  export const CLAUDE_CODE_PROVIDER_ID = 'claude-code';
3
+ /** The agent's name as the person knows it. */
4
+ export const CLAUDE_AGENT_NAME = 'Claude';
3
5
 
4
6
  /** Human-readable upstream service, shown in login and setup surfaces. */
5
7
  export const CLAUDE_CODE_SERVICE_NAME = 'Claude Code subscription';
@@ -11,6 +13,3 @@ export const CLAUDE_CODE_EXECUTABLE_ENV = 'CLAUDE_CODE_EXECUTABLE';
11
13
  export const CLAUDE_AUTH_STATUS_ARGS = ['auth', 'status'] as const;
12
14
  export const CLAUDE_AUTH_LOGIN_ARGS = ['auth', 'login'] as const;
13
15
  export const CLAUDE_AUTH_LOGOUT_ARGS = ['auth', 'logout'] as const;
14
-
15
- /** Required identity line used by the CLI transport. */
16
- export const CLAUDE_CODE_SYSTEM = "You are Claude Code, Anthropic's official CLI for Claude.";
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Every message the Claude Agent SDK 0.3.296 can send — its `SDKMessage`
3
+ * union, listed in fixtures/ — checked against what Moxxy does with it: shown
4
+ * in the chat, or left alone for the reason given. A newer SDK brings a new
5
+ * fixture, and each kind it adds becomes a decision here instead of something
6
+ * lost without a trace. A tool shows whatever its name: one Moxxy has no
7
+ * formatting for is a plain call.
8
+ */
9
+ import { readFileSync } from 'node:fs';
10
+ import { describe, expect, it } from 'vitest';
11
+ import type { ClaudeMessage } from './sdk-types.js';
12
+ import { TurnTranslator } from './translate.js';
13
+
14
+ const kinds = JSON.parse(readFileSync(new URL('./fixtures/claude-agent-sdk-0.3.296.json', import.meta.url), 'utf8')) as { readonly messages: ReadonlyArray<string> };
15
+
16
+ const message = (fields: Record<string, unknown>): ClaudeMessage => fields as unknown as ClaudeMessage;
17
+ const assistant = (content: unknown[], parent: string | null = null) => message({ type: 'assistant', message: { content }, parent_tool_use_id: parent });
18
+ const toolResult = (id: string, content: unknown, toolUseResult?: unknown) =>
19
+ message({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: id, content }] }, parent_tool_use_id: null, ...(toolUseResult ? { tool_use_result: toolUseResult } : {}) });
20
+
21
+ /** The kinds that show, each with messages that lead to it; the last one must show something. */
22
+ const SHOWN: Record<string, ReadonlyArray<ClaudeMessage>> = {
23
+ 'system/init': [message({ type: 'system', subtype: 'init', session_id: 's-1', permissionMode: 'default' })],
24
+ 'system/status': [message({ type: 'system', subtype: 'status', status: null, permissionMode: 'acceptEdits' })],
25
+ stream_event: [message({ type: 'stream_event', event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'Hi' } }, parent_tool_use_id: null })],
26
+ // A sentence on its own is marked by what follows it (see translate.test.ts); with its call it shows at once.
27
+ assistant: [assistant([{ type: 'text', text: 'Reading it.' }, { type: 'tool_use', id: 't0', name: 'Read', input: { file_path: '/w/a.txt' } }])],
28
+ user: [assistant([{ type: 'tool_use', id: 't1', name: 'Read', input: { file_path: '/w/a.txt' } }]), toolResult('t1', 'hello')],
29
+ rate_limit_event: [message({ type: 'rate_limit_event', rate_limit_info: { status: 'allowed_warning', utilization: 0.9 } })],
30
+ 'system/task_notification': [
31
+ assistant([{ type: 'tool_use', id: 'agent-1', name: 'Agent', input: { description: 'List files', prompt: 'list', subagent_type: 'Explore' } }]),
32
+ toolResult('agent-1', 'Async agent launched', { isAsync: true, status: 'async_launched' }),
33
+ message({ type: 'system', subtype: 'task_notification', tool_use_id: 'agent-1', status: 'completed', summary: 'Two files.' }),
34
+ ],
35
+ };
36
+
37
+ /** The kinds Moxxy leaves out of the chat, and why. */
38
+ const LEFT_ALONE: Record<string, string> = {
39
+ result: "ends the turn; the session reads it, with Claude's error when it failed",
40
+ 'system/task_started': 'the session reads it to follow a background subagent or command',
41
+ 'system/task_progress': "its tokens go into the subagent's row when it ends",
42
+ 'system/task_updated': "the subagent's row shows its start and end",
43
+ 'system/background_tasks_changed': 'the session reads it as the list of work Claude runs in the background, for the agents panel',
44
+ 'system/compact_boundary': "Claude shortening its own context; Moxxy's record of the conversation stays whole",
45
+ 'system/api_retry': 'Claude retries by itself; a failure that stays ends the turn with its error',
46
+ 'system/model_refusal_fallback': 'Claude moved to another model by itself and carries on',
47
+ 'system/model_refusal_no_fallback': "the turn's result carries what happened",
48
+ 'system/permission_denied': "the refused call's result says so",
49
+ 'system/hook_started': "the person's own Claude hooks, which run for their own Claude",
50
+ 'system/hook_progress': "the person's own Claude hooks, which run for their own Claude",
51
+ 'system/hook_response': "the person's own Claude hooks, which run for their own Claude",
52
+ 'system/local_command_output': 'output of a slash command, which Moxxy sends only without showing it (`/goal`)',
53
+ 'system/memory_recall': "Claude's own memory, which it reads for itself",
54
+ 'system/files_persisted': "the files show in the calls that wrote them",
55
+ 'system/elicitation_complete': 'an MCP server question, answered through the call it belongs to',
56
+ 'system/control_request_progress': "progress of Moxxy's own requests to Claude",
57
+ 'system/thinking_tokens': 'a count; the reasoning shows itself',
58
+ 'system/session_state_changed': "Claude's session state; Moxxy follows its turn by its messages",
59
+ 'system/worker_shutting_down': 'Claude stopping; Moxxy sees the session end',
60
+ 'system/commands_changed': "Claude's slash commands, which Moxxy does not list",
61
+ 'system/plugin_install': "the person's Claude plugins, installed for their own Claude",
62
+ 'system/notification': "notes for Claude Code's own screen",
63
+ 'system/informational': "notes for Claude Code's own screen",
64
+ 'system/mirror_error': "Claude Code's mirroring of the session elsewhere",
65
+ tool_progress: 'the call shows whole once it ends',
66
+ tool_use_summary: 'the calls it sums up show themselves',
67
+ auth_status: 'sign-in, which Moxxy checks itself',
68
+ prompt_suggestion: "a next message Claude suggests, for Claude Code's own screen",
69
+ conversation_reset: "Claude Code's /clear, which Moxxy does not send",
70
+ };
71
+
72
+ const kindOf = (fields: Record<string, unknown>): string => (fields.type === 'system' ? `system/${String(fields.subtype)}` : String(fields.type));
73
+
74
+ describe('every message the Claude Agent SDK 0.3.296 can send', () => {
75
+ it('has a decision here, so a kind a newer SDK adds needs one', () => {
76
+ expect([...Object.keys(SHOWN), ...Object.keys(LEFT_ALONE)].sort()).toEqual([...kinds.messages]);
77
+ });
78
+
79
+ it.each(Object.keys(SHOWN))('%s shows in the chat', (kind) => {
80
+ const translator = new TurnTranslator();
81
+ const messages = SHOWN[kind] ?? [];
82
+ const last = messages.at(-1);
83
+ for (const earlier of messages.slice(0, -1)) translator.translate(earlier);
84
+
85
+ expect(last && kindOf(last as unknown as Record<string, unknown>)).toBe(kind);
86
+ expect(last ? translator.translate(last).length : 0).toBeGreaterThan(0);
87
+ });
88
+
89
+ it.each(Object.keys(LEFT_ALONE))('%s leaves the chat as it is', (kind) => {
90
+ const [type, subtype] = kind.split('/');
91
+ const alone = message({ type, ...(subtype ? { subtype } : {}), session_id: 's-1', uuid: 'u-1' });
92
+
93
+ expect(new TurnTranslator().translate(alone)).toEqual([]);
94
+ });
95
+ });
96
+
97
+ describe('a tool Moxxy has no formatting for', () => {
98
+ it('shows as a call by its name, with its result', () => {
99
+ const translator = new TurnTranslator();
100
+
101
+ expect(translator.translate(assistant([{ type: 'tool_use', id: 'm1', name: 'Monitor', input: { command: 'tail -f log' } }]))).toEqual([
102
+ { type: 'tool_call', callId: 'm1', name: 'Monitor', input: { command: 'tail -f log' } },
103
+ ]);
104
+ expect(translator.translate(toolResult('m1', 'watching'))).toEqual([{ type: 'tool_result', callId: 'm1', ok: true, output: 'watching' }]);
105
+ });
106
+ });
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The Agent SDK runs the person's own Claude Code CLI. It can start a native
3
+ * binary or a `cli.js`, but not a Windows npm `.cmd` shim, so that one is
4
+ * swapped for the `cli.js` npm put beside it.
5
+ */
6
+ import { afterEach, describe, expect, it } from 'vitest';
7
+ import { mkdtempSync } from 'node:fs';
8
+ import { tmpdir } from 'node:os';
9
+ import path from 'node:path';
10
+ import { CLAUDE_CLI, PATH_FALLBACK_ENV } from '@moxxy/agent-connection-kit';
11
+ import { writeFakeCli } from '@moxxy/vitest-preset/fake-cli';
12
+ import { removeDirSync } from '@moxxy/vitest-preset/fs';
13
+ import { claudeExecutableForSdk, claudeForSdk } from './executable.js';
14
+
15
+ describe('the Claude Code CLI the SDK runs', () => {
16
+ it('runs a native or linked CLI as found', () => {
17
+ expect(claudeExecutableForSdk('/Users/me/.local/bin/claude', () => false)).toBe('/Users/me/.local/bin/claude');
18
+ expect(claudeExecutableForSdk('C:\\Users\\me\\.local\\bin\\claude.exe', () => false)).toBe('C:\\Users\\me\\.local\\bin\\claude.exe');
19
+ });
20
+
21
+ it('runs the cli.js behind a Windows npm shim', () => {
22
+ const shim = path.win32.join('C:\\Users\\me\\AppData\\Roaming\\npm', 'claude.cmd');
23
+ const cli = path.win32.join('C:\\Users\\me\\AppData\\Roaming\\npm', 'node_modules', '@anthropic-ai', 'claude-code', 'cli.js');
24
+
25
+ expect(claudeExecutableForSdk(shim, (file) => file === cli, path.win32)).toBe(cli);
26
+ });
27
+
28
+ it('refuses a shim it cannot see through, rather than running it through a shell', () => {
29
+ expect(() => claudeExecutableForSdk('C:\\npm\\claude.cmd', () => false, path.win32)).toThrow(/claude\.cmd/);
30
+ });
31
+ });
32
+
33
+ describe('claudeForSdk', () => {
34
+ it('takes a configured path as it is', () => {
35
+ expect(claudeForSdk('/opt/claude/bin/claude')).toBe('/opt/claude/bin/claude');
36
+ });
37
+ });
38
+
39
+ describe('the Claude Code a conversation runs, when the desktop could not read the terminal’s PATH', () => {
40
+ const saved = { PATH: process.env.PATH, HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE, [PATH_FALLBACK_ENV]: process.env[PATH_FALLBACK_ENV] };
41
+ let home: string | undefined;
42
+ afterEach(() => {
43
+ for (const [name, value] of Object.entries(saved)) {
44
+ if (value === undefined) delete process.env[name];
45
+ else process.env[name] = value;
46
+ }
47
+ if (home) removeDirSync(home);
48
+ });
49
+
50
+ it('is the copy the installer put in place, not an old one in a fallback folder', () => {
51
+ home = mkdtempSync(path.join(tmpdir(), 'moxxy-claude-sdk-'));
52
+ const options = { windowsEntry: CLAUDE_CLI.windowsShim.entry };
53
+ const current = writeFakeCli(path.join(home, '.local', 'bin', 'claude'), '', options);
54
+ const old = writeFakeCli(path.join(home, 'homebrew', 'bin', 'claude'), '', options);
55
+ process.env.HOME = process.env.USERPROFILE = home;
56
+ process.env.PATH = process.env[PATH_FALLBACK_ENV] = path.dirname(old);
57
+
58
+ expect(claudeForSdk('claude')).toBe(claudeExecutableForSdk(current));
59
+ });
60
+ });
@@ -0,0 +1,34 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { CLAUDE_CLI, findAgentCli } from '@moxxy/agent-connection-kit';
4
+
5
+ /**
6
+ * The file the Agent SDK should start for the person's Claude Code. A Windows
7
+ * npm install puts a `.cmd` shim on PATH, which only a shell can run, so the
8
+ * `cli.js` it points at is used instead.
9
+ */
10
+ export function claudeExecutableForSdk(
11
+ found: string,
12
+ exists: (file: string) => boolean = existsSync,
13
+ paths: Pick<typeof path, 'extname' | 'dirname' | 'join'> = path,
14
+ ): string {
15
+ const extension = paths.extname(found).toLowerCase();
16
+ if (extension !== '.cmd' && extension !== '.bat' && extension !== '.ps1') return found;
17
+ const cli = paths.join(paths.dirname(found), 'node_modules', '@anthropic-ai', 'claude-code', 'cli.js');
18
+ if (exists(cli)) return cli;
19
+ throw new Error(`Cannot find the Claude Code cli.js behind ${found}; reinstall Claude Code or point CLAUDE_CODE_EXECUTABLE at the CLI.`);
20
+ }
21
+
22
+ /**
23
+ * The person's Claude Code CLI as an absolute path for the SDK — on PATH, or
24
+ * where Claude's installer puts it — or `undefined` when it is not installed.
25
+ */
26
+ export function resolveClaudeForSdk(command: string): string | undefined {
27
+ const found = findAgentCli(CLAUDE_CLI, { command });
28
+ return found ? claudeExecutableForSdk(found) : undefined;
29
+ }
30
+
31
+ /** The SDK's file for the configured command: a path as given (shim resolved), a bare name looked up. */
32
+ export function claudeForSdk(command: string): string | undefined {
33
+ return command.includes('/') || command.includes('\\') ? claudeExecutableForSdk(command) : resolveClaudeForSdk(command);
34
+ }