@moxxy/plugin-provider-claude-code 0.44.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
package/src/index.ts CHANGED
@@ -1,42 +1,63 @@
1
+ import { homedir } from 'node:os';
1
2
  import { defineProvider, definePlugin, MoxxyError } from '@moxxy/sdk';
2
- import { CLAUDE_CODE_PROVIDER_ID, CLAUDE_CODE_SERVICE_NAME } from './constants.js';
3
+ import { CLAUDE_CLI, checkAgentCli } from '@moxxy/agent-connection-kit';
4
+ import { CLAUDE_AGENT_NAME, CLAUDE_CODE_PROVIDER_ID, CLAUDE_CODE_SERVICE_NAME } from './constants.js';
3
5
  import {
4
- CLAUDE_CODE_DEFAULT_MODEL,
6
+ CLAUDE_CODE_STARTER_MODEL,
5
7
  claudeCodeModels,
8
+ claudeSessions,
6
9
  createClaudeCodeClient,
7
- type ClaudeCodeProviderConfig,
8
- } from './provider.js';
10
+ type ClaudeAgentProviderConfig,
11
+ } from './agent-provider.js';
12
+ import { claudeForSdk } from './executable.js';
9
13
  import {
10
14
  claudeLogin,
11
15
  claudeLogout,
16
+ claudeSignIn,
12
17
  claudeStatus,
13
18
  checkClaudeCliAuth,
14
19
  resolveClaudeExecutable,
15
20
  } from './login.js';
21
+ import { claudeOwnAutoApprove } from './own-settings.js';
22
+ import { claudeOfferedModels } from './offered-models.js';
23
+ import { ensureClaudeAgentSdk, installedClaudeAgentSdk } from './sdk-install.js';
16
24
 
