-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude-code.ts
More file actions
246 lines (217 loc) · 7.83 KB
/
claude-code.ts
File metadata and controls
246 lines (217 loc) · 7.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import {
CodifyCliSender,
CreatePlan,
DestroyPlan,
ExampleConfig,
ModifyPlan,
ParameterChange,
Resource,
ResourceSettings,
getPty,
z,
} from '@codifycli/plugin-core';
import { OS } from '@codifycli/schemas';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { McpServersParameter } from './mcp-servers-parameter.js';
import { SettingsParameter } from './settings-parameter.js';
const CLAUDE_DIR = path.join(os.homedir(), '.claude');
const CLAUDE_MD_PATH = path.join(CLAUDE_DIR, 'CLAUDE.md');
const mcpStdioServerSchema = z.object({
name: z.string().describe('Unique name for this MCP server'),
type: z.literal('stdio'),
command: z.string().describe('Executable or command to launch the server process'),
args: z.array(z.string()).optional().describe('Arguments to pass to the command'),
env: z.record(z.string(), z.string()).optional().describe('Environment variables for the server process'),
});
const mcpHttpServerSchema = z.object({
name: z.string().describe('Unique name for this MCP server'),
type: z.literal('http'),
url: z.string().describe('URL of the HTTP (streamable-http) MCP server'),
headers: z.record(z.string(), z.string()).optional().describe('HTTP headers sent with every request'),
});
const mcpSseServerSchema = z.object({
name: z.string().describe('Unique name for this MCP server'),
type: z.literal('sse'),
url: z.string().describe('URL of the SSE MCP server (deprecated transport; prefer http)'),
headers: z.record(z.string(), z.string()).optional().describe('HTTP headers sent with every request'),
});
export const mcpServerSchema = z.discriminatedUnion('type', [
mcpStdioServerSchema,
mcpHttpServerSchema,
mcpSseServerSchema,
]);
export type McpServer = z.infer<typeof mcpServerSchema>;
const schema = z
.object({
globalClaudeMd: z
.string()
.optional()
.describe(
'Content for ~/.claude/CLAUDE.md. Accepts inline text, an https:// URL, or a ' +
'codify:// cloud URL (e.g. codify://documentId:fileId). Claude Code reads this at ' +
'the start of every session.',
),
settings: z
.record(z.string(), z.unknown())
.optional()
.describe(
'Settings to merge into ~/.claude/settings.json. Supports model, effortLevel, ' +
'editorMode, permissions, env, hooks, and all other Claude Code settings.',
),
mcpServers: z
.array(mcpServerSchema)
.optional()
.describe('MCP servers to register globally in ~/.claude.json.'),
})
.meta({ $comment: 'https://codifycli.com/docs/resources/claude-code/claude-code' })
.describe('Claude Code installation and configuration management');
export type ClaudeCodeConfig = z.infer<typeof schema>;
const defaultConfig: Partial<ClaudeCodeConfig> = {
mcpServers: [],
};
const exampleSettings: ExampleConfig = {
title: 'Claude Code with custom settings',
description: 'Install Claude Code and configure model selection, editor mode, and shell permissions.',
configs: [
{
type: 'claude-code',
settings: {
model: 'claude-opus-4-7',
effortLevel: 'high',
editorMode: 'vim',
permissions: {
allow: ['Bash(npm run *)', 'Bash(git *)'],
deny: ['Bash(rm -rf *)'],
},
},
},
],
};
const exampleWithMcp: ExampleConfig = {
title: 'Claude Code with global instructions and MCP',
description: 'Install Claude Code, set global instructions via CLAUDE.md, and wire up an MCP server.',
configs: [
{
type: 'claude-code',
globalClaudeMd:
'# Global Instructions\n\nAlways follow security best practices.\nPrefer TypeScript over JavaScript.',
mcpServers: [
{
name: 'filesystem',
type: 'stdio',
command: 'npx',
args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'],
},
],
},
],
};
export class ClaudeCodeResource extends Resource<ClaudeCodeConfig> {
getSettings(): ResourceSettings<ClaudeCodeConfig> {
return {
id: 'claude-code',
defaultConfig,
exampleConfigs: {
example1: exampleSettings,
example2: exampleWithMcp,
},
operatingSystems: [OS.Darwin, OS.Linux],
schema,
parameterSettings: {
globalClaudeMd: { canModify: true },
settings: { type: 'stateful', definition: new SettingsParameter(), order: 1 },
mcpServers: { type: 'stateful', definition: new McpServersParameter(), order: 2 },
},
};
}
async refresh(parameters: Partial<ClaudeCodeConfig>): Promise<Partial<ClaudeCodeConfig> | null> {
const claudeBin = path.join(os.homedir(), '.local', 'bin', 'claude');
try {
await fs.access(claudeBin);
} catch {
return null;
}
const result: Partial<ClaudeCodeConfig> = {};
if (parameters.globalClaudeMd != null) {
if (isRemoteUrl(parameters.globalClaudeMd)) {
result.globalClaudeMd = parameters.globalClaudeMd;
} else {
try {
result.globalClaudeMd = await fs.readFile(CLAUDE_MD_PATH, 'utf8');
} catch {
result.globalClaudeMd = undefined;
}
}
}
return result;
}
async create(plan: CreatePlan<ClaudeCodeConfig>): Promise<void> {
const $ = getPty();
await $.spawn(
'bash -c "curl -fsSL https://claude.ai/install.sh | bash"',
{ interactive: true },
);
// Ensure PATH is updated so subsequent lifecycle methods can call `claude`
const localBin = path.join(os.homedir(), '.local', 'bin');
process.env['PATH'] = `${localBin}:${process.env['PATH'] ?? ''}`;
if (plan.desiredConfig.globalClaudeMd) {
await this.writeClaudeMd(plan.desiredConfig.globalClaudeMd);
}
}
async modify(
pc: ParameterChange<ClaudeCodeConfig>,
plan: ModifyPlan<ClaudeCodeConfig>,
): Promise<void> {
if (pc.name === 'globalClaudeMd') {
const newValue = plan.desiredConfig.globalClaudeMd;
if (newValue) {
await this.writeClaudeMd(newValue);
} else {
await fs.rm(CLAUDE_MD_PATH, { force: true });
}
}
}
async destroy(plan: DestroyPlan<ClaudeCodeConfig>): Promise<void> {
if (plan.currentConfig.globalClaudeMd) {
await fs.rm(CLAUDE_MD_PATH, { force: true });
}
// Native uninstall: remove the binary and version files
await fs.rm(path.join(os.homedir(), '.local', 'bin', 'claude'), { force: true });
await fs.rm(path.join(os.homedir(), '.local', 'share', 'claude'), { recursive: true, force: true });
}
private async writeClaudeMd(content: string): Promise<void> {
await fs.mkdir(CLAUDE_DIR, { recursive: true });
const resolved = await resolveClaudeMdContent(content);
await fs.writeFile(CLAUDE_MD_PATH, resolved, 'utf8');
}
}
function isRemoteUrl(value: string): boolean {
return value.startsWith('https://') || value.startsWith('http://') || value.startsWith('codify://');
}
async function resolveClaudeMdContent(content: string): Promise<string> {
if (content.startsWith('codify://')) {
const regex = /codify:\/\/(.*):(.*)/;
const [, documentId, fileId] = regex.exec(content) ?? [];
if (!documentId || !fileId) {
throw new Error(`Invalid codify URL for claudeMd: ${content}`);
}
const credentials = await CodifyCliSender.getCodifyCliCredentials();
const response = await fetch(`https://api.codifycli.com/v1/documents/${documentId}/file/${fileId}`, {
headers: { Authorization: `Bearer ${credentials}` },
});
if (!response.ok) {
throw new Error(`Failed to fetch claudeMd from ${content}: ${response.statusText}`);
}
return response.text();
}
if (content.startsWith('https://') || content.startsWith('http://')) {
const response = await fetch(content);
if (!response.ok) {
throw new Error(`Failed to fetch claudeMd from ${content}: ${response.statusText}`);
}
return response.text();
}
return content;
}