@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
package/dist/provider.js DELETED
@@ -1,229 +0,0 @@
1
- import { estimateTextTokens } from '@moxxy/sdk';
2
- import { CLAUDE_CODE_PROVIDER_ID } from './constants.js';
3
- import { ClaudeProcessError, runClaudeProcess } from './process.js';
4
- import { createProtocolState, parseClaudeRecord, serializeClaudePrompt } from './protocol.js';
5
- export const CLAUDE_CODE_DEFAULT_MODEL = 'claude-sonnet-5-5';
6
- const NON_TEXT_BLOCK_TOKENS = 256;
7
- /**
8
- * Models offered by Claude Code subscriptions through the installed CLI.
9
- *
10
- * This is deliberately independent of the Anthropic API catalog: the CLI has
11
- * its own availability policy, and this adapter only preserves streamed text.
12
- * moxxy tools ride a text protocol (see protocol.ts). Unsupported capabilities
13
- * are explicit so every host sees the same contract rather than relying on how
14
- * it interprets absent optional flags.
15
- */
16
- const textOnlyCapabilities = {
17
- supportsTools: true,
18
- supportsStreaming: true,
19
- supportsImages: false,
20
- supportsDocuments: false,
21
- supportsAudio: false,
22
- supportsReasoning: false,
23
- hostedTools: ['web_search'],
24
- };
25
- export const claudeCodeModels = [
26
- { id: 'claude-fable-5-1', contextWindow: 1_000_000, maxOutputTokens: 128_000, ...textOnlyCapabilities },
27
- { id: 'claude-opus-5-5', contextWindow: 1_000_000, maxOutputTokens: 128_000, ...textOnlyCapabilities },
28
- { id: CLAUDE_CODE_DEFAULT_MODEL, contextWindow: 1_000_000, maxOutputTokens: 128_000, ...textOnlyCapabilities },
29
- { id: 'claude-haiku-4-5', contextWindow: 200_000, maxOutputTokens: 64_000, ...textOnlyCapabilities },
30
- ];
31
- export class ClaudeCodeProvider {
32
- name = CLAUDE_CODE_PROVIDER_ID;
33
- models;
34
- executable;
35
- defaultModel;
36
- nativeTools;
37
- webSearch;
38
- permissionMode;
39
- allowedTools;
40
- cwd;
41
- spawn;
42
- startupTimeoutMs;
43
- idleTimeoutMs;
44
- maxStderrChars;
45
- maxRecordChars;
46
- constructor(config = {}) {
47
- this.executable = config.executable ?? 'claude';
48
- this.defaultModel = config.defaultModel ?? CLAUDE_CODE_DEFAULT_MODEL;
49
- this.nativeTools = config.mode === 'native-tools';
50
- // Native-tools mode hands the task to Claude's own tools; moxxy tools are
51
- // only offered through the text transport.
52
- this.models = this.nativeTools
53
- ? claudeCodeModels.map((model) => ({ ...model, supportsTools: false }))
54
- : claudeCodeModels;
55
- this.webSearch = config.webSearch !== false;
56
- if (config.permissionMode)
57
- this.permissionMode = config.permissionMode;
58
- this.allowedTools = config.allowedTools ?? [];
59
- this.cwd = config.cwd ?? process.cwd();
60
- if (config.spawn)
61
- this.spawn = config.spawn;
62
- if (config.startupTimeoutMs)
63
- this.startupTimeoutMs = config.startupTimeoutMs;
64
- if (config.idleTimeoutMs)
65
- this.idleTimeoutMs = config.idleTimeoutMs;
66
- if (config.maxStderrChars)
67
- this.maxStderrChars = config.maxStderrChars;
68
- if (config.maxRecordChars)
69
- this.maxRecordChars = config.maxRecordChars;
70
- }
71
- async *stream(req) {
72
- const model = req.model || this.defaultModel;
73
- yield { type: 'message_start', model };
74
- // Native WebSearch replaces moxxy's web_search fallback when it is enabled.
75
- const tools = this.webSearch
76
- ? req.tools?.filter((tool) => tool.hosted?.type !== 'web_search')
77
- : req.tools;
78
- let prompt;
79
- try {
80
- assertSupportedModel(model);
81
- assertTextOnlyRequest(req, this.nativeTools);
82
- prompt = serializeClaudePrompt({ ...req, ...(tools ? { tools } : {}) });
83
- }
84
- catch (error) {
85
- yield nonRetryableError(error);
86
- return;
87
- }
88
- const state = createProtocolState({ toolCalls: (tools?.length ?? 0) > 0 });
89
- let terminal = false;
90
- let lines;
91
- try {
92
- lines = runClaudeProcess({
93
- executable: this.executable,
94
- model,
95
- prompt,
96
- cwd: this.cwd,
97
- nativeTools: this.nativeTools,
98
- webSearch: this.webSearch,
99
- allowedTools: this.allowedTools,
100
- ...(this.permissionMode ? { permissionMode: this.permissionMode } : {}),
101
- ...(req.signal ? { signal: req.signal } : {}),
102
- ...(this.spawn ? { spawn: this.spawn } : {}),
103
- ...(this.startupTimeoutMs ? { startupTimeoutMs: this.startupTimeoutMs } : {}),
104
- ...(this.idleTimeoutMs ? { idleTimeoutMs: this.idleTimeoutMs } : {}),
105
- ...(this.maxStderrChars ? { maxStderrChars: this.maxStderrChars } : {}),
106
- ...(this.maxRecordChars ? { maxRecordChars: this.maxRecordChars } : {}),
107
- });
108
- while (true) {
109
- const next = await lines.next();
110
- if (next.done) {
111
- if (next.value.exitCode !== 0 && !terminal) {
112
- yield classifyClaudeFailure(model, next.value.stderr || `Claude CLI exited unexpectedly with code ${next.value.exitCode}`);
113
- return;
114
- }
115
- break;
116
- }
117
- for (const event of parseClaudeRecord(next.value, state)) {
118
- if (event.type === 'message_end') {
119
- terminal = true;
120
- yield event;
121
- return;
122
- }
123
- if (event.type === 'error') {
124
- terminal = true;
125
- yield classifyClaudeFailure(model, event.message);
126
- return;
127
- }
128
- yield event;
129
- }
130
- }
131
- if (!terminal) {
132
- yield { type: 'error', message: 'Claude CLI ended without a terminal result record', retryable: false };
133
- }
134
- }
135
- catch (error) {
136
- if (error instanceof ClaudeProcessError) {
137
- yield {
138
- type: 'error',
139
- message: error.message,
140
- retryable: error.failure === 'startup_timeout' || error.failure === 'idle_timeout',
141
- };
142
- }
143
- else {
144
- yield classifySpawnFailure(error, this.executable);
145
- }
146
- }
147
- finally {
148
- await lines?.return({ exitCode: 0, stderr: '' });
149
- }
150
- }
151
- async countTokens(req) {
152
- let text = req.system ?? '';
153
- let nonTextBlocks = 0;
154
- for (const message of req.messages) {
155
- for (const block of message.content) {
156
- if (block.type === 'text')
157
- text += block.text;
158
- else
159
- nonTextBlocks += 1;
160
- }
161
- }
162
- for (const tool of req.tools ?? [])
163
- text += tool.name + tool.description;
164
- return estimateTextTokens(text) + nonTextBlocks * NON_TEXT_BLOCK_TOKENS;
165
- }
166
- }
167
- export function createClaudeCodeClient(config = {}) {
168
- return new ClaudeCodeProvider(config);
169
- }
170
- function assertSupportedModel(model) {
171
- if (claudeCodeModels.some((candidate) => candidate.id === model))
172
- return;
173
- throw new Error(`Claude Code model "${model}" is not supported by this adapter. ` +
174
- `Select a supported model: ${claudeCodeModels.map((candidate) => candidate.id).join(', ')}.`);
175
- }
176
- function assertTextOnlyRequest(req, nativeTools) {
177
- if (nativeTools && req.tools && req.tools.length > 0) {
178
- throw new Error('Claude CLI native-tools transport does not support moxxy tools');
179
- }
180
- if (req.reasoning) {
181
- throw new Error('Claude CLI text transport does not support reasoning');
182
- }
183
- }
184
- function classifyClaudeFailure(model, detail) {
185
- if (/model|unknown model|invalid model/i.test(detail)) {
186
- return {
187
- type: 'error',
188
- message: `Claude Code rejected model "${model}": ${detail}. Select a supported model: ${claudeCodeModels.map((candidate) => candidate.id).join(', ')}.`,
189
- retryable: false,
190
- };
191
- }
192
- if (/not logged in|signed out|login required|authenticate|authentication|unauthorized|invalid.*(?:token|credential)|\b401\b/i.test(detail)) {
193
- return {
194
- type: 'error',
195
- message: `Claude CLI is signed out or its authentication was rejected: ${detail}. Run \`moxxy login claude-code\` to sign in again.`,
196
- retryable: false,
197
- };
198
- }
199
- if (/permission|denied|not allowed|forbidden|\b403\b/i.test(detail)) {
200
- return {
201
- type: 'error',
202
- message: `Claude Code permission denied: ${detail}. Review plugins.provider.items.claude-code.config.permissionMode and allowedTools.`,
203
- retryable: false,
204
- };
205
- }
206
- if (/rate.?limit|too many requests|\b429\b|overload|temporar|unavailable|service error|\b5\d\d\b/i.test(detail)) {
207
- return { type: 'error', message: `Claude Code service failure: ${detail}`, retryable: true };
208
- }
209
- return { type: 'error', message: `Claude CLI failed: ${detail}`, retryable: false };
210
- }
211
- function classifySpawnFailure(error, executable) {
212
- const nodeError = error;
213
- if (nodeError?.code === 'ENOENT') {
214
- return {
215
- type: 'error',
216
- message: `Claude CLI executable not found: ${executable}. Install it with \`npm install -g @anthropic-ai/claude-code\` or configure plugins.provider.items.claude-code.config.executable.`,
217
- retryable: false,
218
- };
219
- }
220
- return nonRetryableError(error);
221
- }
222
- function nonRetryableError(error) {
223
- return {
224
- type: 'error',
225
- message: error instanceof Error ? error.message : String(error),
226
- retryable: false,
227
- };
228
- }
229
- //# sourceMappingURL=provider.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"provider.js","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,kBAAkB,EAAE,gBAAgB,EAAoB,MAAM,cAAc,CAAC;AACtF,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAE9F,MAAM,CAAC,MAAM,yBAAyB,GAAG,mBAAmB,CAAC;AAC7D,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAElC;;;;;;;;GAQG;AACH,MAAM,o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KAAK;SACjB,CAAC;IACJ,CAAC;IACD,OAAO,iBAAiB,CAAC,KAAK,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,iBAAiB,CAAC,KAAc;IACvC,OAAO;QACL,IAAI,EAAE,OAAO;QACb,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;QAC/D,SAAS,EAAE,KAAK;KACjB,CAAC;AACJ,CAAC"}
@@ -1,208 +0,0 @@
1
- import { EventEmitter } from 'node:events';
2
- import { PassThrough } from 'node:stream';
3
- import type { ChildProcessWithoutNullStreams } from 'node:child_process';
4
- import { afterEach, describe, expect, it, vi } from 'vitest';
5
- import { ClaudeProcessError, runClaudeProcess, type ClaudeProcessOptions, type ClaudeSpawnOptions } from './process.js';
6
-
7
- class ControlledChild extends EventEmitter {
8
- readonly stdin = new PassThrough();
9
- readonly stdout = new PassThrough();
10
- readonly stderr = new PassThrough();
11
- readonly stdio = [this.stdin, this.stdout, this.stderr] as const;
12
- exitCode: number | null = null;
13
- signalCode: NodeJS.Signals | null = null;
14
- readonly kills: NodeJS.Signals[] = [];
15
-
16
- constructor(private readonly closeOn: NodeJS.Signals | undefined = 'SIGTERM') {
17
- super();
18
- }
19
-
20
- kill(signal: NodeJS.Signals = 'SIGTERM'): boolean {
21
- this.kills.push(signal);
22
- if (signal === this.closeOn) this.close(null, signal);
23
- return true;
24
- }
25
-
26
- close(code: number | null = 0, signal: NodeJS.Signals | null = null): void {
27
- if (this.exitCode !== null || this.signalCode !== null) return;
28
- this.exitCode = code;
29
- this.signalCode = signal;
30
- this.emit('close', code, signal);
31
- }
32
-
33
- asChild(): ChildProcessWithoutNullStreams {
34
- return this as unknown as ChildProcessWithoutNullStreams;
35
- }
36
- }
37
-
38
- const baseOptions: ClaudeProcessOptions = {
39
- executable: 'claude',
40
- model: 'claude-sonnet-5-5',
41
- prompt: 'hello',
42
- cwd: '/tmp',
43
- nativeTools: false,
44
- allowedTools: [],
45
- };
46
-
47
- function processWith(child: ControlledChild, overrides: Partial<ClaudeProcessOptions> = {}) {
48
- return runClaudeProcess({ ...baseOptions, ...overrides, spawn: () => child.asChild() });
49
- }
50
-
51
- async function rejection(promise: Promise<unknown>): Promise<Error> {
52
- try {
53
- await promise;
54
- throw new Error('expected rejection');
55
- } catch (error) {
56
- return error as Error;
57
- }
58
- }
59
-
60
- async function flush(): Promise<void> {
61
- await Promise.resolve();
62
- await Promise.resolve();
63
- }
64
-
65
- afterEach(() => {
66
- vi.useRealTimers();
67
- });
68
-
69
- describe('runClaudeProcess lifecycle', () => {
70
- it('removes nested Claude environment markers without mutating the parent environment', async () => {
71
- const child = new ControlledChild();
72
- let spawnOptions: ClaudeSpawnOptions | undefined;
73
- const oldClaudeCode = process.env.CLAUDECODE;
74
- const oldEntrypoint = process.env.CLAUDE_CODE_ENTRYPOINT;
75
- process.env.CLAUDECODE = '1';
76
- process.env.CLAUDE_CODE_ENTRYPOINT = 'cli';
77
- try {
78
- const lines = runClaudeProcess({
79
- ...baseOptions,
80
- spawn: (_file, _args, options) => {
81
- spawnOptions = options;
82
- return child.asChild();
83
- },
84
- });
85
- const pending = lines.next();
86
- child.close(0);
87
- await pending;
88
- expect(spawnOptions?.env.CLAUDECODE).toBeUndefined();
89
- expect(spawnOptions?.env.CLAUDE_CODE_ENTRYPOINT).toBeUndefined();
90
- expect(process.env.CLAUDECODE).toBe('1');
91
- expect(process.env.CLAUDE_CODE_ENTRYPOINT).toBe('cli');
92
- } finally {
93
- if (oldClaudeCode === undefined) delete process.env.CLAUDECODE;
94
- else process.env.CLAUDECODE = oldClaudeCode;
95
- if (oldEntrypoint === undefined) delete process.env.CLAUDE_CODE_ENTRYPOINT;
96
- else process.env.CLAUDE_CODE_ENTRYPOINT = oldEntrypoint;
97
- }
98
- });
99
-
100
- it('cancels promptly with one abort error and leaves no timer or child alive', async () => {
101
- vi.useFakeTimers();
102
- const child = new ControlledChild();
103
- const controller = new AbortController();
104
- const lines = processWith(child, { signal: controller.signal });
105
- const pending = lines.next();
106
- controller.abort();
107
- const error = await rejection(pending);
108
- expect(error).toMatchObject({ failure: 'aborted' });
109
- expect(child.kills).toEqual(['SIGTERM']);
110
- expect(vi.getTimerCount()).toBe(0);
111
- expect(await lines.next()).toEqual({ done: true, value: undefined });
112
- });
113
-
114
- it('times out startup and clears all lifecycle timers', async () => {
115
- vi.useFakeTimers();
116
- const child = new ControlledChild();
117
- const errorPromise = rejection(processWith(child, { startupTimeoutMs: 50 }).next());
118
- await vi.advanceTimersByTimeAsync(50);
119
- const error = await errorPromise;
120
- expect(error).toMatchObject({ failure: 'startup_timeout' });
121
- expect(child.kills).toEqual(['SIGTERM']);
122
- expect(vi.getTimerCount()).toBe(0);
123
- });
124
-
125
- it('resets the idle timeout on every non-empty record', async () => {
126
- vi.useFakeTimers();
127
- const child = new ControlledChild();
128
- const lines = processWith(child, { startupTimeoutMs: 100, idleTimeoutMs: 100 });
129
- const first = lines.next();
130
- await vi.advanceTimersByTimeAsync(90);
131
- child.stdout.write('{"type":"system"}\n');
132
- expect(await first).toMatchObject({ done: false });
133
-
134
- const second = lines.next();
135
- await vi.advanceTimersByTimeAsync(90);
136
- child.stdout.write('{"type":"system"}\n');
137
- expect(await second).toMatchObject({ done: false });
138
-
139
- const timedOut = rejection(lines.next());
140
- await vi.advanceTimersByTimeAsync(101);
141
- expect(await timedOut).toMatchObject({ failure: 'idle_timeout' });
142
- expect(child.kills).toEqual(['SIGTERM']);
143
- expect(vi.getTimerCount()).toBe(0);
144
- });
145
-
146
- it('caps stderr and accepts a final unterminated record within the cap', async () => {
147
- const child = new ControlledChild();
148
- const lines = processWith(child, { maxStderrChars: 5, maxRecordChars: 20 });
149
- const first = lines.next();
150
- child.stderr.write('abcdefgh');
151
- child.stdout.write('{"ok":true}');
152
- child.close(7);
153
- expect(await first).toEqual({ done: false, value: '{"ok":true}' });
154
- expect(await lines.next()).toEqual({ done: true, value: { exitCode: 7, stderr: 'abcde' } });
155
- });
156
-
157
- it('rejects an oversized unterminated record as a protocol failure', async () => {
158
- vi.useFakeTimers();
159
- const child = new ControlledChild();
160
- const lines = processWith(child, { maxRecordChars: 5 });
161
- const pending = lines.next();
162
- child.stdout.write('123456');
163
- expect(await rejection(pending)).toMatchObject({ failure: 'protocol' });
164
- expect(child.kills).toEqual(['SIGTERM']);
165
- expect(vi.getTimerCount()).toBe(0);
166
- });
167
-
168
- it('escalates SIGTERM to SIGKILL once even when cleanup requests termination again', async () => {
169
- vi.useFakeTimers();
170
- const child = new ControlledChild('SIGKILL');
171
- const controller = new AbortController();
172
- const errorPromise = rejection(processWith(child, { signal: controller.signal }).next());
173
- controller.abort();
174
- await flush();
175
- expect(child.kills).toEqual(['SIGTERM']);
176
- await vi.advanceTimersByTimeAsync(1_000);
177
- expect(await errorPromise).toMatchObject({ failure: 'aborted' });
178
- expect(child.kills).toEqual(['SIGTERM', 'SIGKILL']);
179
- expect(vi.getTimerCount()).toBe(0);
180
- });
181
-
182
- it('terminates immediately when the consumer returns early', async () => {
183
- vi.useFakeTimers();
184
- const child = new ControlledChild();
185
- const lines = processWith(child);
186
- const first = lines.next();
187
- child.stdout.write('record\n');
188
- expect(await first).toEqual({ done: false, value: 'record' });
189
- await lines.return({ exitCode: 0, stderr: '' });
190
- expect(child.kills).toEqual(['SIGTERM']);
191
- expect(vi.getTimerCount()).toBe(0);
192
- });
193
-
194
- it('leaves no child or timer after normal completion', async () => {
195
- vi.useFakeTimers();
196
- const child = new ControlledChild();
197
- const lines = processWith(child);
198
- const pending = lines.next();
199
- child.close(0);
200
- expect(await pending).toEqual({ done: true, value: { exitCode: 0, stderr: '' } });
201
- expect(child.kills).toEqual([]);
202
- expect(vi.getTimerCount()).toBe(0);
203
- });
204
-
205
- it('preserves the typed process error identity', () => {
206
- expect(new ClaudeProcessError('protocol', 'bad')).toBeInstanceOf(Error);
207
- });
208
- });
package/src/process.ts DELETED
@@ -1,224 +0,0 @@
1
- import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
2
-
3
- export interface ClaudeSpawnOptions {
4
- readonly env: NodeJS.ProcessEnv;
5
- readonly cwd: string;
6
- }
7
-
8
- export type ClaudeSpawn = (
9
- executable: string,
10
- args: ReadonlyArray<string>,
11
- options: ClaudeSpawnOptions,
12
- ) => ChildProcessWithoutNullStreams;
13
-
14
- export type ClaudeProcessFailure = 'aborted' | 'startup_timeout' | 'idle_timeout' | 'protocol';
15
-
16
- export class ClaudeProcessError extends Error {
17
- constructor(readonly failure: ClaudeProcessFailure, message: string) {
18
- super(message);
19
- this.name = 'ClaudeProcessError';
20
- }
21
- }
22
-
23
- export interface ClaudeProcessOptions {
24
- readonly executable: string;
25
- readonly model: string;
26
- readonly prompt: string;
27
- readonly cwd: string;
28
- readonly nativeTools: boolean;
29
- /** Enable only Claude Code's native WebSearch when nativeTools is false. */
30
- readonly webSearch?: boolean;
31
- readonly permissionMode?: string;
32
- readonly allowedTools: ReadonlyArray<string>;
33
- readonly signal?: AbortSignal;
34
- readonly spawn?: ClaudeSpawn;
35
- readonly startupTimeoutMs?: number;
36
- readonly idleTimeoutMs?: number;
37
- readonly maxStderrChars?: number;
38
- readonly maxRecordChars?: number;
39
- }
40
-
41
- export interface ClaudeProcessResult {
42
- readonly exitCode: number;
43
- readonly stderr: string;
44
- }
45
-
46
- const DEFAULT_STARTUP_TIMEOUT_MS = 30_000;
47
- const DEFAULT_IDLE_TIMEOUT_MS = 120_000;
48
- const DEFAULT_MAX_STDERR_CHARS = 2048;
49
- const DEFAULT_MAX_RECORD_CHARS = 64 * 1024;
50
- const KILL_GRACE_MS = 1_000;
51
-
52
- type QueueItem = { readonly line: string } | { readonly error: Error } | { readonly done: true };
53
-
54
- export async function* runClaudeProcess(
55
- options: ClaudeProcessOptions,
56
- ): AsyncGenerator<string, ClaudeProcessResult> {
57
- const args = buildArgs(options);
58
- const env = { ...process.env };
59
- // Claude refuses nested interactive sessions. Moxxy is the parent here, not a
60
- // nested Claude Code instance, even when it was launched from Claude Code.
61
- delete env.CLAUDECODE;
62
- delete env.CLAUDE_CODE_ENTRYPOINT;
63
- const spawnImpl = options.spawn ?? ((file, childArgs, childOptions) => spawn(file, [...childArgs], {
64
- stdio: ['pipe', 'pipe', 'pipe'], env: childOptions.env, cwd: childOptions.cwd,
65
- }));
66
-
67
- const child = spawnImpl(options.executable, args, { env, cwd: options.cwd });
68
-
69
- const queue: QueueItem[] = [];
70
- let wake: (() => void) | undefined;
71
- let stdout = '';
72
- let stderr = '';
73
- let closed = false;
74
- let failure: Error | undefined;
75
- let timer: ReturnType<typeof setTimeout> | undefined;
76
- let killTimer: ReturnType<typeof setTimeout> | undefined;
77
- let terminationRequested = false;
78
- const startupTimeoutMs = positive(options.startupTimeoutMs, DEFAULT_STARTUP_TIMEOUT_MS);
79
- const idleTimeoutMs = positive(options.idleTimeoutMs, DEFAULT_IDLE_TIMEOUT_MS);
80
- const maxStderrChars = positive(options.maxStderrChars, DEFAULT_MAX_STDERR_CHARS);
81
- const maxRecordChars = positive(options.maxRecordChars, DEFAULT_MAX_RECORD_CHARS);
82
-
83
- const push = (item: QueueItem): void => {
84
- queue.push(item);
85
- const notify = wake;
86
- wake = undefined;
87
- notify?.();
88
- };
89
- const clearWatchdog = (): void => {
90
- if (timer) clearTimeout(timer);
91
- timer = undefined;
92
- };
93
- const terminate = (): void => {
94
- if (closed || child.exitCode !== null || child.signalCode !== null || terminationRequested) return;
95
- terminationRequested = true;
96
- child.kill('SIGTERM');
97
- killTimer = setTimeout(() => {
98
- killTimer = undefined;
99
- if (!closed && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
100
- }, KILL_GRACE_MS);
101
- killTimer.unref?.();
102
- };
103
- const fail = (error: Error): void => {
104
- if (failure) return;
105
- failure = error;
106
- clearWatchdog();
107
- terminate();
108
- // Cancellation/failure is terminal: discard records received but not yet
109
- // consumed so no text can be emitted after the single error event.
110
- queue.length = 0;
111
- push({ error });
112
- };
113
- const arm = (kind: 'startup' | 'idle'): void => {
114
- clearWatchdog();
115
- const delay = kind === 'startup' ? startupTimeoutMs : idleTimeoutMs;
116
- timer = setTimeout(() => fail(new ClaudeProcessError(
117
- kind === 'startup' ? 'startup_timeout' : 'idle_timeout',
118
- kind === 'startup'
119
- ? `Claude CLI did not produce a stream record within ${delay}ms`
120
- : `Claude CLI stream was idle for ${delay}ms`,
121
- )), delay);
122
- timer.unref?.();
123
- };
124
- const onAbort = (): void => fail(new ClaudeProcessError('aborted', 'Claude CLI request aborted'));
125
-
126
- child.stdin.on('error', (error) => {
127
- // EPIPE commonly follows cancellation; the abort error is the useful one.
128
- if (!failure) fail(error);
129
- });
130
- child.stderr.setEncoding('utf8');
131
- child.stderr.on('data', (chunk: string) => {
132
- if (stderr.length < maxStderrChars) stderr += chunk.slice(0, maxStderrChars - stderr.length);
133
- });
134
- child.stdout.setEncoding('utf8');
135
- child.stdout.on('data', (chunk: string) => {
136
- if (failure) return;
137
- stdout += chunk;
138
- if (stdout.length > maxRecordChars && !stdout.includes('\n')) {
139
- fail(new ClaudeProcessError('protocol', `Claude CLI emitted a stream record larger than ${maxRecordChars} characters`));
140
- return;
141
- }
142
- let newline = stdout.indexOf('\n');
143
- while (newline >= 0 && !failure) {
144
- const line = stdout.slice(0, newline).replace(/\r$/, '');
145
- stdout = stdout.slice(newline + 1);
146
- if (line.length > maxRecordChars) {
147
- fail(new ClaudeProcessError('protocol', `Claude CLI emitted a stream record larger than ${maxRecordChars} characters`));
148
- return;
149
- }
150
- if (line.trim()) {
151
- arm('idle');
152
- push({ line });
153
- }
154
- newline = stdout.indexOf('\n');
155
- }
156
- if (stdout.length > maxRecordChars) {
157
- fail(new ClaudeProcessError('protocol', `Claude CLI emitted a stream record larger than ${maxRecordChars} characters`));
158
- }
159
- });
160
-
161
- const completion = new Promise<number>((resolve) => {
162
- child.once('error', (error) => {
163
- fail(error);
164
- });
165
- child.once('close', (code) => {
166
- closed = true;
167
- clearWatchdog();
168
- if (killTimer) clearTimeout(killTimer);
169
- killTimer = undefined;
170
- if (!failure && stdout.trim()) {
171
- if (stdout.length > maxRecordChars) {
172
- fail(new ClaudeProcessError('protocol', `Claude CLI emitted a stream record larger than ${maxRecordChars} characters`));
173
- } else {
174
- // A final JSON record need not end in a newline.
175
- push({ line: stdout.replace(/\r$/, '') });
176
- }
177
- }
178
- push({ done: true });
179
- resolve(code ?? 1);
180
- });
181
- });
182
-
183
- options.signal?.addEventListener('abort', onAbort, { once: true });
184
- if (options.signal?.aborted) onAbort();
185
- else arm('startup');
186
- if (!failure) child.stdin.end(options.prompt, 'utf8');
187
-
188
- try {
189
- while (true) {
190
- if (queue.length === 0) await new Promise<void>((resolve) => { wake = resolve; });
191
- const item = queue.shift();
192
- if (!item) continue;
193
- if ('error' in item) throw item.error;
194
- if ('done' in item) break;
195
- yield item.line;
196
- }
197
- const exitCode = await completion;
198
- return { exitCode, stderr: stderr.trim() };
199
- } finally {
200
- clearWatchdog();
201
- options.signal?.removeEventListener('abort', onAbort);
202
- terminate();
203
- try { await completion; } catch { /* surfaced through the queue */ }
204
- if (killTimer) clearTimeout(killTimer);
205
- }
206
- }
207
-
208
- function buildArgs(options: ClaudeProcessOptions): string[] {
209
- const args = ['--print', '--verbose', '--output-format', 'stream-json', '--include-partial-messages', '--model', options.model];
210
- if (options.nativeTools) {
211
- args.push('--tools', ...(options.allowedTools.length > 0 ? options.allowedTools : ['']));
212
- if (options.permissionMode) args.push('--permission-mode', options.permissionMode);
213
- if (options.allowedTools.length > 0) args.push('--allowedTools', ...options.allowedTools);
214
- } else if (options.webSearch) {
215
- args.splice(args.length - 2, 0, '--tools', 'WebSearch', '--allowedTools', 'WebSearch');
216
- } else {
217
- args.splice(args.length - 2, 0, '--tools', '');
218
- }
219
- return args;
220
- }
221
-
222
- function positive(value: number | undefined, fallback: number): number {
223
- return value !== undefined && value > 0 ? value : fallback;
224
- }