17
25
  export const claudeCodeProviderDef = defineProvider({
18
26
  name: CLAUDE_CODE_PROVIDER_ID,
27
+ agentName: CLAUDE_AGENT_NAME,
19
28
  models: claudeCodeModels,
20
- createClient: (config) => createClaudeCodeClient({
21
- ...(config as ClaudeCodeProviderConfig),
22
- defaultModel:
23
- typeof (config as { model?: unknown }).model === 'string'
24
- ? (config as { model: string }).model
25
- : (config as ClaudeCodeProviderConfig).defaultModel ?? CLAUDE_CODE_DEFAULT_MODEL,
26
- }),
29
+ starterModel: CLAUDE_CODE_STARTER_MODEL,
30
+ agentCli: {
31
+ check: (opts) => {
32
+ const command = resolveClaudeExecutable();
33
+ return checkAgentCli(CLAUDE_CLI, { command, refresh: opts?.refresh === true }, { signIn: () => claudeSignIn(command) });
34
+ },
35
+ // The SDK is installed when the connection is first used, never just to list models; until then the built-in list stands.
36
+ models: async () => {
37
+ const sdk = await installedClaudeAgentSdk();
38
+ if (!sdk) return [];
39
+ const executable = claudeForSdk(resolveClaudeExecutable());
40
+ return claudeOfferedModels({ sdk, cwd: homedir(), ...(executable ? { executable } : {}) });
41
+ },
42
+ },
43
+ ownAutoApprove: ({ cwd }) => claudeOwnAutoApprove(cwd),
44
+ createClient: (config) => createClaudeCodeClient(providerConfigFrom(config)),
27
45
  async resolveCredentials({ providerConfig, host }) {
28
46
  const config = { ...providerConfig, cwd: host.cwd };
29
- const executable = resolveClaudeExecutable(config);
30
- const status = await checkClaudeCliAuth(executable);
47
+ const command = resolveClaudeExecutable(config);
48
+ const status = await checkClaudeCliAuth(command);
31
49
  if (status.state !== 'signed-in') {
32
50
  throw new MoxxyError({
33
51
  code: status.state === 'signed-out' ? 'AUTH_NO_CREDENTIALS' : 'AUTH_INVALID',
34
52
  message: status.message,
35
53
  hint: status.state === 'signed-out' ? `Run \`moxxy login ${CLAUDE_CODE_PROVIDER_ID}\`.` : undefined,
36
- context: { provider: CLAUDE_CODE_PROVIDER_ID, executable, state: status.state },
54
+ context: { provider: CLAUDE_CODE_PROVIDER_ID, executable: command, state: status.state },
37
55
  });
38
56
  }
39
- return { ...config, executable };
57
+ // The Agent SDK is fetched the first time the Claude connection is used, not with Moxxy.
58
+ await ensureClaudeAgentSdk();
59
+ const executable = claudeForSdk(command);
60
+ return { ...config, ...(executable ? { executable } : {}) };
40
61
  },
41
62
  // No validateKey: readiness is reported by the installed Claude CLI.
42
63
  auth: {
@@ -52,19 +73,37 @@ export const claudeCodePlugin = definePlugin({
52
73
  name: '@moxxy/plugin-provider-claude-code',
53
74
  version: '0.0.0',
54
75
  providers: [claudeCodeProviderDef],
76
+ hooks: {
77
+ // The conversation's Claude ends with it; Claude's own session stays on disk to resume.
78
+ onShutdown: (ctx) => claudeSessions().close(String(ctx.sessionId)),
79
+ },
55
80
  });
56
81
 
57
82
  export default claudeCodePlugin;
58
83
 
84
+ function providerConfigFrom(config: Readonly<Record<string, unknown>>): ClaudeAgentProviderConfig {
85
+ const text = (key: string) => (typeof config[key] === 'string' && config[key] !== '' ? (config[key] as string) : undefined);
86
+ const executable = text('executable');
87
+ const model = text('model');
88
+ const defaultModel = text('defaultModel');
89
+ const cwd = text('cwd');
90
+ return {
91
+ ...(executable ? { executable } : {}),
92
+ ...(model ? { model } : {}),
93
+ ...(defaultModel ? { defaultModel } : {}),
94
+ ...(cwd ? { cwd } : {}),
95
+ };
96
+ }
97
+
59
98
  export {
60
99
  CLAUDE_CODE_PROVIDER_ID,
61
100
  CLAUDE_CODE_SERVICE_NAME,
62
- CLAUDE_CODE_SYSTEM,
63
101
  CLAUDE_CODE_EXECUTABLE_ENV,
64
102
  } from './constants.js';
65
103
  export {
66
104
  claudeLogin,
67
105
  claudeLogout,
106
+ claudeSignIn,
68
107
  claudeStatus,
69
108
  checkClaudeCliAuth,
70
109
  resolveClaudeExecutable,
@@ -75,7 +114,11 @@ export {
75
114
  } from './login.js';
76
115
  export {
77
116
  CLAUDE_CODE_DEFAULT_MODEL,
117
+ CLAUDE_CODE_STARTER_MODEL,
118
+ ClaudeAgentProvider,
78
119
  claudeCodeModels,
120
+ claudeSessions,
79
121
  createClaudeCodeClient,
80
- type ClaudeCodeProviderConfig,
81
- } from './provider.js';
122
+ type ClaudeAgentProviderConfig,
123
+ } from './agent-provider.js';
124
+ export { CLAUDE_AGENT_SDK_VERSION, claudeAgentSdkHome, ensureClaudeAgentSdk } from './sdk-install.js';
package/src/login.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { spawn, type SpawnOptions } from 'node:child_process';
2
+ import type { AgentSignIn } from '@moxxy/agent-connection-kit';
2
3
  import { MoxxyError } from '@moxxy/sdk';
3
4
  import type {
4
5
  ProviderAuthContext,
@@ -12,6 +13,7 @@ import {
12
13
  CLAUDE_CODE_EXECUTABLE_ENV,
13
14
  CLAUDE_CODE_PROVIDER_ID,
14
15
  } from './constants.js';
16
+ import { CLAUDE_CLI, findAgentCli } from '@moxxy/agent-connection-kit';
15
17
 
16
18
  export type ClaudeCliAuthState = 'signed-in' | 'signed-out' | 'missing' | 'unsupported' | 'error';
17
19
 
@@ -113,6 +115,12 @@ export async function checkClaudeCliAuth(executable = resolveClaudeExecutable())
113
115
  };
114
116
  }
115
117
 
118
+ /** Who Claude is signed in as, for the connection's row. */
119
+ export async function claudeSignIn(executable = resolveClaudeExecutable()): Promise<AgentSignIn> {
120
+ const status = await checkClaudeCliAuth(executable);
121
+ return { signedIn: status.state === 'signed-in', ...(status.accountId ? { account: status.accountId } : {}) };
122
+ }
123
+
116
124
  export async function claudeLogin(ctx: ProviderAuthContext): Promise<ProviderOAuthResult> {
117
125
  const executable = resolveClaudeExecutable(ctx.providerConfig);
118
126
  let status = await checkClaudeCliAuth(executable);
@@ -205,7 +213,8 @@ async function runCommand(
205
213
  const spawnOptions: SpawnOptions = options.inherit
206
214
  ? { stdio: 'inherit' }
207
215
  : { stdio: [relay ? 'pipe' : 'ignore', 'pipe', 'pipe'] };
208
- const child = spawn(executable, [...args], spawnOptions);
216
+ // Where Claude's installer puts it counts too: a desktop app often starts without the shell's PATH.
217
+ const child = spawn(findAgentCli(CLAUDE_CLI, { command: executable }) ?? executable, [...args], spawnOptions);
209
218
  let stdout = '';
210
219
  let stderr = '';
211
220
  let askedForCode = false;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The models the person's Claude offers their account, as its own picker lists
3
+ * them: an Agent SDK `query()` that is sent no message answers
4
+ * `supportedModels()` and is closed, so no turn runs and no usage is spent.
5
+ * The list is a recorded SDK 0.3.296 answer; the SDK is the external boundary.
6
+ */
7
+ import { readFileSync } from 'node:fs';
8
+ import { describe, expect, it } from 'vitest';
9
+ import { FakeClaude } from './fake-claude.testkit.js';
10
+ import { claudeOfferedModels } from './offered-models.js';
11
+ import type { ClaudeModelInfo } from './sdk-types.js';
12
+
13
+ const recorded = JSON.parse(
14
+ readFileSync(new URL('./fixtures/claude-supported-models-0.3.296.json', import.meta.url), 'utf8'),
15
+ ) as { models: ReadonlyArray<ClaudeModelInfo> };
16
+ const nothing = async () => undefined;
17
+
18
+ function claude(models: ReadonlyArray<ClaudeModelInfo> = recorded.models): FakeClaude {
19
+ const fake = new FakeClaude(nothing);
20
+ fake.models = models;
21
+ return fake;
22
+ }
23
+
24
+ describe("the models the person's Claude offers", () => {
25
+ it('lists each model once by its full id, current ones first, and sends Claude nothing', async () => {
26
+ const sdk = claude();
27
+
28
+ const models = await claudeOfferedModels({ sdk, cwd: '/work/app' });
29
+
30
+ expect(models.map((m) => m.id).slice(0, 4)).toEqual(['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-fable-5-1', 'claude-haiku-5-5']);
31
+ expect(new Set(models.map((m) => m.id)).size).toBe(models.length);
32
+ expect(models.map((m) => m.id)).not.toContain('default');
33
+ expect(sdk.last.options.cwd).toBe('/work/app');
34
+ expect(sdk.last.closed).toBe(true);
35
+ });
36
+
37
+ it('starts Claude from the CLI the connection uses', async () => {
38
+ const sdk = claude();
39
+
40
+ await claudeOfferedModels({ sdk, cwd: '/work/app', executable: '/usr/local/bin/claude' });
41
+
42
+ expect(sdk.last.options.pathToClaudeCodeExecutable).toBe('/usr/local/bin/claude');
43
+ });
44
+
45
+ it('keeps what Moxxy knows of a model and describes a new one as an agent model', async () => {
46
+ const sdk = claude([
47
+ { value: 'opus', resolvedModel: 'claude-opus-5-5', displayName: 'Opus 5.5', description: '' },
48
+ { value: 'claude-opus-6', displayName: 'Opus 6', description: '', supportsFastMode: true },
49
+ ]);
50
+
51
+ const [opus, next] = await claudeOfferedModels({ sdk, cwd: '/work/app' });
52
+
53
+ expect(opus).toMatchObject({ id: 'claude-opus-5-5', contextWindow: 1_000_000, supportsTools: true });
54
+ expect(next).toMatchObject({ id: 'claude-opus-6', supportsTools: true, supportsImages: true, supportsReasoning: true, supportsFast: true });
55
+ expect(next?.contextWindow).toBe(400_000);
56
+ });
57
+
58
+ it('knows Haiku 5.5 has a 1M window and 128k of output', async () => {
59
+ const sdk = claude([{ value: 'haiku', resolvedModel: 'claude-haiku-5-5', displayName: 'Haiku 5.5', description: '' }]);
60
+
61
+ const [haiku] = await claudeOfferedModels({ sdk, cwd: '/work/app' });
62
+
63
+ expect(haiku).toMatchObject({ id: 'claude-haiku-5-5', contextWindow: 1_000_000, maxOutputTokens: 128_000 });
64
+ });
65
+
66
+ it('closes Claude even when it cannot list its models', async () => {
67
+ const sdk = claude();
68
+ sdk.models = new Error('Claude exited');
69
+
70
+ await expect(claudeOfferedModels({ sdk, cwd: '/work/app' })).rejects.toThrow(/Claude exited/);
71
+ expect(sdk.last.closed).toBe(true);
72
+ });
73
+ });
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The models the person's Claude offers their account, as its own picker lists
3
+ * them. An Agent SDK `query()` that is sent no message answers
4
+ * `supportedModels()` and is closed, so no turn runs and no usage is spent.
5
+ */
6
+ import type { ModelDescriptor } from '@moxxy/sdk';
7
+ import { claudeCodeModels } from './agent-provider.js';
8
+ import type { ClaudeAgentSdk, ClaudeModelInfo, ClaudeUserMessage } from './sdk-types.js';
9
+
10
+ /** `supportedModels` says nothing of the window; a model Moxxy does not know gets this one. */
11
+ const UNKNOWN_MODEL: Omit<ModelDescriptor, 'id'> = {
12
+ contextWindow: 400_000,
13
+ maxOutputTokens: 128_000,
14
+ supportsTools: true,
15
+ supportsStreaming: true,
16
+ supportsImages: true,
17
+ supportsDocuments: true,
18
+ supportsAudio: false,
19
+ supportsReasoning: true,
20
+ hostedTools: ['web_search'],
21
+ };
22
+
23
+ export async function claudeOfferedModels(opts: {
24
+ readonly sdk: ClaudeAgentSdk;
25
+ readonly cwd: string;
26
+ readonly executable?: string;
27
+ }): Promise<ReadonlyArray<ModelDescriptor>> {
28
+ const query = opts.sdk.query({
29
+ prompt: noMessages(),
30
+ options: {
31
+ cwd: opts.cwd,
32
+ systemPrompt: '',
33
+ ...(opts.executable ? { pathToClaudeCodeExecutable: opts.executable } : {}),
34
+ },
35
+ });
36
+ try {
37
+ const models: ModelDescriptor[] = [];
38
+ for (const info of await query.supportedModels()) {
39
+ const id = info.resolvedModel ?? info.value;
40
+ if (info.value === 'default' || models.some((model) => model.id === id)) continue;
41
+ models.push(describe(id, info));
42
+ }
43
+ return models;
44
+ } finally {
45
+ query.close();
46
+ }
47
+ }
48
+
49
+ function describe(id: string, info: ClaudeModelInfo): ModelDescriptor {
50
+ const known = claudeCodeModels.find((model) => model.id === id);
51
+ return { ...(known ?? UNKNOWN_MODEL), id, ...(info.supportsFastMode ? { supportsFast: true } : {}) };
52
+ }
53
+
54
+ /** A prompt that never sends: the query stays open only to answer the model list. */
55
+ async function* noMessages(): AsyncIterable<ClaudeUserMessage> {
56
+ await new Promise<never>(() => undefined);
57
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * The person's own Claude settings decide how a Claude Moxxy starts runs when
3
+ * Moxxy names no mode. Moxxy reads them the way Claude does (the SDK's own
4
+ * resolver, with its trust filter for a mode a repository sets), so the
5
+ * conversation's auto-approve is the truth before Claude ever starts. The SDK
6
+ * is the external boundary.
7
+ */
8
+ import { existsSync, mkdtempSync, readdirSync } from 'node:fs';
9
+ import { tmpdir } from 'node:os';
10
+ import path from 'node:path';
11
+ import { afterEach, describe, expect, it } from 'vitest';
12
+ import { removeDirSync } from '@moxxy/vitest-preset/fs';
13
+ import { FakeClaude } from './fake-claude.testkit.js';
14
+ import { claudeOwnAutoApprove, ownPermissionMode } from './own-settings.js';
15
+ import { installedClaudeAgentSdk } from './sdk-install.js';
16
+ import type { ClaudeAgentSdk } from './sdk-types.js';
17
+
18
+ const nothing = async function* () {};
19
+ const roots: string[] = [];
20
+ afterEach(() => {
21
+ for (const root of roots.splice(0)) removeDirSync(root);
22
+ });
23
+
24
+ describe("the person's own Claude mode", () => {
25
+ it('is the default mode Claude would honor for the folder', async () => {
26
+ const claude = new FakeClaude(nothing, 'bypassPermissions');
27
+
28
+ expect(await ownPermissionMode(claude, '/work/app')).toBe('bypassPermissions');
29
+ expect(claude.settingsRead).toEqual(['/work/app']);
30
+ });
31
+
32
+ it('leaves out a mode the trust filter drops, as Claude does for one a repository sets', async () => {
33
+ const claude = new FakeClaude(nothing, 'bypassPermissions');
34
+ claude.fromRepository = true;
35
+
36
+ expect(await ownPermissionMode(claude, '/work/app')).toBeUndefined();
37
+ });
38
+
39
+ it('is unknown with an SDK that cannot resolve settings, or when resolving fails', async () => {
40
+ const old: ClaudeAgentSdk = { query: () => ({}) as never };
41
+ const broken = new FakeClaude(nothing, 'bypassPermissions');
42
+ broken.settingsError = new Error('managed settings unreadable');
43
+
44
+ expect(await ownPermissionMode(old, '/work/app')).toBeUndefined();
45
+ expect(await ownPermissionMode(broken, '/work/app')).toBeUndefined();
46
+ });
47
+ });
48
+
49
+ describe("the auto-approve of the person's own Claude", () => {
50
+ it('is on for bypass permissions, off for a mode that asks, and unknown for one Moxxy has no switch for', async () => {
51
+ const own = (mode: ConstructorParameters<typeof FakeClaude>[1]) =>
52
+ claudeOwnAutoApprove('/work/app', { load: async () => new FakeClaude(nothing, mode) });
53
+
54
+ expect(await own('bypassPermissions')).toBe(true);
55
+ expect(await own('acceptEdits')).toBe(false);
56
+ expect(await own('auto')).toBeUndefined();
57
+ });
58
+
59
+ it('is unknown, and installs nothing, while the SDK is not installed yet', async () => {
60
+ const home = mkdtempSync(path.join(tmpdir(), 'moxxy-claude-own-'));
61
+ roots.push(home);
62
+
63
+ expect(await installedClaudeAgentSdk({ home })).toBeUndefined();
64
+ expect(await claudeOwnAutoApprove('/work/app', { load: async () => undefined })).toBeUndefined();
65
+ expect(readdirSync(home)).toEqual([]);
66
+ expect(existsSync(path.join(home, '0.3.296'))).toBe(false);
67
+ });
68
+ });
@@ -0,0 +1,33 @@
1
+ /**
2
+ * How the person's own Claude runs when Moxxy names no mode, read the way
3
+ * Claude reads it: its settings merged across tiers, with the trust filter
4
+ * that drops an escalating mode a repository sets.
5
+ */
6
+ import { installedClaudeAgentSdk } from './sdk-install.js';
7
+ import type { ClaudeAgentSdk, ClaudePermissionMode } from './sdk-types.js';
8
+ import { autoApproveFor } from './translate.js';
9
+
10
+ /** The mode the person's own Claude starts in for `cwd`; `undefined` when their settings name none or cannot be read. */
11
+ export async function ownPermissionMode(sdk: ClaudeAgentSdk, cwd: string): Promise<ClaudePermissionMode | undefined> {
12
+ if (!sdk.resolveSettings || !sdk.filterEscalatingDefaultMode) return undefined;
13
+ try {
14
+ return sdk.filterEscalatingDefaultMode(await sdk.resolveSettings({ cwd })).permissions?.defaultMode;
15
+ } catch {
16
+ return undefined;
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Whether the person's own Claude acts without asking in `cwd`. Unknown while
22
+ * the SDK is not installed (it is installed when the connection is first used,
23
+ * never just to read this) and for a mode Moxxy's switch does not stand for.
24
+ */
25
+ export async function claudeOwnAutoApprove(
26
+ cwd: string,
27
+ opts: { readonly load?: () => Promise<ClaudeAgentSdk | undefined> } = {},
28
+ ): Promise<boolean | undefined> {
29
+ const sdk = await (opts.load ?? (() => installedClaudeAgentSdk()))().catch(() => undefined);
30
+ if (!sdk) return undefined;
31
+ const mode = await ownPermissionMode(sdk, cwd);
32
+ return mode === undefined ? undefined : autoApproveFor(mode);
33
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Claude's AskUserQuestion shown as a Moxxy Question, and the person's answer
3
+ * handed back the way Claude reads it (keyed by the question text, labels
4
+ * joined, an answer of their own as written).
5
+ */
6
+ import { describe, expect, it } from 'vitest';
7
+ import { fromClaudeQuestions, toClaudeAnswers } from './questions.js';
8
+
9
+ const asked = {
10
+ questions: [
11
+ {
12
+ question: 'Which colour should the button be?',
13
+ header: 'Button colour',
14
+ multiSelect: false,
15
+ options: [
16
+ { label: 'Red', description: 'Make the button red.' },
17
+ { label: 'Blue', description: 'Make the button blue.' },
18
+ ],
19
+ },
20
+ { question: 'Which sizes?', header: 'Sizes', multiSelect: true, options: [{ label: 'S' }, { label: 'M' }, { label: 'L' }] },
21
+ ],
22
+ };
23
+
24
+ describe('a Claude question in Moxxy', () => {
25
+ it('keeps the question, its tag, its options and whether several fit; an answer of their own is always allowed', () => {
26
+ expect(fromClaudeQuestions(asked)).toEqual([
27
+ {
28
+ id: 'q0',
29
+ header: 'Button colour',
30
+ question: 'Which colour should the button be?',
31
+ options: [
32
+ { id: 'q0o0', label: 'Red', description: 'Make the button red.' },
33
+ { id: 'q0o1', label: 'Blue', description: 'Make the button blue.' },
34
+ ],
35
+ multiSelect: false,
36
+ allowOther: true,
37
+ },
38
+ {
39
+ id: 'q1',
40
+ header: 'Sizes',
41
+ question: 'Which sizes?',
42
+ options: [
43
+ { id: 'q1o0', label: 'S' },
44
+ { id: 'q1o1', label: 'M' },
45
+ { id: 'q1o2', label: 'L' },
46
+ ],
47
+ multiSelect: true,
48
+ allowOther: true,
49
+ },
50
+ ]);
51
+ });
52
+
53
+ it('reads nothing it cannot show', () => {
54
+ expect(fromClaudeQuestions({ questions: 'no' })).toEqual([]);
55
+ expect(fromClaudeQuestions(null)).toEqual([]);
56
+ });
57
+
58
+ it('hands the answers back keyed by the question, as Claude expects', () => {
59
+ const items = fromClaudeQuestions(asked);
60
+
61
+ expect(
62
+ toClaudeAnswers(items, {
63
+ q0: { selected: [], other: 'Teal, my own answer' },
64
+ q1: { selected: ['q1o0', 'q1o2'] },
65
+ }),
66
+ ).toEqual({ 'Which colour should the button be?': 'Teal, my own answer', 'Which sizes?': 'S, L' });
67
+ });
68
+ });
@@ -0,0 +1,45 @@
1
+ import type { QuestionAnswers, QuestionItem } from '@moxxy/sdk';
2
+
3
+ interface ClaudeQuestion {
4
+ readonly question?: unknown;
5
+ readonly header?: unknown;
6
+ readonly multiSelect?: unknown;
7
+ readonly options?: ReadonlyArray<{ readonly label?: unknown; readonly description?: unknown }>;
8
+ }
9
+
10
+ /** Claude's AskUserQuestion input as Moxxy Questions. Claude adds "Other" itself, so an own answer always fits. */
11
+ export function fromClaudeQuestions(input: unknown): QuestionItem[] {
12
+ const questions = (input as { questions?: unknown } | null)?.questions;
13
+ if (!Array.isArray(questions)) return [];
14
+ return (questions as ReadonlyArray<ClaudeQuestion>).flatMap((q, i) => {
15
+ if (typeof q.question !== 'string') return [];
16
+ const id = `q${i}`;
17
+ return [
18
+ {
19
+ id,
20
+ ...(typeof q.header === 'string' ? { header: q.header } : {}),
21
+ question: q.question,
22
+ options: (q.options ?? []).flatMap((option, j) =>
23
+ typeof option.label === 'string'
24
+ ? [{ id: `${id}o${j}`, label: option.label, ...(typeof option.description === 'string' ? { description: option.description } : {}) }]
25
+ : [],
26
+ ),
27
+ multiSelect: q.multiSelect === true,
28
+ allowOther: true,
29
+ },
30
+ ];
31
+ });
32
+ }
33
+
34
+ /** The person's answers keyed by question text: chosen labels joined, an own answer as written. */
35
+ export function toClaudeAnswers(items: ReadonlyArray<QuestionItem>, answers: QuestionAnswers): Record<string, string> {
36
+ const out: Record<string, string> = {};
37
+ for (const item of items) {
38
+ const answer = answers[item.id];
39
+ if (!answer) continue;
40
+ const labels = item.options.filter((option) => answer.selected.includes(option.id)).map((option) => option.label);
41
+ if (answer.other) labels.push(answer.other);
42
+ out[item.question] = labels.join(', ');
43
+ }
44
+ return out;
45
+ }
@@ -0,0 +1,41 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { dueWakeup, wakeupsOf } from './scheduled-wakeups.js';
3
+
4
+ const at = (h: number, m: number, s = 0) => new Date(2026, 9, 24, h, m, s).getTime();
5
+
6
+ describe("Claude's crons as scheduled wakeups", () => {
7
+ it('reads a one-shot wakeup as the time it comes back, in this computer\'s time', () => {
8
+ const [wakeup] = wakeupsOf([{ id: 'c1', schedule: '59 22 24 10 *', recurring: false, prompt: 'check CI' }], at(22, 57, 35));
9
+ expect(wakeup).toEqual({ id: 'c1', prompt: 'check CI', dueAtMs: at(22, 59), recurring: false });
10
+ });
11
+
12
+ it('keeps a wakeup firing this minute at now, not a year on', () => {
13
+ const [wakeup] = wakeupsOf([{ id: 'c1', schedule: '59 22 24 10 *', recurring: false, prompt: 'check CI' }], at(22, 59, 2));
14
+ expect(wakeup?.dueAtMs).toBe(at(22, 59));
15
+ });
16
+
17
+ it('reads a recurring one as its next fire', () => {
18
+ const [wakeup] = wakeupsOf([{ id: 'c2', schedule: '*/5 * * * *', recurring: true, prompt: 'poll' }], at(10, 1, 30));
19
+ expect(wakeup).toMatchObject({ dueAtMs: at(10, 5), recurring: true });
20
+ });
21
+
22
+ it('says nothing of the time for a schedule it cannot read', () => {
23
+ expect(wakeupsOf([{ id: 'c3', schedule: 'soon', recurring: false, prompt: 'x' }], at(10, 0))[0]?.dueAtMs).toBeNull();
24
+ });
25
+
26
+ it('names a /loop wakeup by what it does, without the command', () => {
27
+ expect(wakeupsOf([{ id: 'c4', schedule: '0 11 24 10 *', recurring: false, prompt: '/loop Check CI on main' }], at(10, 0))[0]?.prompt).toBe('Check CI on main');
28
+ });
29
+
30
+ it('finds the wakeup coming back now, and none that is still ahead', () => {
31
+ const wakeups = wakeupsOf(
32
+ [
33
+ { id: 'now', schedule: '59 22 24 10 *', recurring: false, prompt: 'a' },
34
+ { id: 'later', schedule: '30 23 24 10 *', recurring: false, prompt: 'b' },
35
+ ],
36
+ at(22, 58),
37
+ );
38
+ expect(dueWakeup(wakeups, at(22, 59, 1))?.id).toBe('now');
39
+ expect(dueWakeup(wakeups, at(22, 58, 30))).toBeUndefined();
40
+ });
41
+ });
@@ -0,0 +1,34 @@
1
+ import type { AgentScheduledWakeup } from '@moxxy/sdk';
2
+ import { nextFireTime } from '@moxxy/sdk/cron';
3
+ import type { ClaudeSessionCron } from './sdk-types.js';
4
+
5
+ /** How long after its fire time Claude may take up the turn for a wakeup, and how early. */
6
+ const LATE_MS = 60_000;
7
+ const EARLY_MS = 5_000;
8
+
9
+ /**
10
+ * Claude's crons as Moxxy shows them: when each comes back next, read from its
11
+ * schedule in this computer's time (Claude's crons run in local time).
12
+ */
13
+ export function wakeupsOf(crons: ReadonlyArray<ClaudeSessionCron>, nowMs: number): AgentScheduledWakeup[] {
14
+ return crons.map((cron) => ({
15
+ id: cron.id,
16
+ prompt: cron.prompt.replace(/^\/loop\s+/, ''),
17
+ dueAtMs: dueAt(cron.schedule, nowMs),
18
+ recurring: cron.recurring,
19
+ }));
20
+ }
21
+
22
+ /** The wakeup Claude comes back for now, if one is due. */
23
+ export function dueWakeup(wakeups: ReadonlyArray<AgentScheduledWakeup>, nowMs: number): AgentScheduledWakeup | undefined {
24
+ return wakeups.find((wakeup) => wakeup.dueAtMs !== null && wakeup.dueAtMs <= nowMs + EARLY_MS && wakeup.dueAtMs >= nowMs - LATE_MS);
25
+ }
26
+
27
+ function dueAt(schedule: string, nowMs: number): number | null {
28
+ try {
29
+ // From a minute back, so a one-shot wakeup firing this minute reads as now, not as next year.
30
+ return nextFireTime(schedule, new Date(nowMs - 60_000))?.getTime() ?? null;
31
+ } catch {
32
+ return null;
33
+ }
34
+ }