@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,1176 @@
1
+ /**
2
+ * The Claude agent connection, end to end: a real Moxxy session and loop drive
3
+ * `agentStep`, and Claude itself is the stand-in at the Agent SDK boundary
4
+ * (fake-claude.testkit.ts). Nothing between them is replaced.
5
+ */
6
+ import { afterEach, describe, expect, it, vi } from 'vitest';
7
+ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
8
+ import { removeDirSync } from '@moxxy/vitest-preset/fs';
9
+ import { tmpdir } from 'node:os';
10
+ import { dirname, join } from 'node:path';
11
+ import { z } from 'zod/v3';
12
+ import {
13
+ AGENT_CONNECTION_PLUGIN_ID,
14
+ AGENT_GOAL_SUBTYPE,
15
+ QUESTION_ASKED,
16
+ assertDefined,
17
+ autoApproveFromEvents,
18
+ definePlugin,
19
+ defineProvider,
20
+ defineTool,
21
+ type MoxxyEvent,
22
+ type PermissionResolver,
23
+ type QuestionItem,
24
+ type Skill,
25
+ type ToolDef,
26
+ } from '@moxxy/sdk';
27
+ import { buildSynthesizeSkillPlugin, collectTurn, type Session } from '@moxxy/core';
28
+ import { FakeProvider, addFakeProvider, createFakeSession, textReply } from '@moxxy/testing';
29
+ import { defaultModePlugin } from '@moxxy/mode-default';
30
+ import { planModePlugin } from '@moxxy/mode-plan';
31
+ import { goalModePlugin } from '@moxxy/mode-goal';
32
+ import { AgentSessionPool } from '@moxxy/agent-connection-kit';
33
+ import { CLAUDE_CODE_STARTER_MODEL, ClaudeAgentProvider } from './agent-provider.js';
34
+ import type { ClaudeMessage } from './sdk-types.js';
35
+ import { ClaudeAgentSession, toolsLentToClaude } from './agent-session.js';
36
+ import { FakeClaude, assistantText, assistantToolUse, toolResult, type ClaudeScene, type FakeTurn } from './fake-claude.testkit.js';
37
+
38
+ const sessions: Session[] = [];
39
+ const pools: AgentSessionPool<ClaudeAgentSession>[] = [];
40
+ afterEach(async () => {
41
+ await Promise.all(pools.splice(0).map((pool) => pool.closeAll()));
42
+ await Promise.all(sessions.splice(0).map((session) => session.close()));
43
+ });
44
+
45
+ function connect(scene: ClaudeScene, opts: { claude?: FakeClaude; pool?: AgentSessionPool<ClaudeAgentSession> } = {}) {
46
+ const claude = opts.claude ?? new FakeClaude(scene);
47
+ const pool = opts.pool ?? new AgentSessionPool<ClaudeAgentSession>({ limit: 4 });
48
+ pools.push(pool);
49
+ const provider = new ClaudeAgentProvider({
50
+ executable: '/Users/me/.local/bin/claude',
51
+ defaultModel: 'claude-opus-5-5',
52
+ loadSdk: async () => claude,
53
+ sessions: pool,
54
+ });
55
+ const session = createFakeSession({ provider });
56
+ sessions.push(session);
57
+ session.pluginHost.registerStatic(defaultModePlugin);
58
+ return { claude, session, provider, pool };
59
+ }
60
+
61
+ const said = (events: ReadonlyArray<MoxxyEvent>) =>
62
+ events.flatMap((e) => (e.type === 'assistant_message' && e.source === 'model' ? [e.content] : []));
63
+ const denyAll: PermissionResolver = { name: 'deny-all', check: async () => ({ mode: 'deny', reason: 'the person said no' }) };
64
+ const allowAll: PermissionResolver = { name: 'allow-all', check: async () => ({ mode: 'allow' }) };
65
+
66
+ describe('a turn on the Claude agent connection', () => {
67
+ it('hands the person message to Claude Code, unchanged, and shows what Claude did', async () => {
68
+ const { claude, session } = connect(async function* (turn) {
69
+ yield assistantToolUse('toolu_1', 'Bash', { command: 'echo spike-ok' });
70
+ yield toolResult('toolu_1', 'spike-ok');
71
+ yield assistantText(`You said: ${turn.text}`);
72
+ });
73
+
74
+ const events = await collectTurn(session, 'Run echo spike-ok');
75
+
76
+ const { options, received } = claude.last;
77
+ expect(options.systemPrompt).toEqual({ type: 'preset', preset: 'claude_code' });
78
+ expect(options.pathToClaudeCodeExecutable).toBe('/Users/me/.local/bin/claude');
79
+ // The model is the conversation's choice (a fresh one starts on the light starter model).
80
+ expect(options.model).toBe(CLAUDE_CODE_STARTER_MODEL);
81
+ expect(options.includePartialMessages).toBe(true);
82
+ expect(options.mcpServers?.moxxy?.url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/mcp$/);
83
+ expect(received[0]).toMatchObject({ message: { role: 'user', content: [{ type: 'text', text: 'Run echo spike-ok' }] }, origin: { kind: 'human' } });
84
+ expect(events).toContainEqual(expect.objectContaining({ type: 'tool_call_requested', callId: 'toolu_1', name: 'Bash', executedBy: 'provider' }));
85
+ expect(events).toContainEqual(expect.objectContaining({ type: 'tool_result', callId: 'toolu_1', ok: true, output: 'spike-ok' }));
86
+ expect(said(events)).toEqual(['You said: Run echo spike-ok']);
87
+ expect(events).toContainEqual(expect.objectContaining({ type: 'provider_response', inputTokens: 3, outputTokens: 7 }));
88
+ });
89
+
90
+ it('records a sentence Claude says before a call as part of the work, and only its last words as the end of the turn', async () => {
91
+ const { session } = connect(async function* () {
92
+ yield assistantText('Building it.');
93
+ yield assistantToolUse('toolu_1', 'Bash', { command: 'echo ok' });
94
+ yield toolResult('toolu_1', 'ok');
95
+ yield assistantText('Built.');
96
+ });
97
+
98
+ const events = await collectTurn(session, 'Build it');
99
+
100
+ const replies = events.flatMap((e) => (e.type === 'assistant_message' && e.source === 'model' ? [[e.content, e.stopReason]] : []));
101
+ expect(replies).toEqual([
102
+ ['Building it.', 'tool_use'],
103
+ ['Built.', 'end_turn'],
104
+ ]);
105
+ const sentence = events.findIndex((e) => e.type === 'assistant_message' && e.content === 'Building it.');
106
+ const call = events.findIndex((e) => e.type === 'tool_call_requested');
107
+ expect(sentence).toBeLessThan(call);
108
+ });
109
+
110
+ it('keeps the same Claude running for the next message of the conversation', async () => {
111
+ const { claude, session } = connect(async function* (turn) {
112
+ yield assistantText(turn.text === 'first' ? 'one' : 'two');
113
+ });
114
+
115
+ await collectTurn(session, 'first');
116
+ const second = await collectTurn(session, 'second');
117
+
118
+ expect(claude.queries).toHaveLength(1);
119
+ expect(claude.last.received).toHaveLength(2);
120
+ expect(said(second)).toEqual(['two']);
121
+ });
122
+
123
+ it('resumes Claude own session when its process was closed and the conversation goes on', async () => {
124
+ const { claude, session, pool } = connect(async function* () {
125
+ yield assistantText('ok');
126
+ });
127
+ await collectTurn(session, 'remember MARMOT-55');
128
+ await pool.close(String(session.id));
129
+
130
+ await collectTurn(session, 'which word?');
131
+
132
+ expect(claude.queries).toHaveLength(2);
133
+ expect(claude.queries[0]?.closed).toBe(true);
134
+ expect(claude.last.options.resume).toBe('claude-session-1');
135
+ });
136
+
137
+ it('goes on in a new Claude session, with the conversation so far, when Claude no longer has its own', async () => {
138
+ const { claude, session, pool } = connect(async function* (turn) {
139
+ yield assistantText(turn.text.includes('which port?') ? '5433' : 'port 5433 it is');
140
+ });
141
+ await collectTurn(session, 'use port 5433');
142
+ await pool.close(String(session.id));
143
+ claude.saved.clear();
144
+
145
+ const events = await collectTurn(session, 'which port?');
146
+ await collectTurn(session, 'thanks');
147
+
148
+ expect(claude.last.options.resume).toBeUndefined();
149
+ // The record goes first, in a message of its own, so Claude cannot take the person's message for part of it.
150
+ const [record, asked, second] = claude.last.received.map((m) => m.message.content);
151
+ expect(String(record)).toMatch(/^Your earlier session for this Moxxy conversation no longer exists/);
152
+ expect(String(record)).toContain('### Turn 1\nPerson: use port 5433\nAgent: port 5433 it is');
153
+ expect(String(record)).toMatch(/Reply with OK only: the person's message follows next\.$/);
154
+ expect(asked).toEqual([{ type: 'text', text: 'which port?' }]);
155
+ expect(second).toEqual([{ type: 'text', text: 'thanks' }]);
156
+ expect(said(events)).toEqual(['5433']);
157
+ expect(events).toContainEqual(expect.objectContaining({ type: 'plugin_event', subtype: 'agent_session', payload: { provider: 'claude-code', sessionId: 'claude-session-2' } }));
158
+ });
159
+
160
+ it('hears, when the person comes back to it, what the conversation did on another connection meanwhile', async () => {
161
+ const { claude, session } = connect(async function* () {
162
+ yield assistantText('ok');
163
+ });
164
+ addFakeProvider(session, new FakeProvider({ name: 'stand-in', script: [textReply('Renamed it to orders.')] }));
165
+
166
+ await collectTurn(session, 'use port 5433');
167
+ session.providers.setActive('stand-in');
168
+ await collectTurn(session, 'rename the table to orders');
169
+ session.providers.setActive('claude-code');
170
+ await collectTurn(session, 'what did you rename?');
171
+ await collectTurn(session, 'thanks');
172
+
173
+ expect(claude.queries).toHaveLength(1);
174
+ const [, missed, back, after] = claude.last.received.map((m) => m.message.content);
175
+ expect(String(missed)).toMatch(/another connection/);
176
+ expect(String(missed)).toContain('### Turn 2\nPerson: rename the table to orders\nAgent: Renamed it to orders.');
177
+ expect(String(missed)).not.toContain('use port 5433');
178
+ expect(String(missed)).toMatch(/Reply with OK only: the person's message follows next\.$/);
179
+ expect(back).toEqual([{ type: 'text', text: 'what did you rename?' }]);
180
+ expect(after).toEqual([{ type: 'text', text: 'thanks' }]);
181
+ });
182
+
183
+ it('hands the conversation so far over before a goal, since /goal must start its own message', async () => {
184
+ const { claude, session, pool } = connect(async function* (turn) {
185
+ if (turn.text === '/goal') {
186
+ yield assistantText('Goal active: the site is deployed', '<synthetic>');
187
+ return;
188
+ }
189
+ yield assistantText('ok');
190
+ });
191
+ await collectTurn(session, 'use port 5433');
192
+ await pool.close(String(session.id));
193
+ claude.saved.clear();
194
+ session.pluginHost.registerStatic(goalModePlugin);
195
+ session.modes.setActive('goal');
196
+
197
+ await collectTurn(session, 'the site is deployed');
198
+
199
+ const sent = claude.last.received.map((m) => m.message.content);
200
+ expect(String(sent[0])).toMatch(/^Your earlier session[\s\S]*use port 5433[\s\S]*Reply with OK only/);
201
+ expect(sent.slice(1)).toEqual([[{ type: 'text', text: '/goal the site is deployed' }], '/goal']);
202
+ });
203
+ });
204
+
205
+ describe('approvals', () => {
206
+ it('asks the person before Claude runs a tool, and tells Claude why it may not', async () => {
207
+ let answer: unknown;
208
+ const { session } = connect(async function* (turn) {
209
+ yield assistantToolUse('toolu_2', 'Bash', { command: 'touch spike.txt' });
210
+ answer = await turn.canUseTool('Bash', { command: 'touch spike.txt' }, 'toolu_2');
211
+ yield toolResult('toolu_2', 'The user refused this command.', true);
212
+ yield assistantText('I could not create it.');
213
+ });
214
+ session.setPermissionResolver(denyAll);
215
+
216
+ const events = await collectTurn(session, 'create spike.txt');
217
+
218
+ expect(answer).toEqual({ behavior: 'deny', message: 'the person said no' });
219
+ const order = events.filter((e) => 'callId' in e && e.callId === 'toolu_2').map((e) => e.type);
220
+ expect(order).toEqual(['tool_call_requested', 'tool_call_denied', 'tool_result']);
221
+ });
222
+
223
+ it('lets Claude go ahead when the person allows', async () => {
224
+ let answer: unknown;
225
+ const { session } = connect(async function* (turn) {
226
+ answer = await turn.canUseTool('Edit', { file_path: 'math.js' }, 'toolu_3');
227
+ yield assistantText('Edited.');
228
+ });
229
+ session.setPermissionResolver(allowAll);
230
+
231
+ await collectTurn(session, 'fix math.js');
232
+
233
+ expect(answer).toEqual({ behavior: 'allow', updatedInput: { file_path: 'math.js' } });
234
+ });
235
+
236
+ it('checks Moxxy rules before every call Claude makes, without asking the person', async () => {
237
+ let verdict: unknown;
238
+ const { session } = connect(async function* (turn) {
239
+ yield assistantToolUse('toolu_4', 'Bash', { command: 'echo forbidden-word' });
240
+ verdict = await turn.preToolUse('Bash', { command: 'echo forbidden-word' }, 'toolu_4');
241
+ yield toolResult('toolu_4', 'PreToolUse:Bash hook error: blocked by a Moxxy rule', true);
242
+ });
243
+ session.pluginHost.registerStatic(
244
+ definePlugin({
245
+ name: '@moxxy/test-rule',
246
+ hooks: { onToolCall: ({ call }) => (JSON.stringify(call.input).includes('forbidden') ? { action: 'deny', reason: 'blocked by a Moxxy rule' } : undefined) },
247
+ }),
248
+ );
249
+
250
+ await collectTurn(session, 'say forbidden-word');
251
+
252
+ expect(verdict).toEqual({
253
+ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'blocked by a Moxxy rule' },
254
+ });
255
+ });
256
+
257
+ it("shows a subagent's calls under the subagent only, also when Moxxy checks them before the subagent's message arrives", async () => {
258
+ const { session } = connect(async function* (turn) {
259
+ yield assistantToolUse('toolu_agent', 'Agent', { description: 'Look around', prompt: 'list files', subagent_type: 'Explore' });
260
+ await turn.preToolUse('Bash', { command: 'ls' }, 'toolu_sub1', 'a1');
261
+ await turn.canUseTool('Edit', { file_path: 'a.txt' }, 'toolu_sub2', { agentID: 'a1' });
262
+ yield {
263
+ type: 'assistant',
264
+ message: { content: [{ type: 'tool_use', id: 'toolu_sub1', name: 'Bash', input: { command: 'ls' } }] },
265
+ parent_tool_use_id: 'toolu_agent',
266
+ } as ClaudeMessage;
267
+ yield assistantText('Done.');
268
+ });
269
+ session.setPermissionResolver(allowAll);
270
+
271
+ const events = await collectTurn(session, 'look around with a helper');
272
+
273
+ expect(events.filter((e) => e.type === 'tool_call_requested')).toEqual([]);
274
+ expect(events.filter((e) => e.type === 'plugin_event').map((e) => e.subtype)).toEqual(
275
+ expect.arrayContaining(['subagent_started', 'subagent_tool_call']),
276
+ );
277
+ });
278
+
279
+ it('takes Claude real permission mode as the conversation auto-approve, and changes Claude when the person does', async () => {
280
+ const { claude, session } = connect(async function* () {
281
+ yield assistantText('ok');
282
+ });
283
+ session.setPermissionResolver(allowAll);
284
+
285
+ await collectTurn(session, 'first');
286
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(false);
287
+ await session.setAutoApprove(true);
288
+ await collectTurn(session, 'second');
289
+
290
+ expect(claude.last.modeChanges).toEqual(['bypassPermissions']);
291
+ expect(claude.last.options.allowDangerouslySkipPermissions).toBe(true);
292
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(true);
293
+ });
294
+
295
+ it('shows auto-approve off when Claude leaves bypass permissions without Moxxy asking, and leaves it so', async () => {
296
+ const { claude, session } = connect(async function* () {
297
+ yield assistantText('ok');
298
+ });
299
+ session.setPermissionResolver(allowAll);
300
+ await collectTurn(session, 'first');
301
+ await session.setAutoApprove(true);
302
+ await collectTurn(session, 'second');
303
+
304
+ claude.last.changeModeElsewhere('default');
305
+ const events = await collectTurn(session, 'third');
306
+
307
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(false);
308
+ expect(claude.last.modeChanges).toEqual(['bypassPermissions']);
309
+ expect(claude.last.permissionMode).toBe('default');
310
+ expect(events).toContainEqual(expect.objectContaining({ type: 'plugin_event', subtype: 'auto_approve', payload: { enabled: false, elsewhere: true } }));
311
+ });
312
+
313
+ it('sets Claude back to asking when its mode is switched to bypass permissions outside Moxxy between turns', async () => {
314
+ const { claude, session } = connect(async function* () {
315
+ yield assistantText('ok');
316
+ });
317
+ session.setPermissionResolver(allowAll);
318
+ await collectTurn(session, 'first');
319
+
320
+ claude.last.changeModeElsewhere('bypassPermissions');
321
+ const events = await collectTurn(session, 'second');
322
+
323
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(false);
324
+ expect(claude.last.modeChanges).toEqual(['default']);
325
+ expect(claude.last.permissionMode).toBe('default');
326
+ expect(events).toContainEqual(expect.objectContaining({ type: 'plugin_event', subtype: 'auto_approve_restored' }));
327
+ });
328
+
329
+ it('sets Claude back at once when its mode is loosened outside Moxxy in the middle of a turn', async () => {
330
+ const { claude, session } = connect(async function* (turn) {
331
+ if (turn.text === 'second') turn.query.changeModeElsewhere('auto');
332
+ yield assistantText('ok');
333
+ });
334
+ session.setPermissionResolver(allowAll);
335
+ await collectTurn(session, 'first');
336
+
337
+ await collectTurn(session, 'second');
338
+
339
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(false);
340
+ expect(claude.last.permissionMode).toBe('default');
341
+ });
342
+
343
+ it("shows the person's own Claude setup as it is when it starts in bypass permissions", async () => {
344
+ const scene: ClaudeScene = async function* () {
345
+ yield assistantText('ok');
346
+ };
347
+ const { session } = connect(scene, { claude: new FakeClaude(scene, 'bypassPermissions') });
348
+ session.setPermissionResolver(allowAll);
349
+
350
+ await collectTurn(session, 'first');
351
+
352
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(true);
353
+ });
354
+
355
+ it("keeps auto-approve off once the person turned it off, over their own Claude's bypass permissions", async () => {
356
+ const scene: ClaudeScene = async function* () {
357
+ yield assistantText('ok');
358
+ };
359
+ const { claude, session, pool } = connect(scene, { claude: new FakeClaude(scene, 'bypassPermissions') });
360
+ session.setPermissionResolver(allowAll);
361
+ await session.setAutoApprove(true);
362
+ await session.setAutoApprove(false);
363
+
364
+ await collectTurn(session, 'first');
365
+ expect(claude.last.options.permissionMode).toBe('default');
366
+ await pool.close(String(session.id));
367
+ await collectTurn(session, 'second');
368
+
369
+ expect(claude.last.options).toMatchObject({ resume: 'claude-session-1', permissionMode: 'default' });
370
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(false);
371
+ });
372
+
373
+ it('keeps the auto-approve the person chose when a new Claude resumes the session', async () => {
374
+ const { claude, session, pool } = connect(async function* () {
375
+ yield assistantText('ok');
376
+ });
377
+ session.setPermissionResolver(allowAll);
378
+ await collectTurn(session, 'first');
379
+ await session.setAutoApprove(true);
380
+ await collectTurn(session, 'second');
381
+ await pool.close(String(session.id));
382
+
383
+ await collectTurn(session, 'third');
384
+ expect(claude.last.options).toMatchObject({ resume: 'claude-session-1', permissionMode: 'bypassPermissions' });
385
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(true);
386
+
387
+ await session.setAutoApprove(false);
388
+ await collectTurn(session, 'fourth');
389
+ await pool.close(String(session.id));
390
+ await collectTurn(session, 'fifth');
391
+ expect(claude.last.options.permissionMode).toBeUndefined();
392
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(false);
393
+ });
394
+ });
395
+
396
+ describe('Moxxy tools for Claude', () => {
397
+ it('lends Claude only the Moxxy tools it lacks, and runs them through Moxxy', async () => {
398
+ let fromMoxxy: unknown;
399
+ let lentRead: unknown;
400
+ let listed: string[] = [];
401
+ const { session } = connect(async function* (turn) {
402
+ const client = await turn.query.moxxyClient();
403
+ listed = (await client.listTools()).tools.map((t) => t.name);
404
+ yield assistantToolUse('toolu_5', 'mcp__moxxy__browser_title', { url: 'https://example.com' });
405
+ fromMoxxy = await turn.callMoxxyTool('browser_title', { url: 'https://example.com' });
406
+ lentRead = await turn.callMoxxyTool('Read', {});
407
+ yield toolResult('toolu_5', 'Example Domain');
408
+ yield assistantText('The title is Example Domain.');
409
+ });
410
+ session.setPermissionResolver(allowAll);
411
+ session.tools.register(
412
+ defineTool({ name: 'browser_title', description: 'Read a page title', inputSchema: z.object({ url: z.string() }), handler: async () => 'Example Domain' }),
413
+ );
414
+ session.tools.register(defineTool({ name: 'Read', description: 'Read a file', inputSchema: z.object({}), handler: async () => '' }));
415
+
416
+ const events = await collectTurn(session, 'title of example.com?');
417
+
418
+ expect(listed).toEqual(['find_tools', 'describe_tools', 'call_tool']);
419
+ expect(lentRead).toMatchObject({ isError: true });
420
+ expect(fromMoxxy).toEqual({ content: [{ type: 'text', text: 'Example Domain' }] });
421
+ const requests = events.filter((e) => e.type === 'tool_call_requested');
422
+ expect(requests).toHaveLength(1);
423
+ expect(requests[0]).toMatchObject({ name: 'browser_title' });
424
+ expect(requests[0]).not.toHaveProperty('executedBy');
425
+ });
426
+
427
+ it('lets Claude call a Moxxy tool without a second approval window', async () => {
428
+ let answer: unknown;
429
+ const { session } = connect(async function* (turn) {
430
+ answer = await turn.canUseTool('mcp__moxxy__browser_title', {}, 'toolu_6', { mcpServer: { name: 'moxxy', source: 'dynamic' } });
431
+ yield assistantText('ok');
432
+ });
433
+ session.setPermissionResolver(denyAll);
434
+
435
+ await collectTurn(session, 'go');
436
+
437
+ expect(answer).toEqual({ behavior: 'allow', updatedInput: {} });
438
+ });
439
+ });
440
+
441
+ describe('questions', () => {
442
+ it('shows Claude question in Moxxy and hands back the answer keyed by the question', async () => {
443
+ let answer: unknown;
444
+ const { session } = connect(async function* (turn) {
445
+ const input = { questions: [{ question: 'Which colour?', header: 'Colour', multiSelect: false, options: [{ label: 'Red' }, { label: 'Blue' }] }] };
446
+ answer = await turn.canUseTool('AskUserQuestion', input, 'toolu_7');
447
+ yield assistantText('Blue it is.');
448
+ });
449
+ session.questions.attachSurface();
450
+ session.log.subscribe((event) => {
451
+ if (event.type === 'plugin_event' && event.subtype === QUESTION_ASKED) {
452
+ const { questionId, questions } = event.payload as { questionId: string; questions: QuestionItem[] };
453
+ const blue = questions[0]?.options.find((o) => o.label === 'Blue');
454
+ void session.questions.answer(questionId, { [questions[0]?.id ?? '']: { selected: blue ? [blue.id] : [] } });
455
+ }
456
+ });
457
+
458
+ await collectTurn(session, 'make a button');
459
+
460
+ expect(answer).toMatchObject({ behavior: 'allow', updatedInput: { answers: { 'Which colour?': 'Blue' } } });
461
+ });
462
+
463
+ it('tells Claude nobody can answer when no window shows questions', async () => {
464
+ let answer: unknown;
465
+ const { session } = connect(async function* (turn) {
466
+ answer = await turn.canUseTool('AskUserQuestion', { questions: [{ question: 'Which?', options: [] }] }, 'toolu_8');
467
+ yield assistantText('ok');
468
+ });
469
+
470
+ await collectTurn(session, 'go');
471
+
472
+ expect(answer).toMatchObject({ behavior: 'deny', message: expect.stringMatching(/nobody/i) });
473
+ });
474
+ });
475
+
476
+ describe('Moxxy modes on Claude', () => {
477
+ it('plans in Claude own plan mode, and hands the plan to the person as the plan card, not a permission prompt', async () => {
478
+ let answer: unknown;
479
+ const { claude, session } = connect(async function* (turn) {
480
+ answer = await turn.canUseTool('ExitPlanMode', { plan: '# Fix add\n\n- use a + b' }, 'toolu_9');
481
+ yield assistantText('Waiting for your decision.');
482
+ });
483
+ session.pluginHost.registerStatic(planModePlugin);
484
+ session.modes.setActive('plan');
485
+ const asked: string[] = [];
486
+ session.setPermissionResolver({
487
+ name: 'remember-asks',
488
+ check: async (call) => {
489
+ asked.push(call.name);
490
+ return { mode: 'allow' };
491
+ },
492
+ });
493
+
494
+ const events = await collectTurn(session, 'plan the fix');
495
+
496
+ expect(claude.last.options.permissionMode).toBe('plan');
497
+ expect(asked).not.toContain('ExitPlanMode');
498
+ // Handed over, not failed: the call is no red row over the plan.
499
+ expect(events).toContainEqual(expect.objectContaining({ type: 'tool_result', callId: 'toolu_9', ok: true }));
500
+ expect(answer).toMatchObject({ behavior: 'deny', message: expect.stringContaining('Moxxy') });
501
+ expect(session.log.ofType('plugin_event').map((e) => e.subtype)).toContain('plan_completed');
502
+ expect(session.log.ofType('assistant_message').at(-1)?.content).toBe('# Fix add\n\n- use a + b');
503
+ });
504
+
505
+ it('shows the plan Claude wrote to its plan file when it ends a plan turn without handing it over', async () => {
506
+ const dir = mkdtempSync(join(tmpdir(), 'moxxy-claude-plan-'));
507
+ const planFile = join(dir, '.claude', 'plans', 'round-up.md');
508
+ mkdirSync(dirname(planFile), { recursive: true });
509
+ const { session } = connect(async function* () {
510
+ writeFileSync(planFile, '# Round up\n\n- use a toggle');
511
+ yield assistantToolUse('toolu_3', 'Edit', { file_path: planFile, old_string: 'checkbox', new_string: 'toggle' });
512
+ yield toolResult('toolu_3', 'The file was updated.');
513
+ yield assistantText('Plan rewritten. Ready for approval.');
514
+ });
515
+ session.pluginHost.registerStatic(planModePlugin);
516
+ session.modes.setActive('plan');
517
+
518
+ await collectTurn(session, 'use a toggle instead');
519
+
520
+ expect(session.log.ofType('plugin_event').map((e) => e.subtype)).toContain('plan_completed');
521
+ expect(session.log.ofType('assistant_message').at(-1)?.content).toBe('# Round up\n\n- use a toggle');
522
+ removeDirSync(dir);
523
+ });
524
+
525
+ it('leaves a file Claude edits outside its plans folder, or outside plan mode, as a plain edit', async () => {
526
+ const { session } = connect(async function* () {
527
+ yield assistantToolUse('toolu_4', 'Edit', { file_path: '/work/app/index.html', old_string: 'a', new_string: 'b' });
528
+ yield toolResult('toolu_4', 'The file was updated.');
529
+ yield assistantText('Done.');
530
+ });
531
+ session.pluginHost.registerStatic(planModePlugin);
532
+ session.modes.setActive('plan');
533
+
534
+ await collectTurn(session, 'look around');
535
+
536
+ expect(session.log.ofType('plugin_event').map((e) => e.subtype)).not.toContain('plan_completed');
537
+ });
538
+
539
+ it('still asks the person to approve a plan Claude leaves its plan mode with outside Moxxy plan mode', async () => {
540
+ let answer: unknown;
541
+ const { session } = connect(async function* (turn) {
542
+ answer = await turn.canUseTool('ExitPlanMode', { plan: '# Fix add' }, 'toolu_9');
543
+ yield assistantText('Fixed.');
544
+ });
545
+ let described: string | undefined;
546
+ session.setPermissionResolver({
547
+ name: 'remember-description',
548
+ check: async (_call, ctx) => {
549
+ described = ctx?.toolDescription;
550
+ return { mode: 'allow' };
551
+ },
552
+ });
553
+
554
+ await collectTurn(session, 'fix it');
555
+
556
+ expect(described).toContain('# Fix add');
557
+ expect(answer).toMatchObject({ behavior: 'allow' });
558
+ });
559
+
560
+ it('leaves a goal Claude still has open to Claude, without Moxxy pushing it on', async () => {
561
+ const { claude, session } = connect(async function* (turn) {
562
+ if (turn.text === '/goal') {
563
+ yield assistantText('Goal active: the site is deployed', '<synthetic>');
564
+ return;
565
+ }
566
+ yield assistantText('I need the API key to go on.');
567
+ });
568
+ session.pluginHost.registerStatic(goalModePlugin);
569
+ session.modes.setActive('goal');
570
+
571
+ await collectTurn(session, 'the site is deployed');
572
+
573
+ expect(claude.last.received.map((m) => m.message.content)).toEqual([[{ type: 'text', text: '/goal the site is deployed' }], '/goal']);
574
+ expect(session.modes.getActiveName()).toBe('goal');
575
+ });
576
+
577
+ it('answers the next message after a goal turn, once Claude said how its goal stands', async () => {
578
+ const { session } = connect(async function* (turn) {
579
+ if (turn.text === '/goal') {
580
+ yield assistantText('Goal active: the site is deployed', '<synthetic>');
581
+ return;
582
+ }
583
+ yield assistantText(turn.text === 'and now?' ? 'Still deploying.' : 'Working on it.');
584
+ });
585
+ session.pluginHost.registerStatic(goalModePlugin);
586
+ session.modes.setActive('goal');
587
+ await collectTurn(session, 'the site is deployed');
588
+ session.modes.setActive('default');
589
+
590
+ const events = await collectTurn(session, 'and now?');
591
+
592
+ expect(said(events)).toEqual(['Still deploying.']);
593
+ });
594
+
595
+ it('runs a goal with Claude own /goal, and ends Moxxy goal mode when Claude says it is met', async () => {
596
+ const { claude, session } = connect(async function* (turn) {
597
+ if (turn.text === '/goal') {
598
+ yield assistantText('No goal set. Usage: `/goal <condition>`', '<synthetic>');
599
+ return;
600
+ }
601
+ yield assistantText('Goal set: goal.txt says GOAL-DONE', '<synthetic>');
602
+ yield assistantText('goal.txt now says GOAL-DONE.');
603
+ });
604
+ session.pluginHost.registerStatic(goalModePlugin);
605
+ session.modes.setActive('goal');
606
+
607
+ const events = await collectTurn(session, 'goal.txt says GOAL-DONE');
608
+
609
+ expect(claude.last.received.map((m) => m.message.content)).toEqual([
610
+ [{ type: 'text', text: '/goal goal.txt says GOAL-DONE' }],
611
+ '/goal',
612
+ ]);
613
+ expect(claude.last.options.permissionMode).toBe('bypassPermissions');
614
+ expect(said(events)).not.toContain('No goal set. Usage: `/goal <condition>`');
615
+ expect(events).toContainEqual(expect.objectContaining({ type: 'plugin_event', subtype: AGENT_GOAL_SUBTYPE, payload: expect.objectContaining({ status: 'complete' }) }));
616
+ expect(events.some((e) => e.type === 'plugin_event' && e.subtype === 'goal_completed')).toBe(true);
617
+ expect(autoApproveFromEvents(session.log.ofType('plugin_event'))).toBe(false);
618
+ });
619
+ });
620
+
621
+ describe('turns Claude takes up by itself', () => {
622
+ const sub = (id: string, content: unknown[]): ClaudeMessage => ({ type: 'assistant', message: { content }, parent_tool_use_id: 'toolu_agent' }) as ClaudeMessage;
623
+ const system = (fields: Record<string, unknown>): ClaudeMessage => ({ type: 'system', ...fields }) as ClaudeMessage;
624
+ const launchInBackground = async function* (): AsyncIterable<ClaudeMessage> {
625
+ yield assistantToolUse('toolu_agent', 'Agent', { description: 'List files', prompt: 'list the files', run_in_background: true });
626
+ yield system({ subtype: 'task_started', task_id: 't1', tool_use_id: 'toolu_agent', description: 'List files', is_backgrounded: true });
627
+ yield { ...toolResult('toolu_agent', 'Async agent launched'), tool_use_result: { isAsync: true, status: 'async_launched' } } as ClaudeMessage;
628
+ yield assistantText('Started it in the background.');
629
+ };
630
+ const backgroundFinished = {
631
+ background: [
632
+ sub('toolu_agent', [{ type: 'tool_use', id: 'toolu_ls', name: 'Bash', input: { command: 'ls' } }]),
633
+ sub('toolu_agent', [{ type: 'text', text: 'Two files.' }]),
634
+ system({ subtype: 'task_notification', task_id: 't1', tool_use_id: 'toolu_agent', status: 'completed', summary: 'Two files.' }),
635
+ ],
636
+ messages: [assistantText('The helper found two files.')],
637
+ };
638
+
639
+ it("opens a Moxxy turn for it, marked as Claude's, with what Claude said, the helper's work recorded as it came, sending Claude nothing", async () => {
640
+ const { claude, session } = connect(async function* (turn) {
641
+ if (turn.text === '2+2?') yield assistantText('4');
642
+ else yield* launchInBackground();
643
+ });
644
+ session.setPermissionResolver(allowAll);
645
+ await collectTurn(session, 'List the files in the background');
646
+
647
+ claude.last.startOwnTurn(backgroundFinished);
648
+ await vi.waitFor(() => expect(said(session.log.ofType('assistant_message'))).toContain('The helper found two files.'));
649
+
650
+ const opened = session.log.ofType('user_prompt').at(-1);
651
+ expect(opened).toMatchObject({ origin: { kind: 'agent', name: 'List files finished in the background' } });
652
+ const all = session.log.slice();
653
+ const helperDone = all.findIndex((e) => e.type === 'plugin_event' && e.subtype === 'subagent_completed');
654
+ expect(all.some((e) => e.type === 'plugin_event' && e.subtype === 'subagent_tool_call')).toBe(true);
655
+ expect(helperDone).toBeGreaterThan(-1);
656
+ expect(helperDone).toBeLessThan(all.findIndex((e) => e === opened));
657
+ expect(all.filter((e) => opened && e.turnId === opened.turnId && e.type === 'assistant_message')).toHaveLength(1);
658
+ expect(claude.last.received).toHaveLength(1);
659
+
660
+ const next = await collectTurn(session, '2+2?');
661
+ expect(said(next)).toEqual(['4']);
662
+ });
663
+
664
+ it('opens a turn each time Claude wakes itself up, whose result carries no origin, and the next message gets its own reply', async () => {
665
+ const { claude, session } = connect(async function* (turn) {
666
+ yield assistantText(turn.text === 'build it' ? 'Building.' : 'Will check back.');
667
+ });
668
+ session.setPermissionResolver(allowAll);
669
+ await collectTurn(session, 'check CI');
670
+
671
+ claude.last.startOwnTurn({ messages: [assistantText('First check: still running.')], scheduled: true });
672
+ await vi.waitFor(() => expect(said(session.log.ofType('assistant_message'))).toContain('First check: still running.'));
673
+ claude.last.startOwnTurn({ messages: [assistantText('Second check: all green.')], scheduled: true });
674
+ await vi.waitFor(() => expect(said(session.log.ofType('assistant_message'))).toContain('Second check: all green.'));
675
+
676
+ const next = await collectTurn(session, 'build it');
677
+ expect(said(next)).toEqual(['Building.']);
678
+ expect(session.log.ofType('user_prompt').map((p) => p.origin?.kind ?? 'person')).toEqual(['person', 'agent', 'agent', 'person']);
679
+ });
680
+
681
+ it('lists when Claude set itself to come back, and names the turn it comes back in a scheduled check-in', async () => {
682
+ const now = new Date();
683
+ const thisMinute = `${now.getMinutes()} ${now.getHours()} ${now.getDate()} ${now.getMonth() + 1} *`;
684
+ const { claude, session } = connect(async function* (turn) {
685
+ turn.query.crons = [{ id: 'c1', schedule: thisMinute, recurring: false, prompt: '/loop check CI' }];
686
+ yield assistantText('Will check back.');
687
+ });
688
+ session.setPermissionResolver(allowAll);
689
+ await collectTurn(session, 'check CI in a minute');
690
+
691
+ await vi.waitFor(() => expect(session.getInfo().scheduledWakeups).toEqual([{ id: 'c1', prompt: 'check CI', dueAtMs: expect.any(Number), recurring: false }]));
692
+
693
+ claude.last.crons = [];
694
+ claude.last.startOwnTurn({ messages: [assistantText('CI is green.')], scheduled: true });
695
+ await vi.waitFor(() => expect(said(session.log.ofType('assistant_message'))).toContain('CI is green.'));
696
+ expect(session.log.ofType('user_prompt').at(-1)?.origin).toEqual({ kind: 'agent', name: 'Scheduled check-in' });
697
+ await vi.waitFor(() => expect(session.getInfo().scheduledWakeups).toEqual([]));
698
+ });
699
+
700
+ it('lists nothing from a Claude too old to report what it set itself to come back for', async () => {
701
+ const { session } = connect(async function* (turn) {
702
+ turn.query.crons = undefined;
703
+ yield assistantText('ok');
704
+ });
705
+ session.setPermissionResolver(allowAll);
706
+ await collectTurn(session, 'hi');
707
+ expect(session.getInfo().scheduledWakeups).toEqual([]);
708
+ });
709
+
710
+ it('opens the turn when the conversation went to another connection and came back while the helper ran', async () => {
711
+ const { claude, session, pool } = connect(async function* () {
712
+ yield* launchInBackground();
713
+ });
714
+ session.setPermissionResolver(allowAll);
715
+ addFakeProvider(session, new FakeProvider({ name: 'stand-in', script: [] }));
716
+ await collectTurn(session, 'List the files in the background');
717
+
718
+ // The runner switches connections this way: a fresh client each time the conversation comes back.
719
+ session.providers.setActive('stand-in');
720
+ session.providers.replace(
721
+ defineProvider({
722
+ name: 'claude-code',
723
+ models: [],
724
+ createClient: () =>
725
+ new ClaudeAgentProvider({ executable: '/Users/me/.local/bin/claude', defaultModel: 'claude-opus-5-5', loadSdk: async () => claude, sessions: pool }),
726
+ }),
727
+ );
728
+ session.providers.setActive('claude-code');
729
+
730
+ claude.last.startOwnTurn(backgroundFinished);
731
+ await vi.waitFor(() => expect(said(session.log.ofType('assistant_message'))).toContain('The helper found two files.'));
732
+ expect(session.log.ofType('user_prompt').at(-1)).toMatchObject({ origin: { kind: 'agent' } });
733
+ });
734
+
735
+ it("checks Moxxy's rules for a background helper's call while no turn runs", async () => {
736
+ let claudeTurn: FakeTurn | undefined;
737
+ const { session } = connect(async function* (turn) {
738
+ claudeTurn = turn;
739
+ yield* launchInBackground();
740
+ });
741
+ session.setPermissionResolver(allowAll);
742
+ session.pluginHost.registerStatic(
743
+ definePlugin({
744
+ name: '@moxxy/test-rule',
745
+ hooks: { onToolCall: ({ call }) => (JSON.stringify(call.input).includes('forbidden') ? { action: 'deny', reason: 'blocked by a Moxxy rule' } : undefined) },
746
+ }),
747
+ );
748
+ await collectTurn(session, 'List the files in the background');
749
+ assertDefined(claudeTurn, 'Claude ran a turn');
750
+
751
+ const blocked = await claudeTurn.preToolUse('Bash', { command: 'echo forbidden-word' }, 'toolu_bg1', 't1');
752
+ const allowed = await claudeTurn.preToolUse('Bash', { command: 'ls' }, 'toolu_bg2', 't1');
753
+
754
+ expect(blocked).toEqual({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'blocked by a Moxxy rule' } });
755
+ expect(allowed).toEqual({});
756
+ });
757
+ });
758
+
759
+ describe("Claude's work in the background", () => {
760
+ const sub = (content: unknown[]): ClaudeMessage => ({ type: 'assistant', message: { content }, parent_tool_use_id: 'toolu_agent' }) as ClaudeMessage;
761
+ const system = (fields: Record<string, unknown>): ClaudeMessage => ({ type: 'system', ...fields }) as ClaudeMessage;
762
+ const tasks = (...list: Array<Record<string, unknown>>): ClaudeMessage => system({ subtype: 'background_tasks_changed', tasks: list });
763
+ const devServer = { task_id: 't2', task_type: 'local_bash', description: 'npm run dev' };
764
+ const helper = { task_id: 't1', task_type: 'local_agent', subagent_type: 'Explore', description: 'List files' };
765
+ const workOf = (session: Session, subtype: string) =>
766
+ session.log.ofType('plugin_event').filter((e) => e.pluginId === AGENT_CONNECTION_PLUGIN_ID && e.subtype === subtype).map((e) => e.payload);
767
+ const startServer = async function* (): AsyncIterable<ClaudeMessage> {
768
+ yield assistantToolUse('toolu_bg', 'Bash', { command: 'npm run dev', run_in_background: true });
769
+ yield tasks(devServer);
770
+ yield system({ subtype: 'task_started', task_id: 't2', tool_use_id: 'toolu_bg', description: 'npm run dev', task_type: 'local_bash', is_backgrounded: true });
771
+ yield toolResult('toolu_bg', 'Command running in background with ID: t2.');
772
+ yield assistantText('The server is starting.');
773
+ };
774
+ const launchHelper = async function* (): AsyncIterable<ClaudeMessage> {
775
+ yield assistantToolUse('toolu_agent', 'Agent', { description: 'List files', prompt: 'list the files', run_in_background: true });
776
+ yield tasks(helper);
777
+ yield system({ subtype: 'task_started', task_id: 't1', tool_use_id: 'toolu_agent', description: 'List files', task_type: 'local_agent', is_backgrounded: true });
778
+ yield { ...toolResult('toolu_agent', 'Async agent launched'), tool_use_result: { isAsync: true, status: 'async_launched' } } as ClaudeMessage;
779
+ yield assistantText('A helper is on it.');
780
+ };
781
+
782
+ it('lists a command Claude left running while it runs, and records how it ended with what it printed last', async () => {
783
+ const dir = mkdtempSync(join(tmpdir(), 'moxxy-claude-task-'));
784
+ const output = join(dir, 't2.output');
785
+ writeFileSync(output, 'compiling\nready on http://localhost:5173\n');
786
+ const { claude, session } = connect(startServer);
787
+ session.setPermissionResolver(allowAll);
788
+
789
+ await collectTurn(session, 'start the dev server');
790
+ await vi.waitFor(() => expect(session.getInfo().backgroundWork).toEqual([{ id: 't2', kind: 'command', label: 'npm run dev' }]));
791
+
792
+ claude.last.sendBetweenTurns([
793
+ system({ subtype: 'task_notification', task_id: 't2', tool_use_id: 'toolu_bg', status: 'stopped', output_file: output, summary: 'npm run dev was stopped' }),
794
+ tasks(),
795
+ ]);
796
+ await vi.waitFor(() => expect(workOf(session, 'background_work_ended')).toHaveLength(1));
797
+ await vi.waitFor(() => expect(session.getInfo().backgroundWork).toEqual([]));
798
+
799
+ expect(workOf(session, 'background_work_ended')[0]).toEqual({
800
+ provider: 'claude-code',
801
+ id: 't2',
802
+ kind: 'command',
803
+ label: 'npm run dev',
804
+ status: 'stopped',
805
+ summary: 'npm run dev was stopped',
806
+ output: 'compiling\nready on http://localhost:5173\n',
807
+ });
808
+ expect(session.log.ofType('user_prompt')).toHaveLength(1);
809
+ removeDirSync(dir);
810
+ });
811
+
812
+ it("shows a background helper's steps and words as they happen, not at Claude's next turn, and each once", async () => {
813
+ const { claude, session } = connect(launchHelper);
814
+ session.setPermissionResolver(allowAll);
815
+ await collectTurn(session, 'list the files in the background');
816
+ await vi.waitFor(() => expect(session.getInfo().backgroundWork).toEqual([{ id: 'toolu_agent', kind: 'agent', label: 'List files' }]));
817
+
818
+ claude.last.sendBetweenTurns([
819
+ sub([{ type: 'text', text: 'Listing the folder.' }, { type: 'tool_use', id: 'toolu_ls', name: 'Bash', input: { command: 'ls' } }]),
820
+ ]);
821
+ await vi.waitFor(() => expect(session.log.ofType('plugin_event').some((e) => e.subtype === 'subagent_tool_call')).toBe(true));
822
+ expect(session.log.ofType('user_prompt')).toHaveLength(1);
823
+
824
+ claude.last.startOwnTurn({
825
+ background: [
826
+ sub([{ type: 'text', text: 'Two files.' }]),
827
+ system({ subtype: 'task_notification', task_id: 't1', tool_use_id: 'toolu_agent', status: 'completed', output_file: '', summary: 'Two files.' }),
828
+ tasks(),
829
+ ],
830
+ messages: [assistantText('The helper found two files.')],
831
+ });
832
+ await vi.waitFor(() => expect(said(session.log.ofType('assistant_message'))).toContain('The helper found two files.'));
833
+
834
+ const helperEvents = session.log.ofType('plugin_event').filter((e) => e.pluginId === '@moxxy/subagents');
835
+ expect(helperEvents.map((e) => e.subtype)).toEqual(['subagent_started', 'subagent_message', 'subagent_tool_call', 'subagent_message', 'subagent_completed']);
836
+ // Claude lists the helper before it says which call started it: it is listed once, by that call.
837
+ const listedIds = workOf(session, 'background_work').flatMap((p) => (p.work as ReadonlyArray<{ id: string }>).map((w) => w.id));
838
+ expect(new Set(listedIds)).toEqual(new Set(['toolu_agent']));
839
+ expect(session.log.ofType('user_prompt').at(-1)?.origin).toEqual({ kind: 'agent', name: 'List files finished in the background', workId: 'toolu_agent' });
840
+ expect(session.getInfo().backgroundWork).toEqual([]);
841
+ });
842
+
843
+ it('stops one background work through Claude, and says when Claude runs no such work', async () => {
844
+ const { claude, session } = connect(launchHelper);
845
+ session.setPermissionResolver(allowAll);
846
+ await collectTurn(session, 'list the files in the background');
847
+ await vi.waitFor(() => expect(session.getInfo().backgroundWork).toHaveLength(1));
848
+
849
+ expect(await session.stopBackgroundWork('toolu_agent')).toBe(true);
850
+ expect(await session.stopBackgroundWork('nothing-like-it')).toBe(false);
851
+ expect(claude.last.stoppedTasks).toEqual(['t1']);
852
+ claude.last.sendBetweenTurns([
853
+ system({ subtype: 'task_notification', task_id: 't1', tool_use_id: 'toolu_agent', status: 'stopped', output_file: '', summary: '' }),
854
+ tasks(),
855
+ ]);
856
+
857
+ await vi.waitFor(() => expect(session.getInfo().backgroundWork).toEqual([]));
858
+ const ended = session.log.ofType('plugin_event').find((e) => e.subtype === 'subagent_completed');
859
+ expect(ended?.payload).toMatchObject({ childSessionId: 'toolu_agent', stopReason: 'stopped' });
860
+ });
861
+
862
+ it("lists nothing running once the conversation's Claude is closed, as its work ends with it", async () => {
863
+ const { session, pool } = connect(startServer);
864
+ session.setPermissionResolver(allowAll);
865
+ await collectTurn(session, 'start the dev server');
866
+ await vi.waitFor(() => expect(session.getInfo().backgroundWork).toHaveLength(1));
867
+
868
+ await pool.close(String(session.id));
869
+
870
+ await vi.waitFor(() => expect(session.getInfo().backgroundWork).toEqual([]));
871
+ });
872
+ });
873
+
874
+ describe('stopping and failing', () => {
875
+ it('interrupts Claude on Stop, and the next message works as usual', async () => {
876
+ const controller = new AbortController();
877
+ const { claude, session } = connect(async function* (turn) {
878
+ if (turn.text === 'wait') {
879
+ yield assistantToolUse('toolu_10', 'Bash', { command: 'sleep 100' });
880
+ controller.abort();
881
+ await new Promise(() => {});
882
+ }
883
+ yield assistantText('back');
884
+ });
885
+
886
+ const stopped = await collectTurn(session, 'wait', { signal: controller.signal });
887
+ const next = await collectTurn(session, 'again');
888
+
889
+ expect(claude.last.interrupts).toBe(1);
890
+ expect(stopped.map((e) => e.type)).toContain('abort');
891
+ expect(stopped).toContainEqual(expect.objectContaining({ type: 'tool_result', callId: 'toolu_10', ok: false }));
892
+ expect(said(next)).toEqual(['back']);
893
+ });
894
+
895
+ it('ends the turn with Claude own error, and starts Claude again for the next message', async () => {
896
+ let calls = 0;
897
+ const { claude, session } = connect(async function* () {
898
+ calls += 1;
899
+ if (calls === 1) throw new Error('Claude Code process exited with code 1');
900
+ yield assistantText('fine now');
901
+ });
902
+
903
+ const failed = await collectTurn(session, 'hi');
904
+ const next = await collectTurn(session, 'hi again');
905
+
906
+ expect(failed).toContainEqual(expect.objectContaining({ type: 'error', kind: 'fatal', message: expect.stringContaining('exited with code 1') }));
907
+ expect(claude.queries).toHaveLength(2);
908
+ expect(said(next)).toEqual(['fine now']);
909
+ });
910
+
911
+ it('records the context window Claude runs the turn model with, not that of a helper model', async () => {
912
+ const usage = (contextWindow: number, canonicalModel?: string) => ({
913
+ inputTokens: 3, outputTokens: 7, cacheReadInputTokens: 0, cacheCreationInputTokens: 0, webSearchRequests: 0, costUSD: 0,
914
+ contextWindow, maxOutputTokens: 128_000, ...(canonicalModel ? { canonicalModel } : {}),
915
+ });
916
+ const { session } = connect(async function* (turn) {
917
+ yield turn.query.result('success', false, {
918
+ result: 'Hi.',
919
+ modelUsage: { 'claude-fable-5-1[1m]': usage(640_000, 'claude-fable-5-1'), 'claude-haiku-5-5': usage(200_000) },
920
+ });
921
+ });
922
+
923
+ await collectTurn(session, 'hi', { model: 'claude-fable-5-1' });
924
+
925
+ const models = session.getInfo().providers.find((p) => p.name === 'claude-code')?.models ?? [];
926
+ expect(models.find((m) => m.id === 'claude-fable-5-1')?.contextWindow).toBe(640_000);
927
+ expect(models.find((m) => m.id === 'claude-haiku-5-5')?.contextWindow).toBe(1_000_000);
928
+ });
929
+
930
+ it('reports a failed Claude turn as an error', async () => {
931
+ const { session } = connect(async function* (turn) {
932
+ yield turn.query.result('error_max_turns', true, { errors: ['Reached the maximum number of turns'] });
933
+ });
934
+
935
+ const events = await collectTurn(session, 'hi');
936
+
937
+ expect(events).toContainEqual(expect.objectContaining({ type: 'error', message: expect.stringContaining('maximum number of turns') }));
938
+ });
939
+ });
940
+
941
+ describe('one-off text calls', () => {
942
+ it('asks Claude for plain text without tools and without keeping a session', async () => {
943
+ const claude = new FakeClaude(async function* (turn) {
944
+ yield assistantText(`summary of: ${turn.text.slice(0, 20)}`);
945
+ });
946
+ const provider = new ClaudeAgentProvider({ defaultModel: 'claude-opus-5-5', loadSdk: async () => claude });
947
+
948
+ const out: string[] = [];
949
+ for await (const event of provider.stream({
950
+ model: 'claude-opus-5-5',
951
+ system: 'Summarize.',
952
+ messages: [{ role: 'user', content: [{ type: 'text', text: 'A long conversation' }] }],
953
+ })) {
954
+ if (event.type === 'text_delta') out.push(event.delta);
955
+ }
956
+
957
+ expect(out.join('')).toBe('summary of: A long conversation');
958
+ expect(claude.last.options.tools).toEqual([]);
959
+ expect(claude.last.options.persistSession).toBe(false);
960
+ expect(claude.last.options.systemPrompt).toBe('Summarize.');
961
+ });
962
+
963
+ it('gives Claude the instructions of the request as its instructions, not as words the person said', async () => {
964
+ const claude = new FakeClaude(async function* (turn) {
965
+ yield assistantText(`asked: ${turn.text}`);
966
+ });
967
+ const provider = new ClaudeAgentProvider({ defaultModel: 'claude-haiku-5-5', loadSdk: async () => claude });
968
+
969
+ const out: string[] = [];
970
+ for await (const event of provider.stream({
971
+ model: 'claude-haiku-5-5',
972
+ messages: [
973
+ { role: 'system', content: [{ type: 'text', text: 'Plan search queries.' }] },
974
+ { role: 'user', content: [{ type: 'text', text: 'Find the release date.' }] },
975
+ ],
976
+ })) {
977
+ if (event.type === 'text_delta') out.push(event.delta);
978
+ }
979
+
980
+ expect(out.join('')).toBe('asked: Find the release date.');
981
+ expect(claude.last.options.systemPrompt).toBe('Plan search queries.');
982
+ });
983
+
984
+ it("loads none of the person's MCP servers or claude.ai connectors, which a one-step call could only fail on", async () => {
985
+ const claude = new FakeClaude(async function* () {
986
+ yield assistantText('a summary');
987
+ });
988
+ const provider = new ClaudeAgentProvider({ defaultModel: 'claude-haiku-5-5', loadSdk: async () => claude });
989
+
990
+ for await (const _ of provider.stream({ model: 'claude-haiku-5-5', messages: [{ role: 'user', content: [{ type: 'text', text: 'Summarize.' }] }] })) void _;
991
+
992
+ expect(claude.last.options.strictMcpConfig).toBe(true);
993
+ expect(claude.last.options.mcpServers).toBeUndefined();
994
+ });
995
+ });
996
+
997
+ describe('the Moxxy tools Claude can see', () => {
998
+ const askLike = defineTool({ name: 'ask_like', description: 'Ask the person.', inputSchema: z.object({}), notInModes: ['goal'], handler: async () => 'answered' });
999
+
1000
+ it('are listed before Claude starts, since it reads them as it starts', async () => {
1001
+ const claude = new FakeClaude(async function* () {});
1002
+ const session = await ClaudeAgentSession.start({ sdk: claude, cwd: '/work', model: 'claude-opus-5-5', tools: [askLike] });
1003
+
1004
+ const { tools } = await (await claude.last.moxxyClient()).listTools();
1005
+ await session.close();
1006
+
1007
+ expect(tools.map((tool) => tool.name)).toEqual(['find_tools', 'describe_tools', 'call_tool']);
1008
+ expect(tools[0]?.description).toMatch(/ask_like/);
1009
+ });
1010
+
1011
+ it('are lent as a catalog of three small tools, so their full descriptions are not in every request, and the chat shows the tool that ran', async () => {
1012
+ const noted = defineTool({ name: 'note_lookup', description: 'Look a note up.', inputSchema: z.object({}), handler: async () => 'the note' });
1013
+ let listed: string[] = [];
1014
+ const results: unknown[] = [];
1015
+ const { session } = connect(async function* (turn) {
1016
+ listed = (await (await turn.query.moxxyClient()).listTools()).tools.map((tool) => tool.name);
1017
+ yield assistantToolUse('toolu_9', 'mcp__moxxy__call_tool', { name: 'note_lookup', arguments: {} });
1018
+ results.push(await turn.callMoxxyTool('note_lookup', {}));
1019
+ yield toolResult('toolu_9', 'the note');
1020
+ yield assistantText('ok');
1021
+ });
1022
+ session.setPermissionResolver(allowAll);
1023
+ session.tools.register(noted);
1024
+
1025
+ const events = await collectTurn(session, 'look it up');
1026
+
1027
+ expect(listed.filter((name) => name !== 'load_skill')).toEqual(['find_tools', 'describe_tools', 'call_tool']);
1028
+ expect(results).toEqual([{ content: [{ type: 'text', text: 'the note' }] }]);
1029
+ expect(events.filter((e) => e.type === 'tool_call_requested').map((e) => e.type === 'tool_call_requested' && e.name)).toEqual(['note_lookup']);
1030
+ });
1031
+
1032
+ it('stay the same between modes, and Claude hears why one is not available in this mode', async () => {
1033
+ const results: Array<{ content: unknown; isError?: boolean }> = [];
1034
+ const { session } = connect(async function* (turn) {
1035
+ if (turn.text === '/goal') {
1036
+ yield assistantText('Goal active: done', '<synthetic>');
1037
+ return;
1038
+ }
1039
+ if (turn.text.endsWith('do it') || turn.text === 'now ask me') results.push(await turn.callMoxxyTool('ask_like', {}));
1040
+ yield assistantText('ok');
1041
+ });
1042
+ session.pluginHost.registerStatic(definePlugin({ name: 'test-ask', tools: [askLike] }));
1043
+ session.pluginHost.registerStatic(goalModePlugin);
1044
+ session.modes.setActive('goal');
1045
+
1046
+ await collectTurn(session, 'do it');
1047
+ session.modes.setActive('default');
1048
+ await collectTurn(session, 'now ask me');
1049
+
1050
+ expect(results[0]).toEqual({ content: [{ type: 'text', text: expect.stringMatching(/^ask_like is not available in goal mode/) }], isError: true });
1051
+ expect(results[1]).toEqual({ content: [{ type: 'text', text: 'answered' }] });
1052
+ });
1053
+
1054
+ it('tells Claude when the conversation gains a tool, so it reads the list again', async () => {
1055
+ const noted = defineTool({ name: 'note_lookup', description: 'Look a note up.', inputSchema: z.object({}), handler: async () => 'the note' });
1056
+ const found: unknown[] = [];
1057
+ const { claude, session } = connect(async function* (turn) {
1058
+ if (turn.text === 'look it up') found.push(await turn.callMoxxyTool('note_lookup', {}));
1059
+ yield assistantText('ok');
1060
+ });
1061
+ await collectTurn(session, 'hello');
1062
+ session.pluginHost.registerStatic(definePlugin({ name: 'test-notes', tools: [noted] }));
1063
+
1064
+ await collectTurn(session, 'look it up');
1065
+
1066
+ expect(claude.queries).toHaveLength(1);
1067
+ expect(found).toEqual([expect.objectContaining({ content: [{ type: 'text', text: 'the note' }] })]);
1068
+ });
1069
+ });
1070
+
1071
+ describe("the person's Moxxy skills on Claude", () => {
1072
+ const skill = (name: string): Skill => ({
1073
+ id: name as Skill['id'],
1074
+ path: `/skills/${name}.md`,
1075
+ scope: 'user',
1076
+ frontmatter: { name, description: `About ${name}` },
1077
+ body: `Steps for ${name}.`,
1078
+ });
1079
+
1080
+ function withSkills(scene: ClaudeScene, ownSkills: string[] = []) {
1081
+ const claude = new FakeClaude(scene);
1082
+ claude.ownSkills = ownSkills;
1083
+ const connected = connect(scene, { claude });
1084
+ connected.session.pluginHost.registerStatic(buildSynthesizeSkillPlugin(connected.session));
1085
+ connected.session.setPermissionResolver(allowAll);
1086
+ return connected;
1087
+ }
1088
+
1089
+ it("lists them in one tool Claude reads a skill with, leaving one Claude has itself to Claude's", async () => {
1090
+ let listed: string | undefined;
1091
+ let read: { content: unknown; isError?: boolean } | undefined;
1092
+ const { session } = withSkills(async function* (turn) {
1093
+ const { tools } = await (await turn.query.moxxyClient()).listTools();
1094
+ listed = tools.find((tool) => tool.name === 'load_skill')?.description;
1095
+ read = await turn.callMoxxyTool('load_skill', { name: 'monthly-invoices' });
1096
+ yield assistantText('ok');
1097
+ }, ['deploy-staging']);
1098
+ session.skills.register(skill('monthly-invoices'));
1099
+ session.skills.register(skill('deploy-staging'));
1100
+
1101
+ const events = await collectTurn(session, 'do the invoices');
1102
+
1103
+ expect(listed).toContain('- monthly-invoices: About monthly-invoices');
1104
+ expect(listed).not.toContain('deploy-staging');
1105
+ expect(read).toEqual({ content: [{ type: 'text', text: expect.stringContaining('Steps for monthly-invoices.') }] });
1106
+ expect(events).toContainEqual(expect.objectContaining({ type: 'skill_invoked', name: 'monthly-invoices' }));
1107
+ });
1108
+
1109
+ it('reach Claude at its next turn when one is saved during the conversation', async () => {
1110
+ const read: Array<{ content: unknown; isError?: boolean }> = [];
1111
+ const { claude, session } = withSkills(async function* (turn) {
1112
+ if (turn.text === 'use it') read.push(await turn.callMoxxyTool('load_skill', { name: 'monthly-invoices' }));
1113
+ yield assistantText('ok');
1114
+ });
1115
+ await collectTurn(session, 'hello');
1116
+ session.skills.register(skill('monthly-invoices'));
1117
+
1118
+ await collectTurn(session, 'use it');
1119
+
1120
+ expect(claude.queries).toHaveLength(1);
1121
+ expect(read).toEqual([{ content: [{ type: 'text', text: expect.stringContaining('Steps for monthly-invoices.') }] }]);
1122
+ });
1123
+
1124
+ it('reach Claude at its next turn when a skill file is added to a skills folder during the conversation', async () => {
1125
+ const root = mkdtempSync(join(tmpdir(), 'moxxy-claude-skills-'));
1126
+ try {
1127
+ const projectDir = join(root, 'project-skills');
1128
+ const read: Array<{ content: unknown; isError?: boolean }> = [];
1129
+ const connected = connect(async function* (turn) {
1130
+ if (turn.text === 'use it') read.push(await turn.callMoxxyTool('load_skill', { name: 'weekly-report' }));
1131
+ yield assistantText('ok');
1132
+ });
1133
+ connected.session.pluginHost.registerStatic(
1134
+ buildSynthesizeSkillPlugin(connected.session, { userDir: join(root, 'user-skills'), projectDir, rescanBeforeAgentTurns: true }),
1135
+ );
1136
+ connected.session.setPermissionResolver(allowAll);
1137
+ await collectTurn(connected.session, 'hello');
1138
+ mkdirSync(projectDir, { recursive: true });
1139
+ writeFileSync(join(projectDir, 'weekly-report.md'), '---\nname: weekly-report\ndescription: Write the weekly report\n---\nSteps for the weekly report.\n');
1140
+
1141
+ await collectTurn(connected.session, 'use it');
1142
+
1143
+ expect(read).toEqual([{ content: [{ type: 'text', text: expect.stringContaining('Steps for the weekly report.') }] }]);
1144
+ } finally {
1145
+ removeDirSync(root);
1146
+ }
1147
+ });
1148
+ });
1149
+
1150
+ describe('an MCP server set up both in Moxxy and in Claude', () => {
1151
+ it("reaches Claude once, through Claude's own setup", async () => {
1152
+ const mcpTool = (name: string) => defineTool({ name, description: name, inputSchema: z.object({}), handler: async () => 'ok' });
1153
+ const results: Record<string, { isError?: boolean }> = {};
1154
+ const claude = new FakeClaude(async function* (turn) {
1155
+ for (const name of ['mcp__notes__read', 'mcp__vault__secret_word']) results[name] = await turn.callMoxxyTool(name, {});
1156
+ yield assistantText('ok');
1157
+ });
1158
+ claude.ownMcpServers = ['vault'];
1159
+ const { session } = connect(async function* () {}, { claude });
1160
+ session.setPermissionResolver(allowAll);
1161
+ session.pluginHost.registerStatic(definePlugin({ name: 'mcp-servers', tools: [mcpTool('mcp__vault__secret_word'), mcpTool('mcp__notes__read')] }));
1162
+
1163
+ await collectTurn(session, 'which tools?');
1164
+
1165
+ expect(results['mcp__notes__read']?.isError).toBeFalsy();
1166
+ expect(results['mcp__vault__secret_word']?.isError).toBe(true);
1167
+ });
1168
+ });
1169
+
1170
+ describe('the Moxxy tools Claude gets', () => {
1171
+ it('include recall, which searches the whole conversation, and not what Claude has its own of', () => {
1172
+ const tools = ['Read', 'recall', 'session_recall', 'present_view'].map((name) => ({ name }) as ToolDef);
1173
+
1174
+ expect(toolsLentToClaude(tools).map((tool) => tool.name)).toEqual(['recall', 'present_view']);
1175
+ });
1176
+ });