@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.
- package/dist/account-limit.d.ts +8 -0
- package/dist/account-limit.d.ts.map +1 -0
- package/dist/account-limit.js +23 -0
- package/dist/account-limit.js.map +1 -0
- package/dist/agent-provider.d.ts +61 -0
- package/dist/agent-provider.d.ts.map +1 -0
- package/dist/agent-provider.js +195 -0
- package/dist/agent-provider.js.map +1 -0
- package/dist/agent-session.d.ts +145 -0
- package/dist/agent-session.d.ts.map +1 -0
- package/dist/agent-session.js +700 -0
- package/dist/agent-session.js.map +1 -0
- package/dist/background-work.d.ts +42 -0
- package/dist/background-work.d.ts.map +1 -0
- package/dist/background-work.js +140 -0
- package/dist/background-work.js.map +1 -0
- package/dist/constants.d.ts +2 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +2 -2
- package/dist/constants.js.map +1 -1
- package/dist/executable.d.ts +15 -0
- package/dist/executable.d.ts.map +1 -0
- package/dist/executable.js +30 -0
- package/dist/executable.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +55 -16
- package/dist/index.js.map +1 -1
- package/dist/login.d.ts +3 -0
- package/dist/login.d.ts.map +1 -1
- package/dist/login.js +8 -1
- package/dist/login.js.map +1 -1
- package/dist/offered-models.d.ts +13 -0
- package/dist/offered-models.d.ts.map +1 -0
- package/dist/offered-models.js +45 -0
- package/dist/offered-models.js.map +1 -0
- package/dist/own-settings.d.ts +12 -0
- package/dist/own-settings.d.ts.map +1 -0
- package/dist/own-settings.js +31 -0
- package/dist/own-settings.js.map +1 -0
- package/dist/questions.d.ts +6 -0
- package/dist/questions.d.ts.map +1 -0
- package/dist/questions.js +38 -0
- package/dist/questions.js.map +1 -0
- package/dist/scheduled-wakeups.d.ts +10 -0
- package/dist/scheduled-wakeups.d.ts.map +1 -0
- package/dist/scheduled-wakeups.js +30 -0
- package/dist/scheduled-wakeups.js.map +1 -0
- package/dist/sdk-install.d.ts +25 -0
- package/dist/sdk-install.d.ts.map +1 -0
- package/dist/sdk-install.js +94 -0
- package/dist/sdk-install.js.map +1 -0
- package/dist/sdk-types.d.ts +310 -0
- package/dist/sdk-types.d.ts.map +1 -0
- package/dist/sdk-types.js +8 -0
- package/dist/sdk-types.js.map +1 -0
- package/dist/subagents.d.ts +39 -0
- package/dist/subagents.d.ts.map +1 -0
- package/dist/subagents.js +114 -0
- package/dist/subagents.js.map +1 -0
- package/dist/task-list.d.ts +21 -0
- package/dist/task-list.d.ts.map +1 -0
- package/dist/task-list.js +68 -0
- package/dist/task-list.js.map +1 -0
- package/dist/translate.d.ts +57 -0
- package/dist/translate.d.ts.map +1 -0
- package/dist/translate.js +276 -0
- package/dist/translate.js.map +1 -0
- package/package.json +14 -9
- package/src/account-limit.ts +26 -0
- package/src/agent-cli.test.ts +83 -0
- package/src/agent-provider.test.ts +1156 -0
- package/src/agent-provider.ts +223 -0
- package/src/agent-session.ts +790 -0
- package/src/background-work.ts +163 -0
- package/src/constants.ts +2 -3
- package/src/event-coverage.test.ts +105 -0
- package/src/executable.test.ts +60 -0
- package/src/executable.ts +34 -0
- package/src/fake-claude.testkit.ts +376 -0
- package/src/fixtures/claude-agent-sdk-0.3.296.json +43 -0
- package/src/fixtures/claude-supported-models-0.3.296.json +218 -0
- package/src/index.test.ts +49 -0
- package/src/index.ts +61 -18
- package/src/login.ts +10 -1
- package/src/offered-models.test.ts +73 -0
- package/src/offered-models.ts +57 -0
- package/src/own-settings.test.ts +68 -0
- package/src/own-settings.ts +33 -0
- package/src/questions.test.ts +68 -0
- package/src/questions.ts +45 -0
- package/src/scheduled-wakeups.test.ts +41 -0
- package/src/scheduled-wakeups.ts +34 -0
- package/src/sdk-install.test.ts +124 -0
- package/src/sdk-install.ts +107 -0
- package/src/sdk-types.ts +277 -0
- package/src/subagents.ts +123 -0
- package/src/task-list.ts +65 -0
- package/src/translate.test.ts +439 -0
- package/src/translate.ts +280 -0
- package/dist/process.d.ts +0 -34
- package/dist/process.d.ts.map +0 -1
- package/dist/process.js +0 -197
- package/dist/process.js.map +0 -1
- package/dist/protocol.d.ts +0 -30
- package/dist/protocol.d.ts.map +0 -1
- package/dist/protocol.js +0 -368
- package/dist/protocol.js.map +0 -1
- package/dist/provider.d.ts +0 -53
- package/dist/provider.d.ts.map +0 -1
- package/dist/provider.js +0 -229
- package/dist/provider.js.map +0 -1
- package/src/process.test.ts +0 -208
- package/src/process.ts +0 -224
- package/src/protocol.ts +0 -390
- package/src/provider.test.ts +0 -671
- package/src/provider.ts +0 -267
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Claude Agent SDK lives outside Moxxy's bundle, in a folder under
|
|
3
|
+
* `~/.moxxy`, installed with the person's npm when the connection is chosen.
|
|
4
|
+
* npm is the external boundary here: a stand-in `npm` on PATH lays the
|
|
5
|
+
* package out the way npm would.
|
|
6
|
+
*/
|
|
7
|
+
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { tmpdir } from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
11
|
+
import { removeDirSync } from '@moxxy/vitest-preset/fs';
|
|
12
|
+
import { CLAUDE_AGENT_SDK_PACKAGE, ensureClaudeAgentSdk, installClaudeAgentSdk, loadClaudeAgentSdk } from './sdk-install.js';
|
|
13
|
+
|
|
14
|
+
const roots: string[] = [];
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
for (const root of roots.splice(0)) removeDirSync(root);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
function tempRoot(): string {
|
|
20
|
+
const root = mkdtempSync(path.join(tmpdir(), 'moxxy-claude-sdk-'));
|
|
21
|
+
roots.push(root);
|
|
22
|
+
return root;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Lay out the SDK package in `dir` the way npm leaves it. */
|
|
26
|
+
function writeSdk(dir: string, marker: string): void {
|
|
27
|
+
const pkg = path.join(dir, 'node_modules', ...CLAUDE_AGENT_SDK_PACKAGE.split('/'));
|
|
28
|
+
mkdirSync(pkg, { recursive: true });
|
|
29
|
+
writeFileSync(
|
|
30
|
+
path.join(pkg, 'package.json'),
|
|
31
|
+
JSON.stringify({ name: CLAUDE_AGENT_SDK_PACKAGE, type: 'module', exports: { '.': { default: './sdk.mjs' } } }),
|
|
32
|
+
);
|
|
33
|
+
writeFileSync(path.join(pkg, 'sdk.mjs'), `export const marker = ${JSON.stringify(marker)};\nexport function query() { return marker; }\n`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
describe('loading the Claude Agent SDK', () => {
|
|
37
|
+
it('loads the SDK installed in its folder', async () => {
|
|
38
|
+
const dir = tempRoot();
|
|
39
|
+
writeSdk(dir, 'loaded');
|
|
40
|
+
|
|
41
|
+
const sdk = await loadClaudeAgentSdk(dir);
|
|
42
|
+
|
|
43
|
+
expect((sdk.query as unknown as () => string)()).toBe('loaded');
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it('says what is wrong when the folder holds no SDK', async () => {
|
|
47
|
+
await expect(loadClaudeAgentSdk(tempRoot())).rejects.toThrow(/Claude Agent SDK/);
|
|
48
|
+
});
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
describe.skipIf(process.platform === 'win32')('installing the Claude Agent SDK with npm', () => {
|
|
52
|
+
/** A stand-in npm: records its arguments, then installs or fails. */
|
|
53
|
+
function fakeNpm(root: string, behaviour: 'install' | 'fail'): string {
|
|
54
|
+
const bin = path.join(root, 'bin');
|
|
55
|
+
mkdirSync(bin, { recursive: true });
|
|
56
|
+
const script = path.join(bin, 'npm');
|
|
57
|
+
writeFileSync(
|
|
58
|
+
script,
|
|
59
|
+
`#!/usr/bin/env node
|
|
60
|
+
const fs = require('node:fs'); const path = require('node:path');
|
|
61
|
+
fs.appendFileSync(${JSON.stringify(path.join(root, 'npm-calls.log'))}, JSON.stringify({ cwd: process.cwd(), args: process.argv.slice(2) }) + '\\n');
|
|
62
|
+
if (${JSON.stringify(behaviour)} === 'fail') { process.stderr.write('npm ERR! network unreachable\\n'); process.exit(1); }
|
|
63
|
+
const pkg = path.join(process.cwd(), 'node_modules', '@anthropic-ai', 'claude-agent-sdk');
|
|
64
|
+
fs.mkdirSync(pkg, { recursive: true });
|
|
65
|
+
fs.writeFileSync(path.join(pkg, 'package.json'), JSON.stringify({ name: '@anthropic-ai/claude-agent-sdk', type: 'module', main: 'sdk.mjs' }));
|
|
66
|
+
fs.writeFileSync(path.join(pkg, 'sdk.mjs'), 'export function query() { return "installed"; }\\n');
|
|
67
|
+
`,
|
|
68
|
+
);
|
|
69
|
+
chmodSync(script, 0o755);
|
|
70
|
+
return bin;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const calls = (root: string) =>
|
|
74
|
+
readFileSync(path.join(root, 'npm-calls.log'), 'utf8')
|
|
75
|
+
.trim()
|
|
76
|
+
.split('\n')
|
|
77
|
+
.map((line) => JSON.parse(line) as { cwd: string; args: string[] });
|
|
78
|
+
|
|
79
|
+
it('installs the pinned version without the bundled CLI, then loads it', async () => {
|
|
80
|
+
const root = tempRoot();
|
|
81
|
+
const pathEnv = fakeNpm(root, 'install');
|
|
82
|
+
const home = path.join(root, 'agents', 'claude-agent-sdk');
|
|
83
|
+
|
|
84
|
+
const sdk = await ensureClaudeAgentSdk({ home, version: '0.3.296', pathEnv });
|
|
85
|
+
|
|
86
|
+
expect((sdk.query as unknown as () => string)()).toBe('installed');
|
|
87
|
+
const [call] = calls(root);
|
|
88
|
+
expect(call?.args).toEqual(expect.arrayContaining(['install', '--omit=optional']));
|
|
89
|
+
const manifest = JSON.parse(readFileSync(path.join(home, '0.3.296', 'package.json'), 'utf8')) as {
|
|
90
|
+
dependencies: Record<string, string>;
|
|
91
|
+
};
|
|
92
|
+
expect(manifest.dependencies).toEqual({ [CLAUDE_AGENT_SDK_PACKAGE]: '0.3.296' });
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('does not install again once the version is there', async () => {
|
|
96
|
+
const root = tempRoot();
|
|
97
|
+
const pathEnv = fakeNpm(root, 'install');
|
|
98
|
+
const home = path.join(root, 'agents', 'claude-agent-sdk');
|
|
99
|
+
|
|
100
|
+
await installClaudeAgentSdk({ home, version: '0.3.296', pathEnv });
|
|
101
|
+
await ensureClaudeAgentSdk({ home, version: '0.3.296', pathEnv });
|
|
102
|
+
|
|
103
|
+
expect(calls(root)).toHaveLength(1);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('leaves no half-installed folder behind when npm fails, and says why', async () => {
|
|
107
|
+
const root = tempRoot();
|
|
108
|
+
const pathEnv = fakeNpm(root, 'fail');
|
|
109
|
+
const home = path.join(root, 'agents', 'claude-agent-sdk');
|
|
110
|
+
|
|
111
|
+
await expect(installClaudeAgentSdk({ home, version: '0.3.296', pathEnv })).rejects.toThrow(/network unreachable/);
|
|
112
|
+
|
|
113
|
+
expect(existsSync(path.join(home, '0.3.296'))).toBe(false);
|
|
114
|
+
expect(existsSync(home) ? readdirSync(home) : []).toEqual([]);
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('says npm is needed when there is none', async () => {
|
|
118
|
+
const root = tempRoot();
|
|
119
|
+
|
|
120
|
+
await expect(
|
|
121
|
+
installClaudeAgentSdk({ home: path.join(root, 'sdk'), version: '0.3.296', pathEnv: path.join(root, 'empty') }),
|
|
122
|
+
).rejects.toThrow(/npm/);
|
|
123
|
+
});
|
|
124
|
+
});
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { moxxyPath, resolveExecutableTarget, spawnExecutableTarget } from '@moxxy/sdk/server';
|
|
6
|
+
import type { ClaudeAgentSdk } from './sdk-types.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The Claude Agent SDK is installed with the person's npm into a folder under
|
|
10
|
+
* `~/.moxxy`, one sub-folder per version, and loaded from there at runtime:
|
|
11
|
+
* it needs zod 4 and the MCP SDK, which stay out of Moxxy's bundle. The CLI it
|
|
12
|
+
* would bring along is skipped (`--omit=optional`); Moxxy runs the person's own.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const CLAUDE_AGENT_SDK_PACKAGE = '@anthropic-ai/claude-agent-sdk';
|
|
16
|
+
export const CLAUDE_AGENT_SDK_VERSION = '0.3.296';
|
|
17
|
+
|
|
18
|
+
export interface SdkInstallOptions {
|
|
19
|
+
/** Where versions are installed; defaults to `~/.moxxy/agents/claude-agent-sdk`. */
|
|
20
|
+
readonly home?: string;
|
|
21
|
+
readonly version?: string;
|
|
22
|
+
/** PATH to find npm on (tests). */
|
|
23
|
+
readonly pathEnv?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const MAX_NPM_OUTPUT = 4096;
|
|
27
|
+
const loaded = new Map<string, Promise<ClaudeAgentSdk>>();
|
|
28
|
+
|
|
29
|
+
export function claudeAgentSdkHome(): string {
|
|
30
|
+
return moxxyPath('agents', 'claude-agent-sdk');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The SDK, installing it first when this version is not there yet. */
|
|
34
|
+
export function ensureClaudeAgentSdk(opts: SdkInstallOptions = {}): Promise<ClaudeAgentSdk> {
|
|
35
|
+
const dir = versionDir(opts);
|
|
36
|
+
const cached = loaded.get(dir);
|
|
37
|
+
if (cached) return cached;
|
|
38
|
+
const loading = (async () => {
|
|
39
|
+
if (!existsSync(dir)) await installClaudeAgentSdk(opts);
|
|
40
|
+
return loadClaudeAgentSdk(dir);
|
|
41
|
+
})();
|
|
42
|
+
loaded.set(dir, loading);
|
|
43
|
+
loading.catch(() => loaded.delete(dir));
|
|
44
|
+
return loading;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The SDK when this version is installed already; `undefined`, installing nothing, when it is not. */
|
|
48
|
+
export async function installedClaudeAgentSdk(opts: SdkInstallOptions = {}): Promise<ClaudeAgentSdk | undefined> {
|
|
49
|
+
if (!existsSync(versionDir(opts))) return undefined;
|
|
50
|
+
return ensureClaudeAgentSdk(opts);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Install into a scratch folder and move it in place only once npm succeeded. */
|
|
54
|
+
export async function installClaudeAgentSdk(opts: SdkInstallOptions = {}): Promise<void> {
|
|
55
|
+
const version = opts.version ?? CLAUDE_AGENT_SDK_VERSION;
|
|
56
|
+
const dir = versionDir(opts);
|
|
57
|
+
const npm = resolveExecutableTarget('npm', opts.pathEnv === undefined ? {} : { pathEnv: opts.pathEnv });
|
|
58
|
+
if (!npm) throw new Error('Installing the Claude Agent SDK needs npm (it comes with Node.js), and none was found on PATH.');
|
|
59
|
+
|
|
60
|
+
const partial = `${dir}.partial-${process.pid}-${Date.now()}`;
|
|
61
|
+
await mkdir(partial, { recursive: true });
|
|
62
|
+
try {
|
|
63
|
+
await writeFile(
|
|
64
|
+
path.join(partial, 'package.json'),
|
|
65
|
+
`${JSON.stringify({ name: 'moxxy-claude-agent-sdk', private: true, dependencies: { [CLAUDE_AGENT_SDK_PACKAGE]: version } }, null, 2)}\n`,
|
|
66
|
+
);
|
|
67
|
+
await runNpm(npm, partial, ['install', '--omit=optional', '--no-audit', '--no-fund', '--loglevel=error']);
|
|
68
|
+
await rename(partial, dir);
|
|
69
|
+
} catch (err) {
|
|
70
|
+
await rm(partial, { recursive: true, force: true, maxRetries: 3 });
|
|
71
|
+
throw err;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function loadClaudeAgentSdk(dir: string): Promise<ClaudeAgentSdk> {
|
|
76
|
+
const pkgDir = path.join(dir, 'node_modules', ...CLAUDE_AGENT_SDK_PACKAGE.split('/'));
|
|
77
|
+
let manifest: { main?: string; exports?: { '.'?: { default?: string; import?: string } } };
|
|
78
|
+
try {
|
|
79
|
+
manifest = JSON.parse(await readFile(path.join(pkgDir, 'package.json'), 'utf8')) as typeof manifest;
|
|
80
|
+
} catch {
|
|
81
|
+
throw new Error(`The Claude Agent SDK is not installed in ${dir}.`);
|
|
82
|
+
}
|
|
83
|
+
const root = manifest.exports?.['.'];
|
|
84
|
+
const entry = root?.import ?? root?.default ?? manifest.main ?? 'sdk.mjs';
|
|
85
|
+
const mod = (await import(pathToFileURL(path.join(pkgDir, entry)).href)) as Partial<ClaudeAgentSdk>;
|
|
86
|
+
if (typeof mod.query !== 'function') throw new Error(`The Claude Agent SDK in ${dir} has no query().`);
|
|
87
|
+
return mod as ClaudeAgentSdk;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function versionDir(opts: SdkInstallOptions): string {
|
|
91
|
+
return path.join(opts.home ?? claudeAgentSdkHome(), opts.version ?? CLAUDE_AGENT_SDK_VERSION);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function runNpm(npm: NonNullable<ReturnType<typeof resolveExecutableTarget>>, cwd: string, args: string[]): Promise<void> {
|
|
95
|
+
return new Promise((resolve, reject) => {
|
|
96
|
+
const child = spawnExecutableTarget(npm, args, { cwd, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
97
|
+
let stderr = '';
|
|
98
|
+
child.stderr?.on('data', (chunk: Buffer) => {
|
|
99
|
+
stderr = (stderr + chunk.toString('utf8')).slice(-MAX_NPM_OUTPUT);
|
|
100
|
+
});
|
|
101
|
+
child.once('error', (err) => reject(new Error(`Could not run npm: ${err.message}`)));
|
|
102
|
+
child.once('close', (code) => {
|
|
103
|
+
if (code === 0) resolve();
|
|
104
|
+
else reject(new Error(`npm could not install the Claude Agent SDK (exit ${code ?? 'signal'}): ${stderr.trim()}`));
|
|
105
|
+
});
|
|
106
|
+
});
|
|
107
|
+
}
|
package/src/sdk-types.ts
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The part of the Claude Agent SDK (`@anthropic-ai/claude-agent-sdk`) Moxxy
|
|
3
|
+
* uses, typed here because the SDK is installed into `~/.moxxy` and loaded at
|
|
4
|
+
* runtime rather than bundled (it needs zod 4; the repo is on zod 3). Shapes
|
|
5
|
+
* follow the SDK's own `sdk.d.ts` (0.3.296); fields Moxxy does not read are left out.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export type ClaudePermissionMode = 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan' | 'dontAsk' | 'auto';
|
|
9
|
+
export type ClaudeEffort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
|
|
10
|
+
|
|
11
|
+
export interface ClaudeContentBlockText {
|
|
12
|
+
readonly type: 'text';
|
|
13
|
+
readonly text: string;
|
|
14
|
+
}
|
|
15
|
+
export interface ClaudeContentBlockThinking {
|
|
16
|
+
readonly type: 'thinking';
|
|
17
|
+
readonly thinking: string;
|
|
18
|
+
}
|
|
19
|
+
export interface ClaudeContentBlockToolUse {
|
|
20
|
+
readonly type: 'tool_use';
|
|
21
|
+
readonly id: string;
|
|
22
|
+
readonly name: string;
|
|
23
|
+
readonly input: unknown;
|
|
24
|
+
}
|
|
25
|
+
export interface ClaudeContentBlockToolResult {
|
|
26
|
+
readonly type: 'tool_result';
|
|
27
|
+
readonly tool_use_id: string;
|
|
28
|
+
readonly content?: string | ReadonlyArray<{ readonly type: string; readonly text?: string }>;
|
|
29
|
+
readonly is_error?: boolean;
|
|
30
|
+
}
|
|
31
|
+
export type ClaudeContentBlock =
|
|
32
|
+
| ClaudeContentBlockText
|
|
33
|
+
| ClaudeContentBlockThinking
|
|
34
|
+
| ClaudeContentBlockToolUse
|
|
35
|
+
| ClaudeContentBlockToolResult
|
|
36
|
+
| { readonly type: string };
|
|
37
|
+
|
|
38
|
+
/** What Moxxy sends: a user message of the Messages API. */
|
|
39
|
+
export type ClaudeUserContent =
|
|
40
|
+
| string
|
|
41
|
+
| ReadonlyArray<
|
|
42
|
+
| { readonly type: 'text'; readonly text: string }
|
|
43
|
+
| { readonly type: 'image'; readonly source: { readonly type: 'base64'; readonly media_type: string; readonly data: string } }
|
|
44
|
+
| { readonly type: 'document'; readonly source: { readonly type: 'base64'; readonly media_type: string; readonly data: string } }
|
|
45
|
+
>;
|
|
46
|
+
|
|
47
|
+
export interface ClaudeUserMessage {
|
|
48
|
+
readonly type: 'user';
|
|
49
|
+
readonly message: { readonly role: 'user'; readonly content: ClaudeUserContent };
|
|
50
|
+
readonly parent_tool_use_id: null;
|
|
51
|
+
readonly origin: { readonly kind: 'human' };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface ClaudeUsage {
|
|
55
|
+
readonly input_tokens?: number;
|
|
56
|
+
readonly output_tokens?: number;
|
|
57
|
+
readonly cache_read_input_tokens?: number;
|
|
58
|
+
readonly cache_creation_input_tokens?: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** One model's share of a query (`ModelUsage`); only the fields Moxxy reads. */
|
|
62
|
+
export interface ClaudeModelUsage {
|
|
63
|
+
readonly contextWindow?: number;
|
|
64
|
+
readonly maxOutputTokens?: number;
|
|
65
|
+
/** The model id behind an alias or a provider-specific id (`claude-opus-4-7`). */
|
|
66
|
+
readonly canonicalModel?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The plan limit Claude reports for a claude.ai sign-in (absent on an API key). `resetsAt` is in epoch seconds. */
|
|
70
|
+
export interface ClaudeRateLimitInfo {
|
|
71
|
+
readonly status: 'allowed' | 'allowed_warning' | 'rejected';
|
|
72
|
+
readonly resetsAt?: number;
|
|
73
|
+
readonly rateLimitType?: string;
|
|
74
|
+
/** 0–1. */
|
|
75
|
+
readonly utilization?: number;
|
|
76
|
+
readonly overageStatus?: 'allowed' | 'allowed_warning' | 'rejected';
|
|
77
|
+
readonly isUsingOverage?: boolean;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Claude's messages Moxxy reads; others (status, hooks, task notes) arrive too and are passed over. */
|
|
81
|
+
export type ClaudeMessage =
|
|
82
|
+
| {
|
|
83
|
+
readonly type: 'system';
|
|
84
|
+
readonly subtype: 'init';
|
|
85
|
+
readonly session_id: string;
|
|
86
|
+
readonly permissionMode?: ClaudePermissionMode;
|
|
87
|
+
readonly model?: string;
|
|
88
|
+
}
|
|
89
|
+
| { readonly type: 'system'; readonly subtype: string; readonly session_id?: string }
|
|
90
|
+
| {
|
|
91
|
+
readonly type: 'assistant';
|
|
92
|
+
/** `usage` is that of the one API call the message came from. */
|
|
93
|
+
readonly message: { readonly model?: string; readonly content: ReadonlyArray<ClaudeContentBlock>; readonly usage?: ClaudeUsage };
|
|
94
|
+
readonly parent_tool_use_id: string | null;
|
|
95
|
+
readonly session_id?: string;
|
|
96
|
+
/** Set on a message Claude Code wrote itself about a failed request (`rate_limit` when the plan's limit is used up). */
|
|
97
|
+
readonly error?: string;
|
|
98
|
+
}
|
|
99
|
+
| { readonly type: 'rate_limit_event'; readonly rate_limit_info: ClaudeRateLimitInfo; readonly session_id?: string }
|
|
100
|
+
| {
|
|
101
|
+
readonly type: 'user';
|
|
102
|
+
readonly message: { readonly content: string | ReadonlyArray<ClaudeContentBlock> };
|
|
103
|
+
readonly parent_tool_use_id: string | null;
|
|
104
|
+
readonly isSynthetic?: boolean;
|
|
105
|
+
/** The tool's own output object (Edit and Write report their patch here), beside the text Claude read. */
|
|
106
|
+
readonly tool_use_result?: unknown;
|
|
107
|
+
}
|
|
108
|
+
| {
|
|
109
|
+
readonly type: 'stream_event';
|
|
110
|
+
readonly event: {
|
|
111
|
+
readonly type: string;
|
|
112
|
+
readonly delta?: { readonly type: string; readonly text?: string; readonly thinking?: string };
|
|
113
|
+
};
|
|
114
|
+
readonly parent_tool_use_id: string | null;
|
|
115
|
+
}
|
|
116
|
+
| {
|
|
117
|
+
readonly type: 'result';
|
|
118
|
+
readonly subtype: string;
|
|
119
|
+
/** Who started the turn: the person, or Claude itself after a background task. */
|
|
120
|
+
readonly origin?: { readonly kind: string };
|
|
121
|
+
readonly is_error: boolean;
|
|
122
|
+
readonly result?: string;
|
|
123
|
+
readonly session_id: string;
|
|
124
|
+
readonly stop_reason?: string | null;
|
|
125
|
+
readonly terminal_reason?: string | null;
|
|
126
|
+
readonly usage?: ClaudeUsage;
|
|
127
|
+
readonly modelUsage?: Readonly<Record<string, ClaudeModelUsage>>;
|
|
128
|
+
readonly errors?: ReadonlyArray<string>;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
export type ClaudePermissionResult =
|
|
132
|
+
| { readonly behavior: 'allow'; readonly updatedInput?: Record<string, unknown> }
|
|
133
|
+
| { readonly behavior: 'deny'; readonly message: string; readonly interrupt?: boolean };
|
|
134
|
+
|
|
135
|
+
export type ClaudeCanUseTool = (
|
|
136
|
+
toolName: string,
|
|
137
|
+
input: Record<string, unknown>,
|
|
138
|
+
options: {
|
|
139
|
+
readonly signal: AbortSignal;
|
|
140
|
+
readonly toolUseID?: string;
|
|
141
|
+
/** Set when the call comes from inside a subagent. */
|
|
142
|
+
readonly agentID?: string;
|
|
143
|
+
readonly description?: string;
|
|
144
|
+
readonly title?: string;
|
|
145
|
+
readonly mcpServer?: { readonly name: string; readonly source: string };
|
|
146
|
+
},
|
|
147
|
+
) => Promise<ClaudePermissionResult>;
|
|
148
|
+
|
|
149
|
+
export interface ClaudePreToolUseInput {
|
|
150
|
+
readonly hook_event_name: 'PreToolUse';
|
|
151
|
+
readonly tool_name: string;
|
|
152
|
+
readonly tool_input: unknown;
|
|
153
|
+
readonly tool_use_id: string;
|
|
154
|
+
/** Set when the call comes from inside a subagent. */
|
|
155
|
+
readonly agent_id?: string;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface ClaudePreToolUseOutput {
|
|
159
|
+
readonly hookSpecificOutput?: {
|
|
160
|
+
readonly hookEventName: 'PreToolUse';
|
|
161
|
+
readonly permissionDecision: 'deny';
|
|
162
|
+
readonly permissionDecisionReason: string;
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export type ClaudeHookCallback = (
|
|
167
|
+
input: ClaudePreToolUseInput,
|
|
168
|
+
toolUseID: string | undefined,
|
|
169
|
+
options: { readonly signal: AbortSignal },
|
|
170
|
+
) => Promise<ClaudePreToolUseOutput>;
|
|
171
|
+
|
|
172
|
+
/** A time Claude set itself to come back to the session (ScheduleWakeup, `/loop`, CronCreate). */
|
|
173
|
+
export interface ClaudeSessionCron {
|
|
174
|
+
readonly id: string;
|
|
175
|
+
/** A five-field cron expression; a one-shot wakeup's encodes its single fire time. */
|
|
176
|
+
readonly schedule: string;
|
|
177
|
+
readonly recurring: boolean;
|
|
178
|
+
/** What Claude is told when it fires; clipped by Claude at 1000 characters. */
|
|
179
|
+
readonly prompt: string;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Claude's `Stop` hook: it ran the turn to its end. Older Claude sends no `session_crons`. */
|
|
183
|
+
export interface ClaudeStopInput {
|
|
184
|
+
readonly hook_event_name: 'Stop';
|
|
185
|
+
readonly session_crons?: ReadonlyArray<ClaudeSessionCron>;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export type ClaudeStopHookCallback = (input: ClaudeStopInput, toolUseID: string | undefined, options: { readonly signal: AbortSignal }) => Promise<Record<string, never>>;
|
|
189
|
+
|
|
190
|
+
export interface ClaudeQueryOptions {
|
|
191
|
+
readonly cwd: string;
|
|
192
|
+
readonly model?: string;
|
|
193
|
+
readonly effort?: ClaudeEffort;
|
|
194
|
+
/** The Claude Code preset for agent turns; a plain prompt for one-off text calls. */
|
|
195
|
+
readonly systemPrompt: { readonly type: 'preset'; readonly preset: 'claude_code' } | string;
|
|
196
|
+
readonly pathToClaudeCodeExecutable?: string;
|
|
197
|
+
/** Left out to keep the mode the person set up in Claude's own settings. */
|
|
198
|
+
readonly permissionMode?: ClaudePermissionMode;
|
|
199
|
+
readonly allowDangerouslySkipPermissions?: boolean;
|
|
200
|
+
readonly maxTurns?: number;
|
|
201
|
+
readonly includePartialMessages?: boolean;
|
|
202
|
+
readonly resume?: string;
|
|
203
|
+
readonly persistSession?: boolean;
|
|
204
|
+
readonly tools?: ReadonlyArray<string>;
|
|
205
|
+
readonly settingSources?: ReadonlyArray<'user' | 'project' | 'local'>;
|
|
206
|
+
readonly mcpServers?: Record<string, { readonly type: 'http'; readonly url: string; readonly headers: Record<string, string> }>;
|
|
207
|
+
/** Only the servers in `mcpServers`: none of the person's own, claude.ai connectors included. */
|
|
208
|
+
readonly strictMcpConfig?: boolean;
|
|
209
|
+
readonly canUseTool?: ClaudeCanUseTool;
|
|
210
|
+
readonly hooks?: {
|
|
211
|
+
readonly PreToolUse?: ReadonlyArray<{ readonly hooks: ReadonlyArray<ClaudeHookCallback> }>;
|
|
212
|
+
readonly Stop?: ReadonlyArray<{ readonly hooks: ReadonlyArray<ClaudeStopHookCallback> }>;
|
|
213
|
+
};
|
|
214
|
+
readonly env?: Record<string, string | undefined>;
|
|
215
|
+
readonly stderr?: (data: string) => void;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** One of Claude's MCP servers; `status` is `connected`, `failed`, `needs-auth`, `pending` or `disabled`. */
|
|
219
|
+
export interface ClaudeMcpServerStatus {
|
|
220
|
+
readonly name: string;
|
|
221
|
+
readonly status: string;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** A skill or command Claude can run; `builtin` marks Claude Code's own. */
|
|
225
|
+
export interface ClaudeSlashCommand {
|
|
226
|
+
readonly name: string;
|
|
227
|
+
readonly description: string;
|
|
228
|
+
readonly argumentHint: string;
|
|
229
|
+
readonly aliases?: ReadonlyArray<string>;
|
|
230
|
+
readonly builtin?: boolean;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** One model of `supportedModels`: an alias row (`opus`) names the full id it stands for in `resolvedModel`. */
|
|
234
|
+
export interface ClaudeModelInfo {
|
|
235
|
+
readonly value: string;
|
|
236
|
+
readonly resolvedModel?: string;
|
|
237
|
+
readonly displayName: string;
|
|
238
|
+
readonly description: string;
|
|
239
|
+
readonly supportsEffort?: boolean;
|
|
240
|
+
readonly supportsFastMode?: boolean;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export interface ClaudeQuery extends AsyncIterable<ClaudeMessage> {
|
|
244
|
+
interrupt(): Promise<unknown>;
|
|
245
|
+
/** The skills and commands this Claude has. */
|
|
246
|
+
supportedCommands(): Promise<ClaudeSlashCommand[]>;
|
|
247
|
+
/** The models this Claude offers the signed-in account, as its own picker lists them. */
|
|
248
|
+
supportedModels(): Promise<ClaudeModelInfo[]>;
|
|
249
|
+
/** The MCP servers this Claude has, Moxxy's among them. */
|
|
250
|
+
mcpServerStatus(): Promise<ClaudeMcpServerStatus[]>;
|
|
251
|
+
setPermissionMode(mode: ClaudePermissionMode): Promise<void>;
|
|
252
|
+
setModel(model?: string): Promise<void>;
|
|
253
|
+
/** Stop one of Claude's tasks (a background command or helper); Claude then reports it stopped. */
|
|
254
|
+
stopTask(taskId: string): Promise<void>;
|
|
255
|
+
close(): void;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Claude's settings, as far as Moxxy reads them. */
|
|
259
|
+
export interface ClaudeSettings {
|
|
260
|
+
readonly permissions?: { readonly defaultMode?: ClaudePermissionMode };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** What `resolveSettings` answers: the merged settings, and each source's own. */
|
|
264
|
+
export interface ClaudeResolvedSettings {
|
|
265
|
+
readonly effective: ClaudeSettings;
|
|
266
|
+
readonly sources: ReadonlyArray<{ readonly source: string; readonly settings: ClaudeSettings }>;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export interface ClaudeAgentSdk {
|
|
270
|
+
query(params: { prompt: string | AsyncIterable<ClaudeUserMessage>; options: ClaudeQueryOptions }): ClaudeQuery;
|
|
271
|
+
/** One of Claude's saved sessions, searched across every project; `undefined` when it no longer exists. */
|
|
272
|
+
getSessionInfo?(sessionId: string): Promise<{ readonly sessionId: string } | undefined>;
|
|
273
|
+
/** The person's Claude settings for a folder, merged the way Claude merges them. */
|
|
274
|
+
resolveSettings?(opts?: { readonly cwd?: string }): Promise<ClaudeResolvedSettings>;
|
|
275
|
+
/** Drops an escalating `defaultMode` a repository's settings set, as Claude does before honoring it. */
|
|
276
|
+
filterEscalatingDefaultMode?(resolved: ClaudeResolvedSettings): ClaudeSettings;
|
|
277
|
+
}
|
package/src/subagents.ts
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import type { AgentStepEvent } from '@moxxy/sdk';
|
|
2
|
+
|
|
3
|
+
/** Claude's tool that starts a subagent: `Agent` in Claude Code 2.1, `Task` before. */
|
|
4
|
+
const SUBAGENT_TOOLS: ReadonlySet<string> = new Set(['Agent', 'Task']);
|
|
5
|
+
|
|
6
|
+
interface Running {
|
|
7
|
+
text: string;
|
|
8
|
+
tokens: number | undefined;
|
|
9
|
+
/** Claude went on without waiting for it; only its task note ends it. */
|
|
10
|
+
background: boolean;
|
|
11
|
+
done: boolean;
|
|
12
|
+
/** What it said, each shown once: a message read between turns comes again in the next turn. */
|
|
13
|
+
readonly said: Set<string>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Claude's subagents. The call that starts one is shown as the subagent; its own calls carry
|
|
18
|
+
* the starting call's id (`parent_tool_use_id`) and show under it. One running in the background
|
|
19
|
+
* ends later, when Claude reports its task finished, so the session keeps them across turns.
|
|
20
|
+
*/
|
|
21
|
+
export class ClaudeSubagents {
|
|
22
|
+
private readonly agents = new Map<string, Running>();
|
|
23
|
+
/** A subagent's call → the subagent it belongs to. */
|
|
24
|
+
private readonly calls = new Map<string, string>();
|
|
25
|
+
|
|
26
|
+
isSubagentTool(name: string): boolean {
|
|
27
|
+
return SUBAGENT_TOOLS.has(name);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Whether a call started a subagent. */
|
|
31
|
+
isSubagent(callId: string): boolean {
|
|
32
|
+
return this.agents.has(callId);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The subagent a call belongs to, if it is a subagent's call. */
|
|
36
|
+
ownerOf(callId: string): string | undefined {
|
|
37
|
+
return this.calls.get(callId);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
started(callId: string, input: unknown): AgentStepEvent[] {
|
|
41
|
+
if (this.agents.has(callId)) return [];
|
|
42
|
+
this.agents.set(callId, { text: '', tokens: undefined, background: false, done: false, said: new Set() });
|
|
43
|
+
const fields = typeof input === 'object' && input !== null ? (input as Record<string, unknown>) : {};
|
|
44
|
+
const label = typeof fields.description === 'string' && fields.description ? fields.description : 'subagent';
|
|
45
|
+
const agentType = typeof fields.subagent_type === 'string' && fields.subagent_type ? fields.subagent_type : 'general-purpose';
|
|
46
|
+
const prompt = typeof fields.prompt === 'string' && fields.prompt ? fields.prompt : undefined;
|
|
47
|
+
return [{ type: 'subagent_started', id: callId, label, agentType, ...(prompt ? { prompt } : {}) }];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** What a subagent said and called, from one of its messages; each once, however often the message is read. */
|
|
51
|
+
fromMessage(parent: string, text: string, calls: ReadonlyArray<{ readonly id: string; readonly name: string; readonly input: unknown }>): AgentStepEvent[] {
|
|
52
|
+
const agent = this.agents.get(parent);
|
|
53
|
+
if (!agent || agent.done) return [];
|
|
54
|
+
const events: AgentStepEvent[] = [];
|
|
55
|
+
if (text) {
|
|
56
|
+
agent.text = text;
|
|
57
|
+
if (!agent.said.has(text)) events.push({ type: 'subagent_message', id: parent, text });
|
|
58
|
+
agent.said.add(text);
|
|
59
|
+
}
|
|
60
|
+
for (const call of calls) {
|
|
61
|
+
if (this.calls.has(call.id)) continue;
|
|
62
|
+
this.calls.set(call.id, parent);
|
|
63
|
+
events.push({ type: 'subagent_tool_call', id: parent, name: call.name, input: call.input });
|
|
64
|
+
}
|
|
65
|
+
return events;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The result of the call that started a subagent: its answer, unless it went on in the background.
|
|
70
|
+
* The result Claude's model reads wraps the answer in a hand-back note, so the report's own text is preferred.
|
|
71
|
+
*/
|
|
72
|
+
fromResult(callId: string, text: string, isError: boolean, report: unknown): AgentStepEvent[] {
|
|
73
|
+
const r = typeof report === 'object' && report !== null ? (report as { isAsync?: unknown; totalTokens?: unknown; content?: unknown }) : {};
|
|
74
|
+
if (r.isAsync === true && !isError) {
|
|
75
|
+
const agent = this.agents.get(callId);
|
|
76
|
+
if (agent) agent.background = true;
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
if (isError) return this.end(callId, { text: '', error: text });
|
|
80
|
+
const answer = reportText(r.content) || text || this.textOf(callId);
|
|
81
|
+
return this.end(callId, { text: answer, ...(typeof r.totalTokens === 'number' ? { tokens: r.totalTokens } : {}) });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Claude's task reports: progress (tokens so far) and the end of a subagent in the background. */
|
|
85
|
+
fromTaskNote(note: { readonly subtype: string; readonly tool_use_id?: unknown; readonly status?: unknown; readonly summary?: unknown; readonly usage?: unknown }): AgentStepEvent[] {
|
|
86
|
+
if (typeof note.tool_use_id !== 'string') return [];
|
|
87
|
+
const agent = this.agents.get(note.tool_use_id);
|
|
88
|
+
if (!agent) return [];
|
|
89
|
+
if (note.subtype === 'task_progress') {
|
|
90
|
+
const usage = note.usage as { total_tokens?: unknown } | undefined;
|
|
91
|
+
if (usage && typeof usage.total_tokens === 'number') agent.tokens = usage.total_tokens;
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
// A subagent Claude waited for ends with the call's result, which carries its answer.
|
|
95
|
+
if (note.subtype !== 'task_notification' || !agent.background) return [];
|
|
96
|
+
if (note.status === 'completed') return this.end(note.tool_use_id, { text: agent.text || (typeof note.summary === 'string' ? note.summary : '') });
|
|
97
|
+
const reason = typeof note.summary === 'string' && note.summary ? note.summary : `The subagent ${typeof note.status === 'string' ? note.status : 'stopped'}.`;
|
|
98
|
+
return this.end(note.tool_use_id, { text: '', error: reason, stopped: note.status === 'stopped' });
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
private textOf(callId: string): string {
|
|
102
|
+
const agent = this.agents.get(callId);
|
|
103
|
+
return agent ? agent.text : '';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
private end(callId: string, outcome: { readonly text: string; readonly tokens?: number; readonly error?: string; readonly stopped?: boolean }): AgentStepEvent[] {
|
|
107
|
+
const agent = this.agents.get(callId);
|
|
108
|
+
if (!agent || agent.done) return [];
|
|
109
|
+
agent.done = true;
|
|
110
|
+
const tokens = outcome.tokens ?? agent.tokens;
|
|
111
|
+
return [{ type: 'subagent_completed', id: callId, text: outcome.text, ...(tokens !== undefined ? { tokensUsed: tokens } : {}), ...(outcome.error ? { error: outcome.error } : {}), ...(outcome.stopped ? { stopped: true as const } : {}) }];
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function reportText(content: unknown): string {
|
|
116
|
+
if (!Array.isArray(content)) return '';
|
|
117
|
+
return content
|
|
118
|
+
.flatMap((part: unknown) => {
|
|
119
|
+
const p = typeof part === 'object' && part !== null ? (part as { type?: unknown; text?: unknown }) : {};
|
|
120
|
+
return p.type === 'text' && typeof p.text === 'string' && p.text ? [p.text] : [];
|
|
121
|
+
})
|
|
122
|
+
.join('\n');
|
|
123
|
+
}
|