@moxxy/plugin-provider-claude-code 0.43.0 → 0.45.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 +700 -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 +45 -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 +310 -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 +57 -0
  66. package/dist/translate.d.ts.map +1 -0
  67. package/dist/translate.js +276 -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 +1156 -0
  73. package/src/agent-provider.ts +223 -0
  74. package/src/agent-session.ts +790 -0
  75. package/src/background-work.ts +163 -0
  76. package/src/constants.ts +2 -3
  77. package/src/event-coverage.test.ts +105 -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 +73 -0
  87. package/src/offered-models.ts +57 -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 +277 -0
  97. package/src/subagents.ts +123 -0
  98. package/src/task-list.ts +65 -0
  99. package/src/translate.test.ts +439 -0
  100. package/src/translate.ts +280 -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,790 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import type { AgentScheduledWakeup, AgentStepEvent, AgentStepHost, AgentStepRequest, AgentToolCall, AgentToolOutcome, Skill, ToolDef } from '@moxxy/sdk';
4
+ import {
5
+ Inbox,
6
+ agentModeFor,
7
+ earlierConversationNote,
8
+ idleToolsHandler,
9
+ moxxyToolsHandler,
10
+ resumeAgentSession,
11
+ sameToolNames,
12
+ skillsForAgent,
13
+ startMoxxyMcpServer,
14
+ type AgentMode,
15
+ type LiveSession,
16
+ type MoxxyMcpServer,
17
+ type NewSessionReason,
18
+ untilStopped,
19
+ withoutOwnMcpServers,
20
+ } from '@moxxy/agent-connection-kit';
21
+ import { isContextWindowSize } from '@moxxy/sdk';
22
+ import { fromClaudeQuestions, toClaudeAnswers } from './questions.js';
23
+ import type {
24
+ ClaudeAgentSdk,
25
+ ClaudeEffort,
26
+ ClaudeMessage,
27
+ ClaudeModelUsage,
28
+ ClaudePermissionMode,
29
+ ClaudePermissionResult,
30
+ ClaudePreToolUseOutput,
31
+ ClaudeQuery,
32
+ ClaudeUserContent,
33
+ ClaudeUserMessage,
34
+ ClaudeStopInput,
35
+ } from './sdk-types.js';
36
+ import {
37
+ MOXXY_MCP_SERVER,
38
+ MOXXY_TOOL_PREFIX,
39
+ TurnTranslator,
40
+ goalStatusFrom,
41
+ isModeChange,
42
+ toClaudeContent,
43
+ toTokenUsage,
44
+ } from './translate.js';
45
+ import { ClaudeBackgroundWork } from './background-work.js';
46
+ import { ClaudeSubagents } from './subagents.js';
47
+ import { ClaudeTaskList } from './task-list.js';
48
+ import { dueWakeup, wakeupsOf } from './scheduled-wakeups.js';
49
+
50
+ export interface ClaudeSessionSettings {
51
+ readonly sdk: ClaudeAgentSdk;
52
+ readonly cwd: string;
53
+ readonly model: string;
54
+ readonly effort?: ClaudeEffort;
55
+ /** The person's own Claude Code CLI. */
56
+ readonly executable?: string;
57
+ readonly resume?: string;
58
+ readonly permissionMode?: ClaudePermissionMode;
59
+ /** Every Moxxy tool of the conversation: Claude reads the list as it starts, and again on a notice. */
60
+ readonly tools?: ReadonlyArray<ToolDef>;
61
+ /** The conversation's Moxxy skills: Claude reads those meant for it through one more Moxxy tool. */
62
+ readonly skills?: ReadonlyArray<Skill>;
63
+ /** Claude took up a turn by itself while no Moxxy turn runs; `name` says what for, `workId` which background work ended. */
64
+ readonly onAgentTurn?: (name: string, workId?: string) => void;
65
+ /** What Claude's background work did, for the conversation to record at once: its list, a command's end, a helper's steps between turns. */
66
+ readonly onActivity?: (events: ReadonlyArray<AgentStepEvent>) => void;
67
+ }
68
+
69
+ /**
70
+ * Moxxy tools Claude Code already has its own of, so they are not lent over
71
+ * MCP: its file and shell tools, web, background jobs, questions, skills,
72
+ * memory, its own plan (ExitPlanMode) and goal (`/goal`). `recall` is lent:
73
+ * it searches Moxxy's record of the whole conversation, which outlives
74
+ * Claude's own session. The person's Moxxy skills come as a `load_skill` of
75
+ * their own, listing them (see agent-skills).
76
+ */
77
+ const CLAUDE_HAS_ITS_OWN = new Set([
78
+ 'Read', 'Edit', 'Write', 'Bash', 'Grep', 'Glob', 'Sleep', 'Wait', 'StopJob',
79
+ 'web_search', 'web_fetch', 'ask_user', 'session_recall',
80
+ 'load_skill', 'reload_skills', 'synthesize_skill', 'load_tool',
81
+ 'plan_complete', 'goal_complete', 'goal_abandon',
82
+ ]);
83
+
84
+ const toolNames = (tools: ReadonlyArray<ToolDef>) => tools.map((tool) => tool.name);
85
+
86
+ /**
87
+ * Moxxy's tools reach Claude as a catalog of three small tools. Claude lists
88
+ * every deferred tool by name in each request (hundreds once the person's MCP
89
+ * servers are set up); behind the catalog it reads the groups and looks a tool
90
+ * up when it wants one.
91
+ */
92
+ const LENT_AS = { catalog: true } as const;
93
+
94
+ export function toolsLentToClaude(tools: ReadonlyArray<ToolDef>): ToolDef[] {
95
+ return tools.filter((tool) => !CLAUDE_HAS_ITS_OWN.has(tool.name) && !tool.name.startsWith('memory_'));
96
+ }
97
+
98
+ /** Modes in which Claude acts without asking the person: `auto` lets its own classifier decide. */
99
+ export function runsWithoutAsking(mode: ClaudePermissionMode | undefined): boolean {
100
+ return mode === 'bypassPermissions' || mode === 'auto';
101
+ }
102
+
103
+ /**
104
+ * The permission mode a new Claude starts in; `undefined` keeps the mode from
105
+ * the person's Claude settings. `ownMode` is that mode when the conversation
106
+ * recorded auto-approve off: one that acts without asking is set to ask, so the
107
+ * person's switch wins over their own default.
108
+ */
109
+ export function startingPermissionMode(mode: AgentMode, autoApprove: boolean, ownMode?: ClaudePermissionMode): ClaudePermissionMode | undefined {
110
+ if (mode === 'plan') return 'plan';
111
+ if (mode === 'goal' || autoApprove) return 'bypassPermissions';
112
+ return runsWithoutAsking(ownMode) ? 'default' : undefined;
113
+ }
114
+
115
+ type Item =
116
+ | { readonly kind: 'message'; readonly message: ClaudeMessage }
117
+ | { readonly kind: 'ended'; readonly error?: string }
118
+ | {
119
+ readonly kind: 'approve';
120
+ readonly callId: string;
121
+ readonly name: string;
122
+ readonly input: Record<string, unknown>;
123
+ readonly description?: string;
124
+ /** Asked from inside one of Claude's subagents. */
125
+ readonly inSubagent: boolean;
126
+ readonly resolve: (result: ClaudePermissionResult) => void;
127
+ }
128
+ | {
129
+ readonly kind: 'hook';
130
+ readonly callId: string;
131
+ readonly name: string;
132
+ readonly input: unknown;
133
+ readonly inSubagent: boolean;
134
+ readonly resolve: (output: ClaudePreToolUseOutput) => void;
135
+ }
136
+ | { readonly kind: 'moxxy-tool'; readonly call: AgentToolCall; readonly resolve: (outcome: AgentToolOutcome) => void };
137
+
138
+ const NOT_IN_A_TURN = 'Nobody is in the Moxxy conversation right now to answer this.';
139
+ const NO_RULES_YET = 'Moxxy could not check this call against its rules: no turn has run in this conversation yet.';
140
+ /** Moxxy's record of the conversation goes first, on its own (and `/goal` must start the person's message). */
141
+ const READ_ONLY_REPLY = 'Reply with OK only: the person\'s message follows next.';
142
+ class SessionGone extends Error {}
143
+ const MAX_STDERR = 2048;
144
+ /** Where Claude's plan mode keeps the plan it writes: `~/.claude/plans/<name>.md`. */
145
+ const PLAN_FILE = /[\\/]\.claude[\\/]plans[\\/][^\\/]+\.md$/;
146
+
147
+ /** The plan file a Write or Edit of Claude's touches, if it is one. */
148
+ export function claudePlanFileOf(name: string, input: unknown): string | undefined {
149
+ if (name !== 'Write' && name !== 'Edit' && name !== 'MultiEdit') return undefined;
150
+ const path = typeof input === 'object' && input !== null ? (input as { file_path?: unknown }).file_path : undefined;
151
+ return typeof path === 'string' && PLAN_FILE.test(path) ? path : undefined;
152
+ }
153
+ /** Claude's answer for a plan the person now decides on in Moxxy: no "approved", no second copy of it. */
154
+ const PLAN_HANDED_OVER =
155
+ 'The plan is now with the person in Moxxy, who will implement it, have it rewritten or dismiss it there. ' +
156
+ 'Stay in plan mode and end your turn now without repeating the plan.';
157
+
158
+ /**
159
+ * One running Claude Code (one Agent SDK `query()`) for one Moxxy
160
+ * conversation. Every message the person sends is the next user message of
161
+ * the same query, so Claude keeps its context, tools and goal between turns.
162
+ * Everything Claude asks of Moxxy (approvals, the PreToolUse rule check,
163
+ * Moxxy tools over MCP) is queued with its messages and handled in order, so
164
+ * the log shows a call before the decision about it.
165
+ */
166
+ export class ClaudeAgentSession implements LiveSession {
167
+ private readonly input = new Inbox<ClaudeUserMessage | null>();
168
+ private readonly inbox = new Inbox<Item>();
169
+ private readonly query: ClaudeQuery;
170
+ private alive = true;
171
+ private closed = false;
172
+ private inTurn = false;
173
+ /** This turn handed Claude's plan to the plan card through ExitPlanMode. */
174
+ private planHandedOver = false;
175
+ /** A turn ended before Claude's `result` (its reader stopped early); the next turn waits it out. */
176
+ private owesResult = false;
177
+ /** Claude took up a turn by itself and no Moxxy turn has read it yet. */
178
+ private agentTurnPending = false;
179
+ /** When Claude set itself to come back, as its last `Stop` said. */
180
+ private wakeups: AgentScheduledWakeup[] = [];
181
+ /** Claude's tasks by id, named as they started, to say which one finished. */
182
+ private readonly taskNames = new Map<string, string>();
183
+ /** The task whose end Claude takes up next, once it finished in the background. */
184
+ private finishedTask: string | undefined;
185
+ /** That task as Moxxy's background work (`AgentBackgroundWork.id`). */
186
+ private finishedWork: string | undefined;
187
+ /** What Claude runs in the background, as its list says. */
188
+ private readonly background = new ClaudeBackgroundWork();
189
+ /** The last turn's host: Moxxy's rules for a call made while no turn runs (a helper in the background). */
190
+ private lastHost: AgentStepHost | undefined;
191
+ private permissionMode: ClaudePermissionMode | undefined;
192
+ /** Claude's task list, which its tools change one task at a time across turns. */
193
+ private readonly tasks = new ClaudeTaskList();
194
+ /** Claude's subagents; one in the background ends after the turn that started it. */
195
+ private readonly subagents = new ClaudeSubagents();
196
+ /** Reads a background helper's messages while no turn runs; the next turn reads them again and shows nothing twice. */
197
+ private readonly between: TurnTranslator;
198
+ /** The conversation's auto-approve as this turn knows it: as it began, then as Claude's mode changed it. */
199
+ private switchedOn = false;
200
+ private model: string;
201
+ private goalActive = false;
202
+ private stderr = '';
203
+ /** The Moxxy tools Claude is shown: every one of the conversation, the same in every mode. */
204
+ private listed: ToolDef[];
205
+ /** The Moxxy skills Claude is offered. */
206
+ private offered: Skill[];
207
+
208
+ static async start(settings: ClaudeSessionSettings): Promise<ClaudeAgentSession> {
209
+ const checked = await withoutLostSession(settings);
210
+ const mcp = await startMoxxyMcpServer({ name: 'moxxy' });
211
+ try {
212
+ return new ClaudeAgentSession(checked.settings, mcp, checked.newSession);
213
+ } catch (err) {
214
+ await mcp.close();
215
+ throw err;
216
+ }
217
+ }
218
+
219
+ private constructor(
220
+ readonly settings: ClaudeSessionSettings,
221
+ private readonly mcp: MoxxyMcpServer,
222
+ /** Claude's session is new while the conversation may already have run: its first message carries the conversation so far. */
223
+ private newSession: NewSessionReason | undefined,
224
+ ) {
225
+ this.model = settings.model;
226
+ this.permissionMode = settings.permissionMode;
227
+ this.between = new TurnTranslator(settings.cwd, this.tasks, this.subagents);
228
+ // Claude reads Moxxy's tools as it starts: they are listed before it does.
229
+ this.listed = toolsLentToClaude(settings.tools ?? []);
230
+ this.offered = skillsForAgent(settings.skills ?? [], toolNames(this.listed), []);
231
+ mcp.setHandler(idleToolsHandler(this.listed, this.offered, LENT_AS));
232
+ this.query = settings.sdk.query({
233
+ prompt: this.userMessages(),
234
+ options: {
235
+ cwd: settings.cwd,
236
+ model: settings.model,
237
+ ...(settings.effort ? { effort: settings.effort } : {}),
238
+ systemPrompt: { type: 'preset', preset: 'claude_code' },
239
+ ...(settings.executable ? { pathToClaudeCodeExecutable: settings.executable } : {}),
240
+ ...(settings.permissionMode ? { permissionMode: settings.permissionMode } : {}),
241
+ // Lets Moxxy's auto-approve switch Claude to bypassPermissions mid-session.
242
+ allowDangerouslySkipPermissions: true,
243
+ includePartialMessages: true,
244
+ ...(settings.resume ? { resume: settings.resume } : {}),
245
+ mcpServers: { [MOXXY_MCP_SERVER]: { type: 'http', url: mcp.url, headers: { Authorization: mcp.authorization } } },
246
+ canUseTool: (name, input, options) => this.onCanUseTool(name, input, options),
247
+ hooks: {
248
+ PreToolUse: [{ hooks: [async (input) => this.onPreToolUse(input.tool_name, input.tool_input, input.tool_use_id, input.agent_id !== undefined)] }],
249
+ Stop: [{ hooks: [async (input) => this.onStop(input)] }],
250
+ },
251
+ env: claudeEnv(),
252
+ stderr: (data) => {
253
+ this.stderr = (this.stderr + data).slice(-MAX_STDERR);
254
+ },
255
+ },
256
+ });
257
+ void this.pump();
258
+ }
259
+
260
+ get isAlive(): boolean {
261
+ return this.alive;
262
+ }
263
+
264
+ /** Whether this Claude was started with what the turn needs (settings a running Claude cannot change). */
265
+ fits(settings: Pick<ClaudeSessionSettings, 'effort' | 'executable' | 'cwd'>): boolean {
266
+ return (
267
+ settings.effort === this.settings.effort &&
268
+ settings.executable === this.settings.executable &&
269
+ settings.cwd === this.settings.cwd
270
+ );
271
+ }
272
+
273
+ async *turn(req: AgentStepRequest): AsyncGenerator<AgentStepEvent> {
274
+ // Claude's own turn was already read by a turn of the person's.
275
+ if (req.continuesAgentTurn && !this.agentTurnPending) return;
276
+ const ownTurn = req.continuesAgentTurn === true;
277
+ const mode = agentModeFor(req.mode);
278
+ this.inTurn = true;
279
+ this.lastHost = req.host;
280
+ this.switchedOn = req.autoApprove;
281
+ const interrupt = () => void this.query.interrupt().catch(() => undefined);
282
+ req.signal.addEventListener('abort', interrupt, { once: true });
283
+ const all = withoutOwnMcpServers(toolsLentToClaude(req.allTools ?? req.tools), await this.ownMcpServerNames());
284
+ if (!sameToolNames(all, this.listed)) this.listed = all;
285
+ try {
286
+ this.offered = skillsForAgent(req.skills ?? [], toolNames(this.listed), await this.ownSkillNames());
287
+ this.mcp.setHandler(
288
+ moxxyToolsHandler(
289
+ this.listed,
290
+ { runTool: (call) => new Promise((resolve) => this.inbox.push({ kind: 'moxxy-tool', call, resolve })) },
291
+ this.offered,
292
+ LENT_AS,
293
+ ),
294
+ );
295
+ // The conversation gained or lost a tool or a skill since Claude read the list: it reads it again on this notice.
296
+ await this.mcp.announceTools({ signal: req.signal });
297
+ if (!ownTurn) {
298
+ if (this.owesResult && !(await this.settlePrevious())) {
299
+ yield this.endedError();
300
+ return;
301
+ }
302
+ await this.align(req, mode);
303
+ const note = this.newSession ? earlierConversationNote(this.newSession, req.earlierConversation?.()) : req.missedTurns?.();
304
+ this.newSession = undefined;
305
+ const prefix = mode === 'goal' && !this.goalActive ? '/goal ' : '';
306
+ // The record goes in a message of its own: sent together, Claude took the person's message for part of the record.
307
+ if (note) await this.silently(`${note}\n\n${READ_ONLY_REPLY}`);
308
+ if (mode === 'goal') this.goalActive = true;
309
+ this.send(toClaudeContent(req.prompt, prefix));
310
+ }
311
+ const translator = new TurnTranslator(this.settings.cwd, this.tasks, this.subagents);
312
+ this.planHandedOver = false;
313
+ let planFile: string | undefined;
314
+ for (;;) {
315
+ const item = await this.inbox.next();
316
+ if (item.kind === 'ended') {
317
+ yield this.endedError(item.error);
318
+ return;
319
+ }
320
+ if (item.kind === 'message') {
321
+ if (isOwnResult(item.message, this.owesResult)) {
322
+ this.agentTurnPending = false;
323
+ this.finishedTask = undefined;
324
+ this.finishedWork = undefined;
325
+ if (ownTurn) {
326
+ yield* resultEvents(item.message, req.signal.aborted, this.model);
327
+ break;
328
+ }
329
+ }
330
+ if (isPersonResult(item.message, this.owesResult)) {
331
+ this.owesResult = false;
332
+ yield* resultEvents(item.message, req.signal.aborted, this.model);
333
+ break;
334
+ }
335
+ const reported = isInit(item.message) || isModeChange(item.message) ? item.message.permissionMode : undefined;
336
+ // Only the person lets Claude act without asking: a mode that does, set outside Moxxy while auto-approve is off, is set back.
337
+ // A mode not known yet is the person's own Claude setup, shown as it is.
338
+ const was = this.permissionMode;
339
+ const restore = reported !== undefined && was !== undefined && mode !== 'goal' && !this.switchedOn && runsWithoutAsking(reported) && !runsWithoutAsking(was);
340
+ if (restore) {
341
+ await this.setPermissionMode(was);
342
+ yield { type: 'auto_approve_restored' };
343
+ } else if (reported !== undefined) {
344
+ this.permissionMode = reported;
345
+ }
346
+ for (const event of translator.translate(item.message)) {
347
+ if (event.type === 'tool_call') planFile = claudePlanFileOf(event.name, event.input) ?? planFile;
348
+ if (event.type === 'auto_approve') {
349
+ // In goal mode Claude runs bypassPermissions for the goal, not because the person chose auto-approve.
350
+ if (mode === 'goal' || restore) continue;
351
+ this.switchedOn = event.enabled;
352
+ yield isModeChange(item.message) ? { ...event, elsewhere: true } : event;
353
+ continue;
354
+ }
355
+ yield event;
356
+ }
357
+ continue;
358
+ }
359
+ yield* this.handle(item, req, translator, mode);
360
+ }
361
+ // Claude wrote or changed its plan but ended without handing it over: it still goes on the plan card.
362
+ if (mode === 'plan' && !this.planHandedOver && planFile && !req.signal.aborted) {
363
+ const plan = await readFile(planFile, 'utf8').catch(() => '');
364
+ if (plan.trim()) yield { type: 'plan', text: plan.trim() };
365
+ }
366
+ if (mode === 'goal' && !ownTurn && !req.signal.aborted) {
367
+ const status = await this.goalStatus();
368
+ if (status === 'complete') this.goalActive = false;
369
+ if (status) yield { type: 'goal', status };
370
+ }
371
+ } finally {
372
+ req.signal.removeEventListener('abort', interrupt);
373
+ this.mcp.setHandler(idleToolsHandler(this.listed, this.offered, LENT_AS));
374
+ this.inTurn = false;
375
+ this.dismissQueued();
376
+ }
377
+ }
378
+
379
+ /** Stop one work Claude runs in the background (`AgentBackgroundWork.id`); `false` when Claude runs no such work. */
380
+ async stopWork(workId: string): Promise<boolean> {
381
+ const task = this.background.taskOf(workId);
382
+ if (task === undefined || !this.alive) return false;
383
+ await this.query.stopTask(task);
384
+ return true;
385
+ }
386
+
387
+ async close(): Promise<void> {
388
+ if (this.closed) return;
389
+ this.closed = true;
390
+ this.alive = false;
391
+ // Claude's background work ends with it.
392
+ this.report(this.background.stopped());
393
+ this.input.push(null);
394
+ this.query.close();
395
+ this.dismissQueued();
396
+ await this.mcp.close();
397
+ }
398
+
399
+ /** What Claude asked of Moxxy, answered in order with the turn's host. */
400
+ private async *handle(item: Exclude<Item, { kind: 'message' | 'ended' }>, req: AgentStepRequest, translator: TurnTranslator, mode: AgentMode): AsyncGenerator<AgentStepEvent> {
401
+ switch (item.kind) {
402
+ case 'moxxy-tool':
403
+ item.resolve(await req.host.runTool(item.call));
404
+ return;
405
+ case 'hook': {
406
+ yield* translator.announce(item.callId, item.name, item.input, { inSubagent: item.inSubagent });
407
+ const decision = await req.host.approve({ callId: item.callId, name: item.name, input: item.input, policyOnly: true });
408
+ item.resolve(
409
+ decision.allow ? {} : refusedByRules(decision.reason),
410
+ );
411
+ return;
412
+ }
413
+ case 'approve':
414
+ if (item.name === 'AskUserQuestion') {
415
+ item.resolve(await this.answerQuestion(item.input, req));
416
+ return;
417
+ }
418
+ // In Moxxy's plan mode the plan is the person's to answer on the plan card, like Codex's and OpenCode's.
419
+ if (item.name === 'ExitPlanMode' && mode === 'plan' && typeof item.input.plan === 'string') {
420
+ yield* translator.announce(item.callId, item.name, item.input, { inSubagent: item.inSubagent });
421
+ yield* translator.handOver(item.callId, 'The plan is with the person, on the plan card.');
422
+ this.planHandedOver = true;
423
+ yield { type: 'plan', text: item.input.plan };
424
+ item.resolve({ behavior: 'deny', message: PLAN_HANDED_OVER });
425
+ return;
426
+ }
427
+ yield* translator.announce(item.callId, item.name, item.input, { inSubagent: item.inSubagent });
428
+ item.resolve(await this.decide(item, req));
429
+ return;
430
+ }
431
+ }
432
+
433
+ private async decide(item: Extract<Item, { kind: 'approve' }>, req: AgentStepRequest): Promise<ClaudePermissionResult> {
434
+ const plan = item.name === 'ExitPlanMode' && typeof item.input.plan === 'string' ? item.input.plan : undefined;
435
+ const description = plan ?? item.description;
436
+ const decision = await untilStopped(
437
+ req.host.approve({ callId: item.callId, name: item.name, input: item.input, ...(description ? { description } : {}) }),
438
+ req.signal,
439
+ { allow: false as const, reason: 'The person stopped the turn.' },
440
+ );
441
+ if (!decision.allow) return { behavior: 'deny', message: decision.reason };
442
+ // An approved plan runs at once; with auto-approve on, without asking again.
443
+ if (plan !== undefined && this.switchedOn) void this.setPermissionMode('bypassPermissions');
444
+ return { behavior: 'allow', updatedInput: item.input };
445
+ }
446
+
447
+ private async answerQuestion(input: Record<string, unknown>, req: AgentStepRequest): Promise<ClaudePermissionResult> {
448
+ const items = fromClaudeQuestions(input);
449
+ const outcome = await untilStopped(req.host.ask(items), req.signal, { kind: 'dismissed' as const, reason: 'cancelled' as const });
450
+ switch (outcome.kind) {
451
+ case 'answered':
452
+ return { behavior: 'allow', updatedInput: { ...input, answers: toClaudeAnswers(items, outcome.answers) } };
453
+ case 'dismissed':
454
+ return { behavior: 'deny', message: 'The person closed the question without answering.' };
455
+ case 'unanswerable':
456
+ return {
457
+ behavior: 'deny',
458
+ message: 'Nobody is there to answer questions right now. Pick the sensible choice yourself and say which one you picked.',
459
+ };
460
+ }
461
+ }
462
+
463
+ /** Model, mode and goal as this turn wants them, changed on the running Claude. */
464
+ private async align(req: AgentStepRequest, mode: AgentMode): Promise<void> {
465
+ if (req.model && req.model !== this.model) {
466
+ await this.query.setModel(req.model);
467
+ this.model = req.model;
468
+ }
469
+ if (mode !== 'goal' && this.goalActive) {
470
+ await this.silently('/goal clear');
471
+ this.goalActive = false;
472
+ }
473
+ const wanted =
474
+ startingPermissionMode(mode, req.autoApprove) ??
475
+ (this.permissionMode === 'bypassPermissions' || this.permissionMode === 'plan' ? 'default' : undefined);
476
+ if (wanted && wanted !== this.permissionMode) await this.setPermissionMode(wanted);
477
+ }
478
+
479
+ private async setPermissionMode(mode: ClaudePermissionMode): Promise<void> {
480
+ // Known before Claude reports it back, so the report is not taken for a change made elsewhere.
481
+ this.permissionMode = mode;
482
+ await this.query.setPermissionMode(mode);
483
+ }
484
+
485
+ /** After a goal turn: ask `/goal` once whether the goal is still open. Its answer is not shown. */
486
+ private async goalStatus(): Promise<'active' | 'complete' | undefined> {
487
+ let status: 'active' | 'complete' | undefined;
488
+ await this.silently('/goal', (message) => {
489
+ if (message.type !== 'assistant' || !('message' in message)) return;
490
+ for (const block of message.message.content) {
491
+ if (block.type === 'text' && 'text' in block && typeof block.text === 'string') status = goalStatusFrom(block.text) ?? status;
492
+ }
493
+ });
494
+ return status;
495
+ }
496
+
497
+ /** Send a command and read through to its result without showing anything. */
498
+ /** Claude's own skills and commands, not its built-in ones: a Moxxy skill of the same name is left to Claude's. */
499
+ /** Claude's own MCP servers that are on: Moxxy's server of the same name is left to Claude's. */
500
+ private async ownMcpServerNames(): Promise<string[]> {
501
+ try {
502
+ const servers = await this.query.mcpServerStatus();
503
+ return servers.filter((server) => server.name !== MOXXY_MCP_SERVER && server.status !== 'disabled').map((server) => server.name);
504
+ } catch {
505
+ return [];
506
+ }
507
+ }
508
+
509
+ private async ownSkillNames(): Promise<string[]> {
510
+ try {
511
+ const commands = await this.query.supportedCommands();
512
+ return commands.filter((command) => !command.builtin).flatMap((command) => [command.name, ...(command.aliases ?? [])]);
513
+ } catch {
514
+ return [];
515
+ }
516
+ }
517
+
518
+ private async silently(text: string, onMessage?: (message: ClaudeMessage) => void): Promise<void> {
519
+ this.send(text);
520
+ for (;;) {
521
+ const item = await this.inbox.next();
522
+ if (item.kind === 'ended') return;
523
+ if (item.kind !== 'message') {
524
+ refuse(item);
525
+ continue;
526
+ }
527
+ if (isPersonResult(item.message, this.owesResult)) {
528
+ this.owesResult = false;
529
+ return;
530
+ }
531
+ onMessage?.(item.message);
532
+ }
533
+ }
534
+
535
+ /** Wait out the result of a turn whose reader stopped early, so it does not leak into this one. */
536
+ private async settlePrevious(): Promise<boolean> {
537
+ await this.query.interrupt().catch(() => undefined);
538
+ for (;;) {
539
+ const item = await this.inbox.next();
540
+ if (item.kind === 'ended') return false;
541
+ if (item.kind !== 'message') refuse(item);
542
+ else if (isPersonResult(item.message, this.owesResult)) {
543
+ this.owesResult = false;
544
+ return true;
545
+ }
546
+ }
547
+ }
548
+
549
+ private send(content: ClaudeUserContent): void {
550
+ this.owesResult = true;
551
+ this.input.push({ type: 'user', message: { role: 'user', content }, parent_tool_use_id: null, origin: { kind: 'human' } });
552
+ }
553
+
554
+ private async *userMessages(): AsyncGenerator<ClaudeUserMessage> {
555
+ for (;;) {
556
+ const message = await this.input.next();
557
+ if (message === null) return;
558
+ yield message;
559
+ }
560
+ }
561
+
562
+ private async pump(): Promise<void> {
563
+ try {
564
+ for await (const message of this.query) {
565
+ this.inbox.push({ kind: 'message', message });
566
+ this.notice(message);
567
+ }
568
+ this.inbox.push({ kind: 'ended' });
569
+ } catch (err) {
570
+ this.inbox.push({ kind: 'ended', error: err instanceof Error ? err.message : String(err) });
571
+ } finally {
572
+ this.alive = false;
573
+ this.report(this.background.stopped());
574
+ }
575
+ }
576
+
577
+ private onCanUseTool(
578
+ name: string,
579
+ input: Record<string, unknown>,
580
+ options: { readonly toolUseID?: string; readonly agentID?: string; readonly description?: string; readonly title?: string; readonly mcpServer?: { readonly name: string; readonly source: string } },
581
+ ): Promise<ClaudePermissionResult> {
582
+ // Moxxy asks about its own tools when it runs them; a second window would ask twice.
583
+ const server = options.mcpServer;
584
+ if (name.startsWith(MOXXY_TOOL_PREFIX) && server && server.name === MOXXY_MCP_SERVER && server.source === 'dynamic') {
585
+ return Promise.resolve({ behavior: 'allow', updatedInput: input });
586
+ }
587
+ if (!this.inTurn) return Promise.resolve({ behavior: 'deny', message: NOT_IN_A_TURN });
588
+ const description = options.description ?? options.title;
589
+ return new Promise((resolve) =>
590
+ this.inbox.push({
591
+ kind: 'approve',
592
+ callId: options.toolUseID ?? randomUUID(),
593
+ name,
594
+ input,
595
+ ...(description ? { description } : {}),
596
+ inSubagent: options.agentID !== undefined,
597
+ resolve,
598
+ }),
599
+ );
600
+ }
601
+
602
+ /** Claude ended a turn: what it set itself to come back for is said again, whenever it changed. */
603
+ private async onStop(input: ClaudeStopInput): Promise<Record<string, never>> {
604
+ // An older Claude does not say; nothing is listed rather than a guess.
605
+ if (input.session_crons) this.setWakeups(wakeupsOf(input.session_crons, Date.now()));
606
+ return {};
607
+ }
608
+
609
+ private setWakeups(wakeups: AgentScheduledWakeup[]): void {
610
+ if (JSON.stringify(wakeups) === JSON.stringify(this.wakeups)) return;
611
+ this.wakeups = wakeups;
612
+ this.report([{ type: 'scheduled_wakeups', wakeups }]);
613
+ }
614
+
615
+ private onPreToolUse(name: string, input: unknown, callId: string, inSubagent: boolean): Promise<ClaudePreToolUseOutput> {
616
+ if (name.startsWith(MOXXY_TOOL_PREFIX)) return Promise.resolve({});
617
+ if (!this.inTurn) return this.checkRulesBetweenTurns(name, input, callId);
618
+ return new Promise((resolve) => this.inbox.push({ kind: 'hook', callId, name, input, inSubagent, resolve }));
619
+ }
620
+
621
+ /** A call made while no turn runs (a helper in the background) still meets Moxxy's rules. */
622
+ private async checkRulesBetweenTurns(name: string, input: unknown, callId: string): Promise<ClaudePreToolUseOutput> {
623
+ const host = this.lastHost;
624
+ if (!host) return refusedByRules(NO_RULES_YET);
625
+ const decision = await host.approve({ callId, name, input, policyOnly: true });
626
+ return decision.allow ? {} : refusedByRules(decision.reason);
627
+ }
628
+
629
+ /**
630
+ * Watch what Claude sends whether or not a turn runs: which task finished,
631
+ * and Claude taking up a turn by itself (its `init` while Moxxy is idle),
632
+ * which the conversation opens a turn for.
633
+ */
634
+ private notice(message: ClaudeMessage): void {
635
+ if (message.type === 'system') {
636
+ const note = message as { subtype?: unknown; task_id?: unknown; tool_use_id?: unknown; description?: unknown };
637
+ if (note.subtype === 'task_started' && typeof note.task_id === 'string' && typeof note.description === 'string') {
638
+ this.taskNames.set(note.task_id, note.description);
639
+ }
640
+ if (note.subtype === 'task_notification' && typeof note.task_id === 'string') {
641
+ this.finishedTask = this.taskNames.get(note.task_id) ?? this.finishedTask;
642
+ this.finishedWork = this.background.workIdOf(note.task_id, typeof note.tool_use_id === 'string' ? note.tool_use_id : undefined);
643
+ void this.background.end(note).then((events) => this.report(events));
644
+ }
645
+ this.report(this.background.fromNote(note));
646
+ }
647
+ if (!this.inTurn && isBackgroundHelperNote(message)) this.report(this.between.translate(message));
648
+ if (this.closed || this.inTurn || this.owesResult || this.agentTurnPending || !isInit(message)) return;
649
+ this.agentTurnPending = true;
650
+ const due = this.finishedTask ? undefined : dueWakeup(this.wakeups, Date.now());
651
+ // A one-shot wakeup is spent once Claude comes back for it; its Stop says what is left.
652
+ if (due && !due.recurring) this.setWakeups(this.wakeups.filter((wakeup) => wakeup !== due));
653
+ const name = this.finishedTask ? `${this.finishedTask} finished in the background` : due ? 'Scheduled check-in' : 'A background task finished';
654
+ this.settings.onAgentTurn?.(name, this.finishedWork);
655
+ }
656
+
657
+ private report(events: ReadonlyArray<AgentStepEvent>): void {
658
+ if (events.length > 0) this.settings.onActivity?.(events);
659
+ }
660
+
661
+ /**
662
+ * Answer whatever is still queued once no turn can: Claude must never wait on
663
+ * Moxxy forever. What is left of a turn whose reader stopped early is dropped,
664
+ * up to its result; what Claude sent after it is its own (a helper in the
665
+ * background, a turn it took up) and stays for the next reader.
666
+ */
667
+ private dismissQueued(): void {
668
+ const kept: ClaudeMessage[] = [];
669
+ let ended: Extract<Item, { kind: 'ended' }> | undefined;
670
+ for (const item of this.inbox.drain()) {
671
+ if (item.kind === 'ended') ended = item;
672
+ else if (item.kind !== 'message') refuse(item);
673
+ else if (!this.owesResult) kept.push(item.message);
674
+ else if (isPersonResult(item.message, this.owesResult)) this.owesResult = false;
675
+ }
676
+ for (const message of kept) {
677
+ this.inbox.push({ kind: 'message', message });
678
+ this.notice(message);
679
+ }
680
+ if (ended) this.inbox.push(ended);
681
+ }
682
+
683
+ private endedError(error?: string): AgentStepEvent {
684
+ const detail = error ?? 'Claude Code stopped.';
685
+ const stderr = this.stderr.trim();
686
+ return { type: 'error', message: stderr && !detail.includes(stderr) ? `${detail}\n${stderr}` : detail, retryable: false };
687
+ }
688
+ }
689
+
690
+ /**
691
+ * The settings to start Claude with: without `resume` when Claude's session
692
+ * for this conversation no longer exists (Claude would fail every turn on it),
693
+ * so the conversation goes on in a new one. A check that keeps failing stops
694
+ * the turn rather than start over.
695
+ */
696
+ async function withoutLostSession(settings: ClaudeSessionSettings): Promise<{ settings: ClaudeSessionSettings; newSession?: NewSessionReason }> {
697
+ const { resume, sdk } = settings;
698
+ if (!resume) return { settings, newSession: 'new' };
699
+ if (!sdk.getSessionInfo) return { settings };
700
+ const resumed = await resumeAgentSession({
701
+ label: 'Claude Code',
702
+ load: async () => {
703
+ if (!(await sdk.getSessionInfo?.(resume))) throw new SessionGone(`Claude has no session ${resume}.`);
704
+ return resume;
705
+ },
706
+ gone: (error) => error instanceof SessionGone,
707
+ });
708
+ if (resumed.kind === 'loaded') return { settings };
709
+ const { resume: _lost, ...fresh } = settings;
710
+ return { settings: fresh, newSession: 'lost' };
711
+ }
712
+
713
+ function refuse(item: Exclude<Item, { kind: 'message' | 'ended' }>): void {
714
+ switch (item.kind) {
715
+ case 'approve':
716
+ item.resolve({ behavior: 'deny', message: NOT_IN_A_TURN });
717
+ return;
718
+ case 'hook':
719
+ item.resolve({});
720
+ return;
721
+ case 'moxxy-tool':
722
+ item.resolve({ ok: false, message: 'No Moxxy turn is running, so the tool cannot run now.' });
723
+ return;
724
+ }
725
+ }
726
+
727
+ function* resultEvents(message: Extract<ClaudeMessage, { type: 'result' }>, stopped: boolean, model: string): Generator<AgentStepEvent> {
728
+ if (message.usage) yield { type: 'usage', usage: toTokenUsage(message.usage) };
729
+ const tokens = contextWindowOf(message.modelUsage, model);
730
+ if (tokens !== undefined) yield { type: 'context_window', model, tokens };
731
+ if (!message.is_error || stopped) return;
732
+ const detail = message.errors && message.errors.length > 0 ? message.errors.join('; ') : (message.result ?? message.subtype);
733
+ yield { type: 'error', message: `Claude Code: ${detail}`, retryable: false };
734
+ }
735
+
736
+ /**
737
+ * The window Claude ran the model with. `modelUsage` is keyed by the model string Claude
738
+ * used (`claude-opus-5-5[1m]`) and also lists helper models, so match the turn's own.
739
+ */
740
+ function contextWindowOf(usage: Readonly<Record<string, ClaudeModelUsage>> | undefined, model: string): number | undefined {
741
+ if (!usage) return undefined;
742
+ for (const [key, entry] of Object.entries(usage)) {
743
+ const named = key === model || key.replace(/\[[^\]]*\]$/, '') === model || entry.canonicalModel === model;
744
+ if (named && isContextWindowSize(entry.contextWindow)) return entry.contextWindow;
745
+ }
746
+ return undefined;
747
+ }
748
+
749
+ /** The `result` of a turn Claude took up by itself. */
750
+ function isOwnResult(message: ClaudeMessage, owed: boolean): message is Extract<ClaudeMessage, { type: 'result' }> {
751
+ return message.type === 'result' && 'is_error' in message && !isPersonResult(message, owed);
752
+ }
753
+
754
+ function refusedByRules(reason: string): ClaudePreToolUseOutput {
755
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } };
756
+ }
757
+
758
+ /**
759
+ * The `result` of the person's turn. A turn Claude started itself is not: one after a background
760
+ * task carries its origin, but one it woke itself up for (ScheduleWakeup, /loop) carries none, so
761
+ * a result without an origin is the person's only while Moxxy waits for one (`owed`), as from
762
+ * a Claude too old to send origins.
763
+ */
764
+ function isPersonResult(message: ClaudeMessage, owed: boolean): message is Extract<ClaudeMessage, { type: 'result' }> {
765
+ if (message.type !== 'result' || !('is_error' in message)) return false;
766
+ const origin = (message as { origin?: { kind?: string } }).origin;
767
+ return origin === undefined ? owed : origin.kind === 'human';
768
+ }
769
+
770
+ /** A background helper's own message, or Claude's report on one of its tasks. */
771
+ function isBackgroundHelperNote(message: ClaudeMessage): boolean {
772
+ if (message.type === 'assistant') return message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined;
773
+ return message.type === 'system' && 'subtype' in message && (message.subtype === 'task_progress' || message.subtype === 'task_notification');
774
+ }
775
+
776
+ function isInit(message: ClaudeMessage): message is Extract<ClaudeMessage, { subtype: 'init' }> {
777
+ return message.type === 'system' && 'subtype' in message && message.subtype === 'init';
778
+ }
779
+
780
+ /**
781
+ * The environment for Claude Code: Moxxy's own, without the markers that make
782
+ * Claude refuse to start as a nested session when Moxxy itself was launched
783
+ * from Claude Code. The SDK replaces the environment, so it is spread here.
784
+ */
785
+ export function claudeEnv(): Record<string, string | undefined> {
786
+ const env: Record<string, string | undefined> = { ...process.env, CLAUDE_AGENT_SDK_CLIENT_APP: 'moxxy' };
787
+ delete env.CLAUDECODE;
788
+ delete env.CLAUDE_CODE_ENTRYPOINT;
789
+ return env;
790
+ }